razor pages
36 TopicsSolutions for Blazor problems
Hi, I've significantly reduced render times, section rendering and configuration, API exposure, ... And I am starting thinking of sharing. I've never done this before, so I am wondering how to offer my Blazor framework API. Feacures I've implemented: Defer rendering (on standard component level - as naturalrendering pipeline) Custom sections (with custom state proagation and optimization minimizing render requests - my sections allow for full generic settings usable in section definition component with any amount of RenderFragment or other parameters): <YourSection Param1="StateWatchedParam1" Param2="StateWatchedParam2"> <RenderFragment1> StateWatchedContent with single render on whole section outlet </RenderFragment1> <RenderFragment2> StateWatchedContent with single render on whole section outlet </RenderFragment2> </YourSection> Unit of Work system with unltimited dependency tree of steps described by FluentAPI and accessed only by input model from client side - thus limiting any API exposure. You would have to know descriptor, rights and then guess allowed steps and stil only can fill model with input data - nothing more ... LinQ projector pattern with lego building FluentAPI system - where any business logic can be break into named step in specific named projector, so you are out of ordinary expression tree completely. That projector pattern is correctly written to check for Queryable Provider and to work with the same expression tree also for Enumerable. (Thus the same lego pieces can work for client.) Blazor component messagging done on direct Task API system - so without any queue or backlog. You can directly pass any data between any Blazor component and you are doing it in direct way without any delay or data transfer. Here I have SignalR also in the same system - allowing server to communicate with any component needed. And whole system is communicating with ToastLogger, thus any issue/unhandled exception can be (and it is) instantly logged and toasted to user. Background runner - thus any Task in Blazor can be called to just RunInBackground and it is immediately handled in Task lock mechanism, Exception mechanism and with correct Blazor stae update pipeline thus allowing for partial renders and mid render switch to background process finishing later and rendering from that deferred background.87Views0likes0CommentsASP.NET Community Standup - ASP.NET Core Route Tooling Enhancements in .NET 8
ASP.NET Core is built on routing. Minimal APIs, Web APIs, Razor Pages, and Blazor all use routes to customize how HTTP requests map to your code. In .NET 8 we’re investing in a suite of new features to make routing easier to learn and use. These include: Route syntax highlighting Autocomplete of parameter and route names Autocomplete of route constraints Route analyzers and fixers Support for Minimal APIs, Web APIs, and Blazor Join us as James Newton-King overviews these new features and answers your questions, live! Community Links: https://www.theurlist.com/aspnet-standup-2023-04-04 Featuring: James Newton-King (@jamesNK) #aspnetcore #dotnet622Views0likes0CommentsHow to increase session timeout
Hello Everyone, I am working on .NET framework 4.8 with a MVC web application. To login I am using MFA with microsoft's openid-configuration method. When I create FormsAuthenticationTicket and try to set session timeout as per my requirement but it doesn't work. See the sample code as below FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket( 1, // version adminEmail, // get username from the form DateTime.Now, // issue time is now DateTime.Now.AddDays(365), true, // cookie is not persistent "XXXXX" // role assignment is stored in userData ); But it is not working properly, it gets timeout within 15 mins100Views0likes0CommentsHow to trigger modal in blazer web server using c#?
Hi Team I have a blazer web server, want to understand something regarding my code. The suppose when clicking add operation it triggers modal, currently its not doing so and checked by debuging there are no any js errors. How do i improve this logic so it can work as expected? PAGE "/main" @using OperationApp.Models @using OperationApp.Components @using Blazored.Modal <h1>Operation Manager</h1> <!-- Button to open modal for adding a device --> <button class="btn btn-primary mb-3" @onclick="OpenAddDeviceModal">Add Device</button> <!-- Listing of operations --> @if (operations.Any()) { <ul class="list-group"> @foreach (var operation in operations) { <li class="list-group-item d-flex justify-content-between align-items-center"> <span>@operation.Name</span> <span> <!-- Button to remove the operation --> <button class="btn btn-danger" @onclick="() => RemoveOperation(operation.OperationID)">Remove</button> </span> </li> } </ul> } else { <p>No operations available.</p> } <!-- AddDeviceModal component --> <AddDeviceModal @ref="addDeviceModal" /> @code { private List<Operation> operations = new List<Operation>(); private AddDeviceModal addDeviceModal; private void OpenAddDeviceModal() { addDeviceModal.Open(); // Open the modal } private void RemoveOperation(int operationID) { var operationToRemove = operations.FirstOrDefault(op => op.OperationID == operationID); if (operationToRemove != null) { operations.Remove(operationToRemove); } } }138Views0likes0CommentsWhat do i use to make a inline editable table for razor page?
http://datatable.net edit function costs money, so I'm trying to make my own table with inline editing with Razor page, but I don't know what is the modern way to do it. Razor is not so modern but I don't think I want to use jQuery for it if there's a better way. I read some posts and there are a lot of answers like Ajax, jQuery, fetch API,... and I also found a library called Hydro for Razor that mimics SPA functionality, but I don't know if it's applicable to this task. Can someone point me in a direction?223Views0likes0CommentsHow to create a customer plugin using dotnet 6.0
Hi, I implement a base application ( a standard app), now i want to create a customer plugin inherited from the base app, My goal is to linked between there and implement the new features in the customer plugin without touch the base app. Thanks256Views0likes1CommentLooking for recommendations for hosting ASP.NET web apps
I've been with an ASP.NET web hosting service for several years. However, the service provided has declined in the last couple of years. So, I started looking for a new, inexpensive, web hosting service. This is for my side business, which doesn't attract that much traffic. Yes, I'm sure that Azure would do, but like I said I'm trying to keep costs down. Naturally, I started searching. I've come across a couple of "Top 10 hosting services for 2023". I've spent about three weeks looking at different ones. I want to publish my ASP.NET Core both from Visual Studio and Azure DevOps Services, using the Azure DevOps FTP task if necessary. My website is currently written in .NET 6. This search experience has not been a pleasant experience. Some services I've spoken to said that because I am working with ASP.NET, then it can only run on Windows, and therefore I couldn't use their service, since they are a Linux only provider (mostly WordPress). I have told two of these web hosting services that ASP.NET Core can run on Linux. I even shared links from Microsoft that ASP.NET Core can run on Linux, Mac, and Windows. In both cases their response was disbelief and a refusal to discuss the topic further with me. Since it seems that many web hosting services have a mindset that refuse to accept the idea that anything from Microsoft can run on Linux, I decided to go back to researching web hosting companies that offer ASP.NET on Windows (both traditional .NET Framework varieties as well as .NET Core with .NET 5, 6, and 7). I settled on one, but they insist that I must allow them to re-register the domain I've owned for 10+ years. They will not allow me to upload my website to them until I've unlocked my website from the domain registrar I use. I've told them, at least three times, that I am satisfied with the domain registrar I have and only need a web hosting provider. They won't hear of it and refuse to go any further with me. So, once again I'm back to searching for a web hosting company for small businesses, that is inexpensive (OK, cheap), that I might be able to have multiple domains on. Therefore, I'd appreciate recommendations from this community, please.1.4KViews0likes8CommentsAjax to Controller bind model
Guys, good afternoon, I'm working on an application in which it makes javascript ajax requests to the backend An error occurs when I send a structure this way: " const OFManutencaoViewModel = { Justification: Justification, RequesterJustification: idOFJustificationRequestor, EmailsJustifications: idListaOFJustificationEmails, OFBecalhoViewModel: oFCabecalhoViewModel } " Properly populated according to the payload (attached image) below: My model is structured like this: public class OFManutencaoViewModel { public OFBecalhoViewModel OFBecalhoViewModel { get; set; } public string Justification { get; set; } public string RequesterJustification { get; set;} public string EmailsJustifications { get; set; } } When making the call it hits the controller but with null values Method structure (image attached): I've already checked property by property and everything is correct. Could someone give me some help237Views0likes0CommentsNo Registered Service for IEmailSender
Hello all, I am using ASP.Net Core Web API (.Net Core 😎 to create a web app and API, when i added default Identity and Areas Pages i am getting an error for IEmailSender Service not beeing registered even though i dont need and have registered a mock class for it. Thank you Program.cs using Microsoft.AspNetCore.Identity; using Microsoft.OpenApi.Models; using Microsoft.EntityFrameworkCore; using ProMateAPI.Data; using ProMate.Library; using Swashbuckle.AspNetCore.Filters; using ProMateAPI.Utility; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // this would be enabled if we only needed the defaults for users and such //builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) // .AddEntityFrameworkStores<ApplicationDbContext>(); // builder.Services.AddDbContext<TContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))); builder.Services.AddDbContext<ProMateContext>(); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => { options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey, }); options.OperationFilter<SecurityRequirementsOperationFilter>(); }); /* * options => { options.SignIn.RequireConfirmedAccount = false; options.SignIn.RequireConfirmedAccount = false; } * * */ builder.Services.AddScoped<IEmailSender, MyEmailSender>(); builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>(); ////builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddAuthentication(); builder.Services.AddAuthorization(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.MapIdentityApi<IdentityUser>(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run(); ------------- MyEmailSender.cs using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace ProMateAPI.Utility; public class MyEmailSender : IEmailSender { public Task SendEmailAsync(string email, string subject, string htmlMessage) { return Task.CompletedTask; } } ----------------- Register.html.cs // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using ProMateAPI.Utility; namespace ProMateAPI.Areas.Identity.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IUserStore<IdentityUser> _userStore; private readonly IUserEmailStore<IdentityUser> _emailStore; private readonly ILogger<RegisterModel> _logger; //private readonly IEmailSender _emailSender; // IEmailSender emailSender public RegisterModel( UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, IUserStore<IdentityUser> userStore, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger ) { _userManager = userManager; _roleManager = roleManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _logger = logger; //_emailSender = emailSender; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [BindProperty] public InputModel Input { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public string ReturnUrl { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public IList<AuthenticationScheme> ExternalLogins { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class InputModel { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task OnGetAsync(string returnUrl = null) { // creates missing roles if (!_roleManager.RoleExistsAsync(SD.Roles.Customer.ToString()).GetAwaiter().GetResult()) { foreach (var r in Enum.GetValues(typeof(SD.Roles))) { _roleManager.CreateAsync(new IdentityRole(r.ToString())).GetAwaiter().GetResult(); } } ReturnUrl = returnUrl; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } private IdentityUser CreateUser() { try { return Activator.CreateInstance<IdentityUser>(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " + $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore<IdentityUser> GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore<IdentityUser>)_userStore; } } }5.3KViews0likes1Comment