How can I do this manually for an application which was not configured for an individual accounts authentication and authorization ?
Adding ASP.NET Core Identity service to an Existing ASP.NET Core 2.2 , EF Core Razor Web application
beginner level question about menus
I have a second menu that I would like to display when any one of five pages are loaded.
I currently display it as shown below. Isn't there a way to display second menu that doesn't require changes in all five places if I were to change it?
(I have two more second menus with different content to do and would like to do them correctly.
It would be something that would know to load right after the _LayoutPage.
<div><partial name="partials/_RowTwoMenu" /></div>
How to run 2 services in one time.
Hi,
1. I have 2 different services that running with .AddSingleton during server start up. Here is the example in Startup.cs
services.AddSingleton<LiveDataProvider>();
services.AddSingleton<IHostedService, RefreshService>();
services.AddSingleton<SimulationDataProvider>();
services.AddSingleton<IHostedService, SimulationRefreshService>();
2. My problem here is that the services seems to not running with this setup. I wonder what to do if I want these both services running as usual. I think there must be something with the .AddSingleton.
Thanks.
Serve multiple angular spa from a single core web application
The name is invalid because it is a reserved name in Razor page
I was trying to add a razor page named as 'Add&EditPerson'. but i was given an error 'The name is invalid because it is a reserved name'. but i couldn't find any reference from the library named as this name. So what are the references for this name or how can i find out reserved names as a list ?
Why asp.net core threws Endpoint Routing error?
I followed the tutorial in https://www.youtube.com/watch?v=aIkpVzqLuhA to create Web APIs.
Here is the code the same as the tutorial:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.Run(async (context) =>
{
await context.Response.WriteAsync("abc");
});
}
}
}
However, after I ran the program, visual studio threw an error:
System.InvalidOperationException: 'Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...).'
Why it turns out to be this? The code is all the same as the tutorial. The tutorial runs without error but not do I.
What's more, I am using the .net core 3.0 preview 6 now.
Get Current User Role
How can I get the current user role which just logged in?
.NET Core Package Manager Console hangs when trying to perform Add-Migration
When I want to add an migration, these are the steps that I perform before typing the add-migration command:
- $env:CENTRAL_APPLICATION_SETTINGS="C:\Users\amosa\source\repos\DotNetCore\CentralApplicationSettings\CentralApplicationSettings"
- $env:DOCUMENT_STUDIO_CONNECTIONSTRING="Server=.\SQLEXPRESS;Database=DBONE;Trusted_Connection=False;MultipleActiveResultSets=true;User Id=user;Password=password"
- $env:DOCUMENT_STUDIO_DSSCHEMA="DocumentStudio"
- $env:ASPNETCORE_ENVIRONMENT="Development"
Add-Migration DocumentStudioBaseMigration -Context DocumentStudioDbContext -OutputDir Migrations\DocumentStudioMigrations
This is the dbcontext file that I use:
publicDocumentStudioDbContext(DbContextOptions<DocumentStudioDbContext> options):base(options){}publicDbSet<Documents>Documents{ get;set;}publicDbSet<DocumentCategories>DocumentCategories{ get;set;}publicDbSet<DocumentFields>DocumentFields{ get;set;}publicDbSet<DocumentFieldsStore>DocumentFieldsStore{ get;set;}publicDbSet<DocumentFieldPermissions>DocumentFieldPermissions{ get;set;}protectedoverridevoidOnModelCreating(ModelBuilder modelBuilder){
modelBuilder.HasDefaultSchema(schema:Environment.GetEnvironmentVariable(DSCASGlobals.DS_DatabaseSchema));base.OnModelCreating(modelBuilder);}
When I enter the add-migration part, my package manager just hangs and does nothing. I have never encountered this issue before and it seems like nothing is happening.
CPU usages 100%
We have one console application build using .net 2.1 and we are running this as window service
Ajax request don't give alert ASP.NET Core 2.2 Razor page.
Saving server request is success. but it doesn't provide alert and dynamic textboxes weredisappeared. Are there any configurations issues or version problems ?
AddOrEditPerson.cshtml
@page "{Id?}"
@model Users.Pages.AddOrEditPersonModel
@{
ViewData["Title"] = "AddOrEditPerson";
Layout = "~/Pages/Shared/_Layout.cshtml";
ViewData["Title"] = Model.IsNewUser ? "New User" : "Edit User";
}
<form method="post" enctype="multipart/form-data">
<div class="col-md-10">
<div class="col-md-7 mb-3">
<input type="text" name="txtContact" asp-for="Person.Contacts" class="form-control" />
</div>
<div class="col-md-3 mb-3">
<input type="button" class="btn btn-primary" onclick="AddTextBox()" value="Add More" />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<button class="btn btn-primary" id="submit">Save</button>
<button class="btn btn-primary" asp-page-handler="Delete" id="delete">Delete</button>
</div>
</div>
</form>
<script>$(function () {$('#submit').on('click', function (evt) { evt.preventDefault();$.ajax({ url: '', data: new FormData(document.forms[0]), contentType: false, processData: false, type: 'post', success: function () { alert('Uploaded by jQuery'); } }); }); }); $(function () {$('#delete').on('click', function (evt) { evt.preventDefault();$.ajax({ url: 'Admin/AddOrEditPerson?handler=Delete', data: new FormData(document.forms[0]), contentType: false, processData: false, type: 'post', success: function () { alert('Uploaded by jQuery'); } }); }); }</script>
_Layout.cshtml
<!DOCTYPE html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>@ViewData["Title"] - Users</title><environment include="Development"><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" /><script src="~/js/site.js"></script></environment><environment exclude="Development"><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" crossorigin="anonymous" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"/></environment><link rel="stylesheet" href="~/css/site.css" /></head><body><header><nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"><div class="container"><a class="navbar-brand" asp-area="" asp-page="/Index">Users</a><button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"><partial name="_LoginPartial" /></div></div></nav></header><div class="container"><partial name="_CookieConsentPartial" /><main role="main" class="pb-3"> @RenderBody()</main></div><footer class="border-top footer text-muted"><div class="container">© 2019 - Users- <a asp-area="" asp-page="/Privacy">Privacy</a></div></footer><environment include="Development"><script src="~/lib/jquery/dist/jquery.js"></script><script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script></environment><environment exclude="Development"><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery" crossorigin="anonymous" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js" asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal" crossorigin="anonymous" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o"></script></environment><script src="~/js/site.js" asp-append-version="true"></script> @RenderSection("Scripts", required: false)</body></html>
Why my webapi no works but reports 404 no found?
I still follow the tutorial in this: https://www.youtube.com/watch?v=aIkpVzqLuhA
Here is startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
and here is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApplication1.Controller
{
[Route("api/[controller]")]
public class ValuesController : Microsoft.AspNetCore.Mvc.ControllerBase
{
// GET: api/<controller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<controller>
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
After I ran the URL https://localhost:44361/api/values/ , nothing works but receive a
MVC Controller list from database
Need some help on pulling data from database in MVC Controller. This is the code I have but not sure if I'm doing this right using a LINQ query
public class EditProfileController : Controller { public IActionResult Index() { var listdata = db.Users.ToList().Select(x => new FE.Models.AspNetUsers { Id = x.Id, // (repeat the same for all) }).ToList(); } } }
Get error on index 'EditProfileController.Index()': not all code paths return a value FE'
and on db 'The name db does not exist in the current context'
How can I pull data from a database table to create a list view?
Error when attempting to use _userManager.GetUserByEmailAsync(...
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose()
on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AsyncDisposer'.
This code fails when excuted in the IndexModel class, but I simply copied it from where I am using it in my own directory in the Identity Area where it does work and does not throw an exception.
I have put off learning DI, and it appears this has bitten me.
The main difference between the two classes is that I am using a different menu for the class that works, than the class that does not.
I would assume that since the only difference I am aware of between IndexModel and the class that works is the menus, that commenting out everything in the larger menu except the bare minimum to launch the page would fix this issue. But it does not.
What could I be doing in one place to break this code, that I am not doing in the other?
thanks!
public class IndexModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly ILogger<RegisterModel> _logger; private readonly RoleManager<IdentityRole> _roleManager; public IndexModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger, RoleManager<IdentityRole> roleManager ) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _roleManager = roleManager; } public async void OnGet() { var userName = User.Identities.First<ClaimsIdentity>().Name; try { var userByEmail = await _userManager.FindByEmailAsync(userName);
And to be complete, here is the code that does work that I copied this over from.
public class ManageUserAccountsModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly ILogger<RegisterModel> _logger; private readonly RoleManager<IdentityRole> _roleManager; public ManageUserAccountsModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger, RoleManager<IdentityRole> roleManager ) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _roleManager = roleManager; } [BindProperty ] public List<EmailDto> Customers { get; set; } public async Task<IActionResult> OnGet() { //currently can only manage account from local computer in VS. Remove If Debug to publish to web Customers = new List<EmailDto>(); using (var context = new resumesEntities()) { var users = (from i in context.Users select new EmailDto { Id = i.ID, Email = i.IdentityName }).OrderBy(a=>a.Email); if(users!=null) { IList<string> emptyList = new List<string> { "none"}; foreach (EmailDto j in users) { var next = await _userManager.FindByEmailAsync(j.Email);
What are the best practices to follow for building data access layer using EF Core?
Hi, I am building my project in such a way that I have a single SPA angular asp.net core application which call separate Web API asp.net core projects based on the angular modules they are configured. Now, I want to know the best possible approach I could take to make managing my databases more easily. Should I create a class library separately that will solely handle all the db calls or should I put each db calls inside of the Web api projects. Also I am planning to user Repository pattern but am not sure if it is required in EF Core. Also, I don't want to use SQL Server. So, what are the best practices to follow?
Linq with jagged arrays
I am trying to understand a piece of code but I am not sure I do. I will be very grateful if someone could explain to me what happens here:
foreach (var row in jaggedArray.Skip(1).OrderBy(r => r[headerIndex])) { Console.WriteLine(string.Join(" | ", row)); }
I suggest that .Skip(1) misses the first row, but after that, I did not understand anything. I will give you an example of what this code does:
4 name, age, grade Peter, 25, 5.00 George, 34, 6.00 Marry, 28, 5.49 sort name
This is an example input. Our jagged array has 4 rows and 3 columns. We have to sort the name header so in this case, the header index is equal to 0. Thank you advance!
File Upload Management
Hopefully I can explain this clearly. I am creating a page where a user can upload 1 or more videos. My issue is matching the information tied to each video with the video itself. The user can dynamically add numerous instances of videos per page in any order and then click save to upload all at once.
I have this working during the creation of the page, but my issue now is during an edit of the page. A user could add another instance of a video upload or change an existing upload to a different file or both. Tracking what file belongs to what instance is a challenge here because there could be instances that are in between and unchanged.
Each instance is given an order number and it would be ideal if I could somehow link the order number to the file being uploaded, then during post I could just match the two.
Here is a very basic drawing of how it could flow: https://drive.google.com/file/d/1As-NMmuz9A_P9UdUmcRQ390xVAo4gwdn/view?usp=sharing
Any thoughts?
Thanks in advance.
Byte image is not saved in the DB
Hi
I'm using Core 2.1 and SQL Server 2017
I have this byte field in the model:
public byte[] Image { get; set; }
of course I have its corresponding varbinary(MAX) field in the DB.
and trying to add in image to it in the controller by this:
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Job,Address,MobileNo,SexId,EnterDate")] Guest guest, List<IFormFile> Image) { if (ModelState.IsValid) { foreach(var item in Image) { if(item.Length > 0) { using (var stream = new MemoryStream()) { await item.CopyToAsync(stream); guest.Image = stream.ToArray(); } } } guest.InsertDate = DateTime.Now; _context.Add(guest); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["SexId"] = new SelectList(_context.Sex, "Id", "SexName", nzeel.SexId); return View(guest); }
and have this file item in this Create view:
<input type="file" id="files" asp-for="Image" />
but when I select an image of type JPG for example no image is saved in the DB in the new record added!
Note: when I put the Image in the binding the post action does not succeeded when I press the submit button! and the page is refreshed only with no changes!
Why? and How to solve please?
How does aspnetcore use DbContext in other threads?
public SerialPortStartController(FireControlContext context) { _context = context; } public void Index() { Task.Run(() => { Start(); }); } public void Start() { //I need to use _context here //Reinstantiation is too cumbersome. I need to use ConnectionStrings in appsettings.json string connection = @"Data Source=LP-HOME\SQLEXPRESS;Initial Catalog=FireControl;Integrated Security=True"; DbContextOptions dbContextOption = new DbContextOptions(); DbContextOptionsBuilder dbContextOptionBuilder = new DbContextOptionsBuilder(dbContextOption); using (var ctx = new FireControlContext(dbContextOptionBuilder.UseSqlServer(connection).Options)) { } }
Two Factor Authentication, VerifyTwoFactorTokenAsync always return false
I tried creating a new project from VS 2017 (.Net Core v2.0) and for authentication, I chose 'Individual User Accounts'. I put QRCode from (https://davidshimjs.github.io/qrcodejs/). I put javascript code in EnableAuthenticator.cshtml
<script src="~/lib/qcrcode.js/qrcode.js"></script><script> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 } );</script>
In ManageController.cs, action method EnableAuthenticator doesn't change at all.
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableAuthenticator (EnableAuthenticatorViewModel model) { var user = await _userManager.GetUserAsync(User); if ( user == null ) { throw new ApplicationException ($"Unable to load user with ID '{_userManager.GetUserId (User)}'."); } if ( !ModelState.IsValid ) { await LoadSharedKeyAndQrCodeUriAsync (user, model); return View (model); } // Strip spaces and hypens var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty); //AuthenticatorTokenProvider var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.EmailConfirmationTokenProvider, verificationCode); if ( !is2faTokenValid ) { ModelState.AddModelError ("Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync (user, model); return View (model); } await _userManager.SetTwoFactorEnabledAsync (user, true); _logger.LogInformation ("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id); var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); TempData[RecoveryCodesKey] = recoveryCodes.ToArray (); return RedirectToAction (nameof (ShowRecoveryCodes)); }
and this is QRCode generator
private async Task LoadSharedKeyAndQrCodeUriAsync (ApplicationUser user, EnableAuthenticatorViewModel model) { var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if ( string.IsNullOrEmpty (unformattedKey) ) { await _userManager.ResetAuthenticatorKeyAsync (user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync (user); } model.SharedKey = FormatKey (unformattedKey); model.AuthenticatorUri = GenerateQrCodeUri (user.Email, unformattedKey); }
I run and register user, I get notification to 'update-database' to be executed in Package manager console, done. I register again and login successfully. In the 'Two-factors Authentication' menu, I clicked 'configure authentication app', go to 'enable authenticator' page scan QRCode through google/microsoft authenticator and always get fail with this error message:Verification code is valid.
I tried to debug, I found VerifyTwoFactorTokenAsync() always return false. I don't know why this happen ? I tried to changed AuthenticatorTokenProvider became EmailConfirmationTokenProvider and still return false.
but I found something interesting that [TwoFactorEnabled] and [EmailConfirmed] columns in the dbo.AspNetUsers is false.
are there any relation between value in the [TwoFactorEnabled] and [EmailConfirmed] columns and VerifyTwoFactorTokenAsync(), because one of the parameter is ApplicationUser ?
how to solve this problem ?
HTTP Error 502.3 - Bad Gateway, Wen deploying asp.net core
I deployed asp.net core website. I have followed all the processes kept online. But I dont know what this particular problem this.
They Application has been previously deployed on 3 other systems and it works fine. So am trying to deploy it on a windows 10 Pc and it giving me a strange error that I have not seen before.