Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

manipulate images in Blazor Client-side

$
0
0

Hi there,

I need to change resolution of an Image on Blazor Client-Side.

I tried with this code:

    public static class IncreaseImgResolution
    {
        public static async Task<string> IncreaseDpi(string base64IngString, float moltiplicatioFactor)
        {
            return await Task.Run(() => EnchangeImgDpi(base64IngString, moltiplicatioFactor));
        }

        private static string EnchangeImgDpi(string base64IngString, float moltiplicatioFactor)
        {
            byte[] imageBytes = Convert.FromBase64String(base64IngString);
            var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            var OriginalBitmap = new Bitmap(ms);
            var vertRes = OriginalBitmap.VerticalResolution * moltiplicatioFactor;
            var horRes = OriginalBitmap.HorizontalResolution * moltiplicatioFactor;
            OriginalBitmap.SetResolution(horRes, vertRes);
            using (var stream = new MemoryStream())
            {
                OriginalBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                var str = stream.ToArray();
                return Convert.ToBase64String(str);
            }
        }
    }

But I retrieve following error:

blazor.webassembly.js:1 WASM: System.PlatformNotSupportedException: Operation is not supported on this platform.

At following line of code:

var OriginalBitmap = new Bitmap(ms);

So, I think System.Drawing is not working on webassembly.

I would like to know if somebody can suggest some workaround or alternative solutions.

Thank you


.Net Core 3.1 connection to Dynamics GP Web Services will not work. Is there a solution?

$
0
0

I have tried to use the Microsoft WCF Web Service Reference Provider to create a connection to GP Web Services from inside a .NET Core 3 web API project and am getting an error stating "No endpoints compatible with .Net Core apps were found". Says that the System.ServiceModel.Channels.SymmetricSecurityBindingElement element type is unsupported.

GP Web Services are running and in use by an older web site so they are actively in use and therefore not the problem.

As a result of the errors, I cannot generate a proxy using either the legacy or the native end point WSDL’s from inside a .NET Core project.

I also cannot reference a project using an older version of Microsoft .NET framework from the newer Microsoft .NET Core project. This means I cannot just reference the existing project we use or even try to make a new project with the older framework as the base.

I would like to ask if anyone else has this issue and has found a workaround or a way to utilize GP Web Services from a .NET Core 3 project when they cannot create the proxy through the means provided by Microsoft? Unhappy with this since they are both Microsoft products and you would think they could talk to each other ...

How can I generate blob URL by .net core without Azure?

$
0
0

As we know, now many websites(such as youtube) play their video with blob format for they don't want any other people to download the video easily.

Now I want to play the video with blob format by .net core for I don't want any other people to download the video easily also.

I googled about this and all about this of .net core must achieve with Azure.

Meanwhile, I found many tutorials about Java which can achieve this only with itself.

How can I generate blob URL by .net core without Azure?

Thank you.

Razor Pages Vs MVC apps

$
0
0

I am wondering why Microsoft is pushing these Razor Pages Apps over MVC.
This is very annoying and concerning to me.

I'm going over the "Recommended Learning path" in the Overview at:
https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-3.1

It says for a new app go through the Razor Pages app.
For maintaining an app go through MVC.

Why are they pushing this Razor Pages thing?
I went through the Razor pages in the Core 2.x tutorials.
This looks like a return to the old WebForms paradigm.  Why are they doing this.
This is unclean and disgusting.  Did Microsoft learn nothing from the Web Forms era?

I try to keep the pulse on where the technology is going.
I've talked my bosses and directors into going from WebForms to MVC back in 2010.
And from Full Framework to .Net Core in 2015 and 2018 at two different places.
And if you went .Net Core Web Forms was no longer even available.  So I know I had the right pulse on the technology back in 2010.
I knew MVC would be the future and Web Forms would eventually go away.

This leaves me confused and bewildered.  I just cannot believe they are pushing this Web Forms looking crap with a separate .cs file that looks like a code behind file.
Can somebody clear this up?

What is the advantage of using Razor Pages?
Please don't answer with they are easier.
That is way to vague.

How to intercept errors generated in DotNet.js - Blazor Client Side

$
0
0

Hello guys,

I´m getting out of memory error on DotNet.js because I´m trying to upload a too big file.

My question is how I can Catch the error in Blazor Client ?

Thanks for help

asp core 3.1 identity login dowesn't work and shows samesite warning

$
0
0
<div>I just finished my asp .net core 3.1 project. and i was trying to deploy it onIIS. So first i scaffolded Asp Identity and it createdidentityHostingStartup and other files. And published the project as self-Contained forwin-x64  as  I generated self signed certificate using openssl for Identity using this process </div> <div> https://benjii.me/2017/06/creating-self-signed-certificate-identity-server-azure/ and put it inside publish folder.also i have used No managed code for the app pool when i tested it, the login it worked on some machines on chrome but for those it didn't work on,it still worked on Microsoft edge browser. when i inspected the login, it shows a warning "a cookie associated with the resource was set with samesite==none" and the warning disappears instantly.But the request was sent with a cookie with value"samesite= strict" and not secure. So i modified startup.cs as shown and set samesite property to none but it didn't work. </div> <div> </div> <div>Here is the code for **startup.cs** </div> <div>
       public void ConfigureServices(IServiceCollection services)        {            X509Certificate2 cert = null;            using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))            {                certStore.Open(OpenFlags.ReadOnly);                X509Certificate2Collection certCollection = certStore.Certificates.Find(                    X509FindType.FindByThumbprint,                    // Replace below with your cert's thumbprint                    "418f13d9473b6412e186f8e3a05fbf0370ec865c",                    false);                // Get the first cert with the thumbprint                if (certCollection.Count > 0)                {                    cert = certCollection[0];                    //Log.Logger.Information($"Successfully loaded cert from registry: {cert.Thumbprint}");                }            }            // Fallback to local file for development            if (cert == null)            {                cert = new X509Certificate2(Path.Combine("C:\\inetpub\\wwwroot\\VatAppPublish\\", "localhost.pfx"), "");               // Log.Logger.Information($"Falling back to cert from file. Successfully loaded: {cert.Thumbprint}");            }                       services.AddDbContext<vat_dbContext>(options =>                options.UseMySql(                    Configuration.GetConnectionString("DefaultConnection")));            services.AddDbContext<ApplicationDbContext>(options =>               options.UseMySql(                   Configuration.GetConnectionString("DefaultConnection")));            services.AddMvc(option => option.EnableEndpointRouting = false)                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)                .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());            services.AddAuthentication(IISDefaults.AuthenticationScheme);            services.AddTransient<CompanyBLLCustom>();            services.AddTransient<CustomerBLLCustom>();            services.AddTransient<MachinesalesBLLCustom>();            services.AddTransient<ManualsalesBLLCustom>();            services.AddTransient<PurchaseBLLCustom>();            services.AddTransient<SummaryreportsBLLCustom>();            services.AddTransient<SystemconfigBLLCustom>();            services.AddTransient<SalesreportBLLCustom>();            services.AddTransient<PurchasereportBLLCustom>();            services.AddTransient<CompanyFunctions>();            services.AddTransient<CustomerFunctions>();            services.AddTransient<MachinesalesFunctions>();            services.AddTransient<ManualsalesFunctions>();            services.AddTransient<PurchaseFunctions>();            services.AddTransient<SystemconfigFunctions>();            services.AddTransient<SummaryreportsFunctions>();            services.AddTransient<SalesreportFunctions>();            services.AddTransient<PurchasereportFunctions>();            services.AddTransient<CompanyValidator>();            services.AddTransient<CustomerValidator>();            services.AddTransient<MachinesalesValidator>();            services.AddTransient<ManualsalesValidator>();            services.AddTransient<PurchaseValidator>();            services.AddTransient<SummaryreportsValidator>();            services.AddTransient<SystemconfigValidator>();            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)                .AddEntityFrameworkStores<ApplicationDbContext>();            services.AddIdentityServer()                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()                .AddSigningCredential(cert); ;            services.Configure<CookiePolicyOptions>(options =>            {                options.MinimumSameSitePolicy = SameSiteMode.None;            });            services.AddAuthentication()                .AddIdentityServerJwt();            services.AddControllersWithViews();            services.AddRazorPages();            // In production, the React files will be served from this directory            services.AddSpaStaticFiles(configuration =>            {                configuration.RootPath = "ClientApp/build";            });        }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)        {            app.UseAuthentication();            app.UseIdentityServer();                      app.UseHttpsRedirection();            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();                app.UseDatabaseErrorPage();            }            else            {                app.UseExceptionHandler("/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.UseStaticFiles();            app.UseSpaStaticFiles();            app.UseRouting();            app.UseAuthorization();            app.UseEndpoints(endpoints =>            {                endpoints.MapControllerRoute(                    name: "default",                    pattern: "{controller}/{action=Index}/{id?}");                endpoints.MapRazorPages();            });            app.UseSpa(spa =>            {                spa.Options.SourcePath = "ClientApp";                if (env.IsDevelopment())                {                    spa.UseReactDevelopmentServer(npmScript: "start");                }            });            app.UseCookiePolicy(new CookiePolicyOptions            {                MinimumSameSitePolicy = SameSiteMode.None            });
```
*** appseting.json***
```{  "ConnectionStrings": {    "DefaultConnection": "Server=localhost;Port=3306;User=root;Password='';Database=vat_db;TreatTinyAsBoolean=true"  },  "Logging": {    "LogLevel": {      "Default": "Information",      "Microsoft": "Warning",      "Microsoft.Hosting.Lifetime": "Information"    }  },  "IdentityServer": {    "Clients": {      "VatApplication": {        "Profile": "IdentityServerSPA"      }    }    ,    "Key": {      "Type": "File",      "FilePath": "C:\\inetpub\\wwwroot\\VatAppPublish\\localhost.pfx",      "Password": ""    }  },  "AllowedHosts": "*"
}
```
**IdentityHostingStartup.CS**
```public class IdentityHostingStartup : IHostingStartup    {        public void Configure(IWebHostBuilder builder)        {            builder.ConfigureServices((context, services) => {            });        }    }

</div> <div>Thank you in Advance.</div>

Asp Core 3.1 Identity Example doesn't work

Index form to contain import and export to excel actions

$
0
0

@model IEnumerable<StudentAttendance.Models.Staff>
<div class="row">
<div class="col-md-3">
<h4 style="display: inline">Staff List </h4>
<h4 style="display: inline"><a asp-action="Create">Create New</a></h4>
</div>
<div class="col-md-7">
<form asp-action="Index" method="get" enctype="multipart/form-data">
<div class="form-actions no-color">
<div class="col-md-3" style="margin-top:-2px">
Find by Dept name:
</div> <div class="col-md-4">
<input type="text" name="SearchString" class="form-control" style="height:25px;background-color:lavender" />
</div><div class="col-md-2">
<input type="submit" value="Search" class="btn btn-default" />
</div><div align="right" class="col-md-3">
<a asp-action="Index" style="background-color:lavender">Back to full List</a>
</div>
</div>
</form>
</div>
<a asp-action="Export">Export</a>
<form method="post" enctype="multipart/form-data">
<div class="col-md-2">
<input class="form-control" type="file" name="file" />
<a asp-action="Import">Import</a>
</div>
</form>
</div>
<table class="table">
<thead >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.StaId)
</th>
<th>
@Html.DisplayNameFor(model => model.Contact)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.StaId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Contact)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@if (User.IsInRole("Manager"))
{<a asp-action="Edit" asp-route-id="@item.Id">Edit</a>} |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
@if (User.IsInRole("Admin"))
{<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>}
</td>
</tr>
}
</tbody>
</table>

Index.cshtml of StaffController is shown above. I want to accomodate import funcion also. Is it possible. I have underlined the problematic tags


ASP.NET 3.0 : 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[Application.Startup]' while attempting to activate Application.Identity.Startup'.'

$
0
0

I am upgrading my ASP.NET 2.1 Application to ASP.NET 3.0, While running I am getting error as ''Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[Application.Startup]' while attempting to activate Application.Identity.Startup'.''. I have used IHostBuilder instead of IWebHostBuilder.Below is my Program.cs for reference

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
          {
            logging.ClearProviders();
            logging.AddConsole();
          })
        .ConfigureWebHostDefaults(webBuilder =>
        {
          webBuilder.UseStartup<Startup>();
        });

Upgrade from .Net Core 2.2 to 3.0 gives Internal Server Error for SignInManager

$
0
0

Hello,

    So I upgraded from my MVC from .NetCore  2.2 to 3.0.  After making the required changes to the Startup.cs and Program.cs, then all the models and controllers.  I ran a build and had no errors.  I then went to debug with Microsoft Edge and ran into a huge error that I have not been able to figure out what I am missing.  There error I am getting is 

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.

In following everything from the migration page (https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#razor-pages) I added the service.AddRazorPages() after services.AddControllersWithViews(), and I have the app.UseRouting before the app.UseAuthentication, which is before the app.UseEdnpoints.  In the endpoints I also have the MapRazorPages setup.  I have tried adding the Microsoft.AspNetCore.Identity.UI package to the project but that also did not seem to help.  Before I even began to make changes I ran the project and it worked perfectly fine.  

The only changes I can see that affected this were the required changes.  Replacing services.AddDefaultIdentity with services.AddIdentityCore, and what I mentioned above.   

Any thoughts on what I may have missed in the upgrade?

Invalid URI: The format of the URI could not be determined when accessing external DLL in .net core 2.2 application

$
0
0

Dear All,

   I've two applications, one of the application build version under 4.5.2 which supports Dynamics CRM 2016 SDKs. another one project which I'm currently building under .NET CORE 2.2 version which does not support CRM SDK. So, I'm referencing 4.5.2 application dll into .net core 2.2 application. Once, I completed all the mappings and referencing models, the following error occured when debugging the application in local machine. 

{System.UriFormatException: Invalid URI: The format of the URI could not be determined.

And the above error referencing my local above mentioned two application URLs.

Please help me, I'm stuck in this issue. 

Awaiting your reply.

Thanks,

ASP.NEt 3.0 : FormattedLogValues

$
0
0

Below is the line of code which was running well in ASp.NET 2.1 but after upgrading from 2.1 to 3.0 it throws error

var formattedMessage = new FormattedLogValues(message, values).ToString();

What is the alternate to above code in ASP.NET 3.0

WebAPI: why does it use MVC namespace and classes?

$
0
0

Hello,

I'm pretty new to the WebAPI world.

So far I've read some great articles on how to create and call WebAPI; however, I'm still a bit puzzled about one thing: even if we create "just" a WebAPI, not a MVC application, we are almost "stuck" with theMicrosoft.AspNetCore.Mvc namespace.

For instance:

  • ControllerBase is part of the namespace;
  • HttpMethodAttribute (HttpGet, HttpPost, etc.) is part of the namespace;
  • even return methods like Ok(), CreatedAtRoute(), etc. are part of the namespace.

Why is this like that? Can't we have a "proper" separation between "pure WebAPI" and MVC application? Is that the correct way of doing thing? If no, what is the correct way of creating a "pure WebAPI"?

Thanks and have a nice day :).

An unhandled exception occurred while processing the request.

$
0
0

I am getting error while running my .Net core 3.1 Application

<div class="titleerror">TypeLoadException: Could not load type 'Microsoft.AspNetCore.Authentication.Internal.RequestPathBaseCookieBuilder' from assembly 'Microsoft.AspNetCore.Authentication, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.</div>

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions..ctor()

<div class="titleerror">TargetInvocationException: Exception has been thrown by the target of an invocation.</div>

System.RuntimeTypeHandle.CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool hasNoDefaultCtor)

Below are the packages I have added

<PackageReference Include="IdentityModel" Version="4.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.0.0" /><PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" /><PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" /><PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" /><PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" /><PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" /><PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.1.1" /><PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.1.11" /><PackageReference Include="Microsoft.AspNetCore.Mvc.Localization" Version="2.1.3" /><PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.1.3" /><PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.1.3" /><PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.1.3" /><PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.1.11" /><PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.1" /><PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.1" /><PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.1.1" /><PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" /><PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.0.1" /><PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.1" /><PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.1" /><PackageReference Include="Newtonsoft.Json" Version="11.0.2" /><PackageReference Include="NLog" Version="4.6.6" /><PackageReference Include="NLog.Extensions.Logging" Version="1.5.2" /><PackageReference Include="NLog.Web.AspNetCore" Version="4.7.0" /><PackageReference Include="Quartz" Version="3.0.5" /><PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />

Is this error relates to mis matched dependency ? If it is which dependency is causing problem ?

Unable to seed my table in mysql for authorisation in asp.netcore 3.1

$
0
0

Dear All,

I am using mysql has my database. I actually dont have this problem when I use MSSQL. so the issue is I activated my project to use the default authorisation scheme which is meant to create the default users and roles table.

But unfortunately I am gettting a strange error

CREATE TABLE `AspNetUserLogins` (
    `LoginProvider` varchar(255) CHARACTER SET utf8mb4 NOT NULL,
    `ProviderKey` varchar(255) CHARACTER SET utf8mb4 NOT NULL,
    `ProviderDisplayName` longtext CHARACTER SET utf8mb4 NULL,
    `UserId` bigint NOT NULL,
    CONSTRAINT `PK_AspNetUserLogins` PRIMARY KEY (`LoginProvider`, `ProviderKey`),
    CONSTRAINT `FK_AspNetUserLogins_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE
)

MySQL said: Documentation
#1071 - Specified key was too long; max key length is 1000 bytes

So I tried following this tutorials

https://thienn.com/change-primary-key-aspnetcore-identity-and-more/

It worked but some other tables are still displaying the error like one I pasted above. Been strugling with this for 2 hours Please any help.

Dont forget am using Mysql. Mssql most likely wont give this error. I am using Pomelo.EntityframeworkCore ORM library

Thanks alot.


anonymous User with password-protected link in asp.net core 3.1 - is ClaimsPrinciple/cookie the best way to do this?

$
0
0

ok - so im trying to do something like vimeo.com
where a private video can be accessed by just inputting a password
so for example if you go here:
https://vimeo.com/392083444
you get a simple password box and submit button

i came to the conclusion to use claims
since the user is anonymous - i didnt want to use Identity
in addition the video password is saved in the db with the video metadata

oh and btw just like vimeo or youtube -
there is a proper Identity setup bc the profile is governed by a proper Identity login

so the first question is:
is going with ClaimsPrinciple the best strategy to do this?
or am i making too much out of it ?
i mean pre-Core i would have gone with session vars but thats not a thing now in core

heres what ive got so far

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> LinkLogin([Bind("ID, Guid, Password")] LinkLoginVM vm)
    {
        if (String.IsNullOrEmpty(vm.Password))
        {
            return ViewComponent("Error", new { errorcode = 1});
        }
        var c = await db.Vids.SingleAsync(c => c.Guid == vm.Guid);

        // create and add guid
        if (ModelState.IsValid)
        {
            if (vm.Password == c.Password)
            {
                // give user a claim
                ApplicationUser user = await um.GetUserAsync(HttpContext.User);  <-- this doesnt really return anything
                var claims = new List<Claim>() { 
                    new Claim(ClaimTypes.Name, "Password Guest"),
                    new Claim(JwtRegisteredClaimNames.Sub, vm.Guid),
                    new Claim(JwtRegisteredClaimNames.AuthTime, DateTime.Now.ToString())
                };

                // not sure what im doing here
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
//               await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProps);
                await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity), authProps);
            }
        }
        else
        {
            // put debugger here if problematic
            Console.WriteLine("ERR: ModelState not valid");
            var errors = ModelState
                .Where(x => x.Value.Errors.Count > 0)
                .Select(x => new { x.Key, x.Value.Errors })
                .ToArray();
        }

        return RedirectToAction("Vids", new { id = vm.Guid });
    }

in my startup im sure i messed something up -
cause i feel like all im reading a bunch of spaghetti code in the articles
and with the constant version changes even some articles from a year ago are out of date

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/View/LinkLogin/";
            options.LogoutPath = "/Account/Logout/";
            //options.Cookie.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = environment.IsDevelopment() ? Microsoft.AspNetCore.Http.CookieSecurePolicy.None : Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(35);

            //could be - 
            //options.LoginPath = "/Identity/Account/Login";
            //options.LogoutPath = "/Identity/Account/Logout";
            //options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.LoginPath = $"/Identity/Account/Login";
            options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddRazorPagesOptions(options =>
            {
                // deprecated  in3.1?
                // options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                options.Conventions.AuthorizeFolder("/View");
            });

and then later

        // routing and security
        app.UseRouting();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>  etc...

im referencing these articles:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1
https://www.yogihosting.com/aspnet-core-identity-claims/
https://www.red-gate.com/simple-talk/dotnet/net-development/using-auth-cookies-in-asp-net-core/

the claims get processed but they dont get stored
is it even possible to store these claims with an anonymous user
if yes where should i be looking for them with an anonymous user?
if no what should i be doing next?

How to insert multiple record to database at a time by ajax in asp.net core mvc with entity framework

$
0
0

I want to save records in two model where one model can get single row and second model can get multiple row. Please help me to resolve it.

controller: PatientTestsController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPatientTest(PatientTestsAndBilling ptb)
{

if (ModelState.IsValid)
{

}

return View(ptb);
}


Model : PatientTest

public class PatientTest
{
[Key]
public int Id { get; set; }

[Display(Name ="Patient Id")]
public int PatientId { get; set; }

[Display(Name ="Test Id")]
public int TestId { get; set; }

[Display(Name ="Doctor")]
public int DoctorId { get; set; }

[Display(Name="Center")]
public int CenterId { get; set; }


[Display(Name = "Test")]
[ForeignKey("TestId")]
//relation of Tests table
public virtual Tests Tests { get; set; }

[Display(Name = "Doctor Reference")]
[ForeignKey("DoctorId")]
//relation of Doctors table
public virtual Doctors Doctors { get; set; }

[Display(Name = "Center Reference")]
[ForeignKey("CenterId")]
//relation of Centers table
public virtual Centers Centers { get; set; }

[Display(Name = "Patient")]
[ForeignKey("PatientId")]
//relation of Patient table
public virtual Patient Patient { get; set; }

}

Model : PatientBilling

public class PatientTest
{
[Key]
public int Id { get; set; }

[Display(Name ="Patient Id")]
public int PatientId { get; set; }

[Display(Name ="Test Id")]
public int TestId { get; set; }

[Display(Name ="Doctor")]
public int DoctorId { get; set; }

[Display(Name="Center")]
public int CenterId { get; set; }


[Display(Name = "Test")]
[ForeignKey("TestId")]
//relation of Tests table
public virtual Tests Tests { get; set; }

[Display(Name = "Doctor Reference")]
[ForeignKey("DoctorId")]
//relation of Doctors table
public virtual Doctors Doctors { get; set; }

[Display(Name = "Center Reference")]
[ForeignKey("CenterId")]
//relation of Centers table
public virtual Centers Centers { get; set; }

[Display(Name = "Patient")]
[ForeignKey("PatientId")]
//relation of Patient table
public virtual Patient Patient { get; set; }

}

Model : PatientTestAndBilling

public class PatientTestsAndBilling
{
public List<PatientTest> patientTests { get; set; }
public PatientBilling patientBilling { get; set; }
}


this is my jquery code..

$("#save").click(function () {
var row = $('#table2 tbody tr').length;
var patientTest=[];
var patientBilling;
var j;
for (var i = 0; i < row; i++) {
j = i + 1;
patientTest.push({
PatientId: $('#patientId').val(),
TestId: $('#table2 tbody tr:nth-child('+j+')').attr('id'),
DoctorId: $('#doctor').val(),
CenterId: $('#center').val(),

});
}
patientBilling= {
PatientId: $('#patientId').val(),
TotalPrice: $('#total_price').text(),
PaidAmt: $('#total_paid').text(),
BalanceAmt: $('#balance').text(),
OtherCharges: $('#ot_charges').val(),
Discount: $('#discount').val(),
PaymentType: $('#payType').val()
};
var model = {
"patientTest": patientTest,
"patientBilling": patientBilling
}
alert(JSON.stringify(model));
$.ajax({
type: "POST",
url: "/Reception/PatientTests/AddPatientTest",
data: model,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
}
});
});

in this example I am getting only Patient Billing data not Patient test data please help me to resolve it..

ASP.NET 3.0 IhostBuilder does not contain definition of UserKestrel

$
0
0

I have ASP.NET 3.0 Application, I am getting error as IHostBuilder does not contain definition of UseKestrel. Can I Use UseKestrel or ConfigureKestrel In ASP.NET 3.0 ?  

can i abstract to a base class then override to a generic class?

$
0
0

Hi

Can i do something like this

public abstract class SomeBaseClass
{
    public abstract OtherBaseClass SomeProperty {get;set;}
}

public class SomeClass<T> : SomeBaseClass where T : OtherBaseClass 
{
    public override T SomeProperty {get;set;}
}

when i do this i get saying T doesn't match the inherited abstract member.

What i am trying to do is to have a list of SomeBaseClass which needs access to SomeProperty or doi just do IList<SomeClass<OtherBaseClass>>()

Multiple file upload

$
0
0

I would like to upload a variable list of files in ASP.NET Core MVC. So, I create dinamically with jQuery a list of:

<input type="file" name="a_file" id="a_file" class="d-none" />

All with the same name, in order to obtain na array on posting to the server. I would like to populate these, programatically, with jQuery or JavaScript, once I use another input tag to get the file name and then I would like to inject the file name in the previous input tags...

How can I populate these input tags with the files that I want to upload?

I would like to access those files in the Controller with:

public IActionResult SubmitForm1(IFormCollection form)

Could anyone help me?

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>