how to pass two quries in UserManager in variable
var completedTask = await Task.WhenAny(_userManager.FindByNameAsync(userForLoginDto.UserName), _userManager.FindByIdAsync(userForLoginDto.Id));
var user = await completedTask;
var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);
i found new error System.InvalidOperationException: A second operation started on this context before a previous operation completed.
See also questions close to this topic
-
How can I determine the correct zoom level for Bing Maps when there is only one pushpin?
I add a number of pushpins to a map and then "rightsize" or "right zoom" it so that all the pushpins show but so that the ones on the far edges are barely within the boundaries, like so:
However, if there is only one pushpin (as in the following case with Iowa, which only had the one civil war battle), rather than zero in on that as close as possible, it zooms out all the way to Skylab, like so:
This is the code I use to "right size" the map:
private void RightsizeZoomLevelForAllPushpins() { try { // Set the view so that all pushpins are displayed, with a bit of a margin around them // from https://stackoverflow.com/questions/65779504/how-to-set-the-zoom-level-of-bing-map-to-just-wide-enough-to-display-all-pushpin/65781319#65781319 var map = this.userControl11.myMap; var locations = map.Children.OfType<Pushpin>().Select(x => x.Location); //Margin var w = new Pushpin().Width; var h = new Pushpin().Height; var margin = new Thickness(w / 2, h, w / 2, 0); //Set view map.SetView(locations, margin, 0); currentZoomLevel = Convert.ToInt32(map.ZoomLevel); UncheckAllZoomLevelToolstripMenuItems(); SetZoomMenuItem(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
How can I get a one-pushpin map to not only center, but also zoom in as far as possible?
-
C#: calling methods with multiple objects as parameters from other classes
I am wondering whether it is possible to call methods with
objects
as parameters from otherclasses
without using to many parameters.In detail: how can you call method
Info.Status()
insideclass Car
?Extending parameters to
MethodA(Location location1, Location location2, Garage garage1, Car car1)
would do the trick.
BUT whenever you use
MethodA()
somewhere else, you always have to deal with all parameters and objects, just because of the methodInfo.Status()
in it, that needs the additional parameters.Or is it a lack of structure of my code and you need other principles (out, Interface, ...) ?
And where you should create the
objects
location1, location2, garage1 and car1 ? InMain
?Lovely greetings from Germany,
Laurapublic class Location { } public class Garage {} public class Car { public void MethodA(Location location1, Location location2) { // method doing stuff with objects location1 and location2 // now calling method Info.Status() to get some status information } } public static class Info { public static void Status(Location location1, Location location2, Garage garage1, Car car1) { // method to print out some values and properties of objects location1, location2, // garage1 and car1 } }
-
I am trying to create a Notepad application in C# that uses a SQL database. How to cross references users with another table?
I am trying to create a Notepad application in C# that uses a SQL database to allow users to log in and access previously-stored notes. How would I go about this? I am trying to develop an application that will work locally on someone's computer but can log in with different usernames and passwords to store different notes. For example, bobPersonal123 has 20 different notes, where each note has a Title, Message, and Picture. Bob also has a work account, bobWork123, that has a different set of notes, let's say 15, each with a Title, Message, and Picture. I know how to use a separate SQL table for each aspect, logging in with different accounts and storing 20 different Title, Message, and Pictures, but how would I be able to allow a specific user to access a specific table of notes once logged in? Would I essentially need to create a table within a table? Or is there a way to create a column for bobPersonal vs bobWork that contains some sort of reference to another table? If so, how do you create references to other tables?
Sorry if this question has a fairly obvious answer as I've only just begun using SQL. Thanks in advance.
-
getting prob on reading nested class c#
Hi really need assistance here,
I have 2 classes which i use to read from json i need to save into 2 tables (root and participants) in 1 submission. i will have only 1 root with 1 or many participants. i have no prob saving the root but i have prob reading if i am sending both (root with participants}
[ { "NoIC": "122233243", "Nama": "TEST NAME", ... "Participant": [ { "Nama" : "Participant 1", "Bil" : "1", ... }, { "Nama" : "Participant 2", "Bil" : "1", .... } ] } ] public class Participant { public string ref_no { get; set; } public string Nama { get; set; } public string Bil { get; set; } public string Price { get; set; } public string RequestedPlace { get; set; } public string RequestedExe { get; set; } public string RequestedDate { get; set; } public string Type { get; set; } } public class Root { public string NoIC { get; set; } public string Nama { get; set; } public string HPNo { get; set; } public string Email { get; set; } public string Type { get; set; } public string RegisterBy { get; set; } public List<Participant> Participant { get; set; } } public string RegisterApplication([FromBody] Root register, Participant participants) { try { using (MySqlConnection sql = new MySqlConnection(_connectionString)) { using (MySqlCommand cmd = new MySqlCommand("GetInsertApplication", sql)) { sql.Open(); cmd.CommandType = System.Data.CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("@refNo", register.RefNo); cmd.Parameters.AddWithValue("@NoIC", register.NoIC); cmd.Parameters.AddWithValue("@Nama", register.Nama.ToUpper()); cmd.Parameters.AddWithValue("@NoFonHp", register.HPNo); cmd.Parameters.AddWithValue("@Email", register.Email); cmd.Parameters.AddWithValue("@refType", register.Type); cmd.Parameters.AddWithValue("@RegisterBy", register.RegisterBy); ...... ref_no = refnoParameter.Value.ToString(); //will pass this refno to child/participant
my prob is here. i need to read the child (1 Root can have more than 1 participant)
List<Participant> participants = new List<Participant>(); using (MySqlCommand cmd2 = new MySqlCommand("GetInsertParticipant", sql)) { cmd2.Parameters.AddWithValue("@ref_no", ref_no); cmd2.Parameters.AddWithValue("@Nama", participant.Nama.ToUpper()); cmd2.Parameters.AddWithValue("@Bil", participant.Bil); cmd2.Parameters.AddWithValue("@Price", participant.Price); cmd2.Parameters.AddWithValue("@RequestedPlace", participant.RequestedPlace); cmd2.Parameters.AddWithValue("@RequestedExe", participant.RequestedExe); cmd2.Parameters.AddWithValue("@RequestedDate", participant.RequestedDate); cmd2.Parameters.AddWithValue("@Type", participant.Type); cmd2.Connection.Open(); cmd2.CommandType = CommandType.Text; cmd2.ExecuteNonQuery();
}}}}}
anybody please, i stuck here for few days and i really need your help/opinion. thaks in advanced
-
How do I insert input from form to database?
My model looks like this:
public class Customer { public int CustomerId { get; set; } [Required(ErrorMessage = "Please enter a valid first name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter a valid last name")] public string LastName { get; set; } [Required(ErrorMessage = "Please enter a valid address")] public string Address { get; set; } public string Email { get; set; } [Required(ErrorMessage = "Please enter a valid city")] public string City { get; set; } public string Phone { get; set; } [Range(1, 5, ErrorMessage = "Please enter a valid country")] public int CountryId { get; set; } public Country Country { get; set; } [Required(ErrorMessage = "Please enter a valid state")] public string State { get; set; } [Required(ErrorMessage = "Please enter a valid postal code")] public string PostalCode { get; set; } public string fullname => FirstName + LastName; }
My controller looks like this:
public class CustomerController : Controller { private CustomerContext context { get; set; } public CustomerController(CustomerContext ctx) { context = ctx; } public IActionResult List() { var customers = context.Customers.ToList(); return View(customers); } [HttpGet] public IActionResult Add() { ViewBag.Action = "Add"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View("Edit", new Customer()); } [HttpGet] public IActionResult Edit(int id) { ViewBag.Action = "Edit"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); var customer = context.Customers .Include(c => c.Country) .FirstOrDefault(c => c.CustomerId == id); return View(customer); } [HttpPost] public IActionResult Edit(Customer customer) { string action = (customer.CustomerId == 0) ? "Add" : "Edit"; if (ModelState.IsValid) { if (action == "Add") { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); return RedirectToAction("List", "Customer"); } else { ViewBag.Action = action; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View(customer); } }
I also have a DbContext file with data i created to test other things:
public class CustomerContext : DbContext { public CustomerContext(DbContextOptions<CustomerContext> options) :base(options) { } public DbSet<Customer> Customers { get; set; } public DbSet<Country> Countries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Country>().HasData( new Country { CountryId = 1, Name = "Canada"}, new Country { CountryId = 2, Name = "United States"}, new Country { CountryId = 3, Name = "United Kingdom" }, new Country { CountryId = 4, Name = "Mexico" }, new Country { CountryId = 5, Name = "Russia" } ); modelBuilder.Entity<Customer>().HasData( new Customer { CustomerId = 1, FirstName = "Bruce", LastName = "Wayne", Phone = "416-123-4567", Email = "bruce.wayne@gmail.com", CountryId = 1, Address = "123 sesame street", City = "Toronto", PostalCode = "L812A", State = "Ontario" } ); }
I already did the add-migration and updated my database via the package manager console. I created a form in the view that looks like this:
Cancel<form method="post" asp-action="Add"> <div asp-validation-summary="All"> <div> <label asp-for="FirstName">First Name</label> <input type="text" name="FirstName" asp-for="FirstName" /> </div> <div> <label asp-for="LastName">Last Name</label> <input type="text" name="LastName" asp-for="LastName" /> </div> <div> <label asp-for="Address">Address</label> <input type="text" name="Address" asp-for="Address" /> </div> <div> <label asp-for="City">City</label> <input type="text" name="City" asp-for="City" /> </div> <div> <label asp-for="State">State</label> <input type="text" name="State" asp-for="State" /> </div> <div> <label asp-for="PostalCode">Postal Code</label> <input type="text" name="Postal Code" asp-for="PostalCode" /> </div> <div> <label asp-for="CountryId">Country</label> <select name="Country" asp-for="CountryId"> @foreach (Country country in ViewBag.Countries) { <option value="@country.CountryId">@country.Name</option> } </select> </div> <div> <label asp-for="Email">Email</label> <input type="text" name="Email" asp-for="Email" /> </div> <div> <label asp-for="Phone">Phone</label> <input type="text" name="Phone" asp-for="Phone" /> </div> <input type="hidden" asp-for="CustomerId" /> </div> <button type="submit" value="Save" asp-controller="Customer" asp-action="List">Save</button>
I've tried looking up multiple different solutions to solve my issue but I cant seem to figure out how to solve it. If someone could help me that would be much appreciated. thanks in advance.
-
Submit button doenst work with script asp.net mvc5
I have a maybe simple problem but I don`t have that much experience with scripts:
I have this Skript in my _Layout.cshtml:
<script> $('button').click(function () { $(this).prop('disabled', true); }); </script>
and one of my views:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, null)) { @Html.AntiForgeryToken() <div class="mt-5 d-flex flex-row"> <textarea class="form-control" name="TextArea"></textarea> <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button> </div> }
This form works great without the script, but for any reason with the script it doesn`t work.
I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.
After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.
I think I need to extend the script but can someone help me how to do it?
Thanks all
-
Authenticate users on AWS Cognito with OpenId Connect (OKTA) for .Net Core 3.x
I have a .net core 3.x web API that authenticates users on aws cognito in the cognito userpool. AWSSDK provides good support for that.
I have to extend my application support to include okta (openId Connect) users via cognito. I have already synced up the users and I can authenticate them successfully using the default UI provided by cognito.
I am not able to find any examples/documentation on how I can authenticate these users on OKTA (openId-connect) via an API call from my application. I am using postman to call my API authenticate endpoints.
Is there any way I can make a postman call to the cognito/openId connect (send user creds in the body/request) and authenticate the user to get the jwt token back in response in?
Most examples I found are old .net core 2.0 and earlier and they use mvc and razor page.
Thank you RDG
-
ASP.Net 5 Web API: Use own Login / Token system?
Is it really a bad idea to create a own Login system with tokens? I know there are built in identity services in .NET and for a token based authentification nearly everyone says "Jwt"... But I prefer to do as much as possible by my own, so I understand what (my) code is doing and can easily customize things.
This is my general idea for a login system with blazor (.net hosted), other login systems like google & co are NOT planned:
- Public API endpoint "API/Login" with params "username" and "password"
- The client (Blazor App for example) sends user and hashed password and encrypts both (so sniffers can't read anything, SSL will be on top ofc)
- The server decrypts this information by a shared key
- The server checks the database for the user and password-hash combination
- If user/password was correct (found), a generated API Key / Token will be generated (for an easy example, a new Guid, but not the UserId)
- The client saves this API Key / Token (localstorage for example)
- The client sends the API Key / Token on every web API request via the headers
The simplyfied code could be (NOT tested, just pseudo):
API-Controller:
[HttpPost] [Route("API/Login")] public string Login(string username, string passwordHash) { if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(passwordHash)) { var user = context.Users.Where(u => u.Username = username && u.PasswordHash = passwordHash && u.TokenExpires > DateTime.Now).FirstOrDefault(); if (user != null) { string exampleToken = Guid.NewGuid().ToString(); user.Token = exampleToken; context.Users.Update(user); context.SaveChanges(); return exampleToken; } } return null; } [HttpGet] [Route("API/WeatherForecast")] public IEnumerable<WeatherForecast> Get() { var customToken = Request.Headers["CustomToken"].FirstOrDefault(); if (customToken != null && context.Users.Where(u => u.Token == customToken)) { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } return null; }
API-Call:
protected override async Task OnInitializedAsync() { Http.DefaultRequestHeaders.Add("CustomToken", "000b5244-9477-4119-8456-8451b197d61f"); forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast"); }
What I DONT like with the default security approaches:
- For me hard to understand, just too much code / services / options (it's more a "blackbox" for me) for a "simple" login
- Hard to customize without changing all the services
- Hackers will try to check security issues for the most common security setups (they don't know much about my security system, if I use a custom one)
Maybe I did miss something... What are the big cons for a custom security system?
-
how to show country-wise search results from single db in dotnet application
i am developing a web app for used goods buy and sale and the site will be launched in few countries. But i am stuck on how to architect the db for displaying the search results countrywise from the same website and same SQL db when people search a product. Thanks a lot for your help.