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

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

$
0
0

Hi, I have this error and have been looking it up on the internet.
Unfortunately i am not able to fix this problem and tried all kind of things that i found.

Here is the error:

An unhandled exception occurred while processing the request.
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

Stack Query Cookies Headers
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator+<>c__DisplayClass8_0.<CreateActivateInfo>b__1(ViewContext context)
Microsoft.Extensions.Internal.PropertyActivator<TContext>.Activate(object instance, TContext context)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.Activate(object page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync<TFilter, TFilterAsync>()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Website.Web.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.AspNetCore.Mvc;
using Website.Web.Models;

namespace Website.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Coookiesssss
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //Set database Connection from application json file
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            //add identity
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            //configure identity options
            services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });

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

                options.LoginPath = "/Identity/Account/Login";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });

            //add mvc 2.2
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //adding autorization policy's
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

            });

            //Seed atabase with new roles
            Seed.CreateRoles(app.ApplicationServices,Configuration).Wait();
        }
    }
}
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using Website.Web.Models;

namespace Website.Web.Data
{
    public static class Seed
    {
        public static async Task CreateRoles(IServiceProvider serviceProvider, IConfiguration Configuration)
        {

            var scopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
            var scope = scopeFactory.CreateScope();

            //adding customs roles
            var RoleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            string[] roleNames = { "Admin", "Manager", "Member" };
            IdentityResult roleResult;

            foreach (var roleName in roleNames)
            {
                // creating the roles and seeding them to the database
                var roleExist = await RoleManager.RoleExistsAsync(roleName);
                if (!roleExist)
                {
                    roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            // creating a super user who could maintain the web app
            var poweruser = new ApplicationUser
            {
                UserName = Configuration.GetSection("AppSettings")["UserEmail"],
                Email = Configuration.GetSection("AppSettings")["UserEmail"]
            };




            //var UserManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            //string userPassword = Configuration.GetSection("AppSettings")["UserPassword"];
            //var user = await UserManager.FindByEmailAsync(Configuration.GetSection("AppSettings")["UserEmail"]);

            //if (user == null)
            //{
            //    var createPowerUser = await UserManager.CreateAsync(poweruser, userPassword);
            //    if (createPowerUser.Succeeded)
            //    {
            //        // here we assign the new user to the "Admin" role
            //        await UserManager.AddToRoleAsync(poweruser, "Admin");
            //    }
            //}
        }
    }
}
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Website.Web.Data;

namespace Website.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var serviceProvider = services.GetRequiredService<IServiceProvider>();
                    var configuration = services.GetRequiredService<IConfiguration>();
                    Seed.CreateRoles(serviceProvider, configuration).Wait();

                }
                catch (Exception exception)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(exception, "An error occurred while creating roles");
                }
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Website.Web.Models;

namespace Website.Web.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

Thanks in advance!






UseExceptionHandler not work in netcore3 preview7

$
0
0

create a new project ,nothing changed.

And I manual throw an exception in an action.

app.UseExceptionHandler("/Home/Error");

it is worked in netcore2.2,but failed in netcore3 preview7.

when I use this code, it is worked.

app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.Redirect("/Home/Error");
                });
            });

I can't understand...

Stream data from Cloud Storage to Client Machine through Web API

$
0
0

Requirement is to allow user to upload and download large files upto 2GB from Angular 5 based SPA to google cloud storage or file storage based on deployment. Flow is SPA->Asp.NetCore WebAPI -> Google Cloud Storage.

We don't want to expose underlying storage provider to the user whether it is file system or google file storage.

The user authorization is happening at ASP.Net Core Web API layer so requests and response needs to go through web api

We have used Memory stream to buffer the response from Cloud Storage and than passed that stream to the response. We don't want to buffer the response on web server as file sizes could be very large. Below is the code which works for us but requires full stream to be buffered before sending the response

[HttpGet]
[Route("filedownload")]
public async Task<IActionResult> GetFile4(string fileName)
{
    var outputFile = new MemoryStream();
    string objectName = "objectname";
    if (!string.IsNullOrEmpty(fileName))
        objectName = fileName;
    var downloadObjectOptions = new DownloadObjectOptions();
    await helper._client.DownloadObjectAsync(helper._bucketName, objectName, outputFile,downloadObjectOptions);
    outputFile.Position = 0;
    return new FileStreamResult(outputFile, "text/csv");
}

Find a Model controller's after generating MVC Controller with views

$
0
0

.NET Core: How to find and edit the controller of an entity generated with crud?

API Method to Return "../images/xyz.png" is returning "/api/images/xyz.png"

$
0
0

Hi

I have a service method with some hardcoded "C#" - this service API is part of the main Asp.Net MVC Core web application (not a separate project).

Error message: http://localhost:5000/api/images/blockdevice.png 404 (not found).

//READ - TREE NODES FOR {SYSTEM - TABLE - LOOKUP SETUP etc.}
[HttpPost]
public async Task<IActionResult> ReadSystemTree([FromBody]object route)
{

.....
icon = "../images/blockdevice.png", 
....

}

The right way of hosting worker threads on each rounded hour

$
0
0

Hi,

I'm making an application which is supposed to have multiple threads/services (bots) running. Those threads are supposed to check an API for current currency values. There will be some calculations on each rounded hour (e.g. 10:00, 11:00, etc).

Currently, I'm running Angular (front-end) and ASP.NET Core 2.2 MVC + SignalR (back-end).

What's the right way of hosting those threads/services? Assuming those threads are spawned based on database records.

I was looking at https://docs.microsoft.com/en-us/aspnet/core/signalr/background-services?view=aspnetcore-2.2 but I'm not quite if that's the right solution since I have to display the results in the front-end with SignalR if they match to certain conditions.

What's the right way of doing that scenario?

.net core how to render to login page after login?

$
0
0

what can I do to redirect user to Index HomeController page? Note: I'm using the default authetication layout of .NET CORE 2.1.

Blazor in load balanced environment?

$
0
0

 Hello all,

 My team is evaluating Blazor as an alternative to Angular for some upcoming front end work, and have been thoroughly impressed with it. At this stage of its development we think it will serve our needs nicely, but we still are in need of some guidance.

 Our remaining questions have to do with how the server side version of Blazor would behave in a load balanced environment. The State Management section of the Blazor docs (https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0) does a great job of answering most of the questions we’ve had, and we plan on following that article’s recommendations. Here is what we are still wondering:

  1. Are there any changes necessary to the load balancer itself for this to work? We use sticky sessions for our current apps. I will need to explain any such changes to our infrastructure team.
  2. Aside from the changes necessary for .NET Core apps in general, are there any configuration changes necessary on the servers for Blazor to work in a load balanced environment? We are using Windows Server 2012, and will upgrade to 2016 at some point.
  3. Are there any other pitfalls we should be aware of? We have no experience with SignalR or other Websockets-based frameworks.

Thank you in advance to anyone who can weigh in on this.

-Craig


Web API routing doesn't appreciate non-public controllers

$
0
0

Pre-requirements

Create default netcoreapp2.2 web api project (I use Rider, but I believe it doesn't really matter).

Start the project.

Call an action in a controller and ensure that it works.

Change

Change the controller's access modifier from public to internal

Expected behavior

The same api call works

Actual behavior

The same api call return 404

Why I care

I used to close access modifiers as hard as I can. Once I saw developers that references anything from anywhere for no reason, and it was really hard to track. I'd love to have a flow that could warn me about wrong references.

If a class should not be referenced from another project, it's access modifier should be internal. Well, due to that's whatinternal means.

The actual flow seems weird to me: reflection should not think about access modifiers. For example, you are able to (de)serialize any class with any fields.

Unfortunately, I couldn't find a code where the route resolving happens. Could anyone link the file?

WEB API and Docker host issue

$
0
0

Dear all,

I have a simple web api project for which I need to host it under Docker image.

For that I have added the following docker file to my root project :

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-nanoserver-1709 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-nanoserver-1709 AS build
WORKDIR /src
COPY ["BooksApi/BooksApi.csproj", "BooksApi/"]
RUN dotnet restore "BooksApi/BooksApi.csproj"
COPY . .
WORKDIR "/src/BooksApi"
RUN dotnet build "BooksApi.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "BooksApi.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "BooksApi.dll"]

If I compile and run the app from visual studio , docker file gets compile and runn properly and I can hit my web site api.

Then I have try to compile and run doker image outide visual studio using docker command as explain in different post.
For that I open a powershell command and then run  the follwing command from the root of my project :

docker build -t myimage .

by doing so I get a failure error as desribed below :

Docker error

Any idea what can be wrong ?

regards

How to select max column value from dataBase in c# .net core?

$
0
0

if (ModelState.IsValid)
{

//the select query here 

}

I have a problem with returnUrl for authentication

$
0
0

Hi,

I have a problem with returnUrl for authentication. I used returnUrl in my form 

<form id="profile-form" method="post" asp-controller="Account" asp-action="UserAccount"
    asp-route-returnUrl="@Html.Raw(Context.Request.Path)" ><button class="btn btn-primary" type="submit">Submit</button></form>

        [Authorize(Roles = "Admin, User")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UserAccount(AccountModel model, string returnUrl)
        {
            return LocalRedirect(returnUrl);
        }
            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

                options.LoginPath = "/AccountSystem/UserLogin";//options.ReturnUrlParameter = "returnUrl";
                options.LogoutPath = "/AccountSystem/UserLogout";
                options.AccessDeniedPath = "/AccountSystem/UserAccessDenied";
                options.SlidingExpiration = true;
            });
public IActionResult UserLogin(string returnUrl)
        {
            int languageId = HttpContext.Session.GetJSon<int>("LanguageId");var queryArray = returnUrl.Split("returnUrl=");
            if (queryArray.Length == 2)
            {
                returnUrl = queryArray[1].ToString();
            }
            if (queryArray.Length == 1)
            {
                returnUrl = queryArray[0].ToString();
            }

            var PageAccount = _unitOfWork.Pages.GetAll().Include(i => i.PageRoot).ThenInclude(i => i.Language)
                                        .Where(i => i.IsApproved && i.Language.IsApproved &&
                                                    i.PageRoot.ActionName == "UserLogin" &&
                                                    i.LanguageId == languageId).FirstOrDefault();

            return LocalRedirect("~/" + PageAccount.PageRoot.RootName + "/" + PageAccount.Url + "?returnUrl=" + returnUrl);
        }

when The authentication cookie timeout, I get this url : 

returnUrl="/Account/UserAccount?returnUrl=%2Fkullanici%2Fhesabim"

in this url, there is two question mark. I have to get returnUrl in form when that is posted. 

I figured out it. var queryArray = returnUrl.Split("returnUrl=");

But there is a problem. why is there two question mark ?

I tried to change returnUrl with loginReturnUrl

//options.ReturnUrlParameter = "loginReturnUrl";

then I get the same result again. 

how can I change my logic in this structure then I get just one question mark in returnUrl ?

thank you

Oracle connectivity issue for asp.net core 2.1 web api from docker container

$
0
0
Hi All,
I am trying to connect oracle database using Oracle.ManagedDataAccess.Core 2.18.3 ; i am using asp.net core 2.1 web api. When i run this code on my local machin it works fine but when dockerised it and deployed it under container it fails with below error

ORA-00604 : error occured at recursive SQL level 1
ORA-01882 : timezone region not found

I searched on internet and found below solutions but both of them are not working for me ; Please help asap.

1. Set timezone in docket file as below
ENV TZ=America/New_York
2. Also setup timezone to open oracle connection as below
Oracle globalization info = con.GetSession();
info.TimeZone = "America/New_York";
con.SetSessionInfo(info);


Please help

SQLCipher Decryption in .NetCore 3 preview 6

$
0
0

I have an ASP.Net core (3.0.100-preview6-012264) project need to access password protected SQLite database that was encrypted by DB Browser for SQLCipher.

I followed the steps of the link below, use Microsoft.EntityFrameworkCore.Sqlite.Core and SQLitePCLRaw.bundle_sqlcipher package

https://github.com/paragpkulkarni/SQLiteEncryptionUsingEFCore

I also followed its reference, use Microsoft.Data.Sqlite package

https://www.bricelam.net/2016/06/13/sqlite-encryption.html

they didn't work!!

How could I access this password protected SQLite which encrypted by DB Browser for SQLCipher?

How to generate parametrized insert statement for details with master master work but details not ?

$
0
0

problem

when get data from json file for master it work but details not work ?

i work on web application asp.net core 2.1 i get data as json then concatenate them for master and details and there are another layer will execute it .

i success generate insert statement on master

but details cannot do

so that i need to add details with master 

{"master":{"table":"master_table","fields":{"name":"bar","address":"fleet street","phone":"555"},"keys":{"id":1,"branch_id":1}},"details":[{"table":"detail1_table","keys":{"id":1,"branch_id":1,"LineNumber":1},"fields":{"ItemCode":"item-5050","Quantity":10,"Price":50,"Total":500}},{"table":"detail1_table","keys":{"id":1,"branch_id":1,"LineNumber":2},"fields":{"ItemCode":"item-9050","Quantity":5,"Price":20,"Total":100}}]}

Expected Result is 3 statement insert :

// generated success

INSERT INTO master_table(id, branch_id, name, address, phone) VALUES(@id, @branch_id, @name, @address, @phone);

// generated problem

insert into detail1_table(id,branch_id,LineNumber,ItemCode,Quantity,Price,Total) values (@id,@branch_id,@LineNumber,@ItemCode,@Quantity,@Price,@Total)


// generated problem


insert into detail1_table(id,branch_id,LineNumber,ItemCode,Quantity,Price,Total) values (@id,@branch_id,@LineNumber,@ItemCode,@Quantity,@Price,@Total)



What I have tried:


publicstaticclassJsonHelper{publicstaticstringGetInsertStatement(JToken mastertoken){returnstring.Format("INSERT INTO {0}({1}) VALUES({2});",
                mastertoken["table"],GetFieldParameterNames(mastertoken),GetFieldParameterNames(mastertoken,false));}staticstringGetFieldParameterNames(JToken mastertoken,bool fieldOnly =true){string p = fieldOnly ?string.Empty:"@";returnstring.Concat(string.Join(", ", mastertoken["keys"].Cast<JProperty>().Select(jp => p + jp.Name)),", ",string.Join(", ", mastertoken["fields"].Cast<JProperty>().Select(jp => p + jp.Name)));}publicstaticList<SqlParameter>GetSqlParams(JToken mastertoken){List<SqlParameter> para =newList<SqlParameter>();foreach(JToken jt in mastertoken["keys"])
                para.Add(newSqlParameter("@"+ jt.ToObject<JProperty>().Name, jt.First));foreach(JToken jt in mastertoken["fields"])
                para.Add(newSqlParameter("@"+ jt.ToObject<JProperty>().Name, jt.First));return para;}publicstaticstringGetInsertStatmentText(stringJsonData){stringInsert="";JObject jo =JObject.Parse(JsonData);JToken m = jo["master"];string connectionstring ="Server=sdfff-PC\\SQL2014;Database=sqlm;User Id=sa;Password=abc123;";//change connection stringusing(SqlConnection connection =newSqlConnection(connectionstring)){using(SqlCommand command =newSqlCommand(JsonHelper.GetInsertStatement(m), connection)){
                    connection.Open();List<SqlParameter> lsp =JsonHelper.GetSqlParams(jo["master"]);foreach(SqlParameter sqp in lsp)

                        command.Parameters.Add(sqp);Insert= command.CommandText;}}returnInsert;}
        program.csstaticvoidMain(string[] args){stringJsonData=File.ReadAllText("D:\\2.json");string insertStatment =JsonHelper.GetInsertStatmentText(JsonData);}


Is System.Drawing.Common a reasonable choice for drawing in an ASP.NET Core app?

$
0
0

I want to draw circles, rectangles, triangles, and text on a ASP.NET Core app and deploy that to Azure.

Is Microsoft's System.Drawing.Common a reasonable package for this?

//homopterous64.rssing.com/chan-54021951/article6097-live.html

$
0
0

Added a MVC Controller view using Entity Framework

In the orders Model I have 

[Required]
[Display(Name = "Action Type", Description = "Action Type.", Prompt = "Action Type", ShortName = "Action", Order = 10)]
public int ActionID { get; set; }

[Required]
[Display(Name = "Transaction Type", Description = "Transaction Type.", Prompt = "Transaction Type", ShortName = "Transaction", Order = 11)]
public int TransactionID { get; set; }

public ActionType ActionType { get; set; }
public TransactionType TransactionType { get; set; }

------------------------------------------------------------------

ActionType Model

[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }

[MaxLength(32)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Action Type is Required.")]
[Display(Name = "Action", Description = "The Action Type.", Prompt = "Action Type", ShortName = "Action", Order = 1)]
public string Action { get; set; }

public ICollection<Order> Orders { get; set; }

---------------------------------------------------------------------------

TransactionType Model

[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }

[MaxLength(32)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Transaction Type is Required.")]
[Display(Name = "Transaction", Description = "The Transaction Type.", Prompt = "Transaction Type", ShortName = "Transaction", Order = 1)]
public string Type { get; set; }

public ICollection<Order> Orders { get; set; }

---------------------------------------------------------------------------

In Create.cshtml I want to change these to a list of ActionType and TransactionType but this is generated:

<div class="form-group">
<label asp-for="ActionID" class="control-label"></label>
<input asp-for="ActionID" class="form-control" />
<span asp-validation-for="ActionID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TransactionID" class="control-label"></label>
<input asp-for="TransactionID" class="for-control"/>
<span asp-validation-for="TransactionID" class="text-danger"></span>
</div>

The Controller Create has no model

// GET: Trade/Orders/Create
public IActionResult CreateAsync()
{

return View();
}

and the Create.cshtml as no @model IEnumerable

@model Data_Store.Trading.Order

So what is the correct way to do this so I have 2 dropdown select lists.

MVC @Request["someName"] is there an equivalent in Core Razor Pages

$
0
0

In MVC after postback I can persist a hiddenfield value using

<input type="hidden" id="hdfSearchType" name="hdfSearchType" value="@Request["hdfSearchType"]" />

How can I have same behavior in Razor Pages other than using page property like

<input type="hidden" asp-for="hdfSearchType" name="hdfSearchType" />

Which one to choose between DotNet Core MVC or Razor Pages for the future

$
0
0

I am shifting to DotNet Core and can see the options of using both Core MVC orRazor Pages

Both have their differences amongst many. Core MVC is suitable for API Calls/Complex applications whereas Razor Pages are suitable for HTML Views.

My question is do we expect one standard to dominate in the future or both will run in parallel? In the later option, we have to master both programming styles.

Thanks.

Dynamic table using html razor code has check box. Need to select and consume check box data without javascript

$
0
0

Dynamic table using html razor code has check box. Need to select and consume check box data without javascript

hello, I am trying to create a table with Model information.  Each row has a check box that is not part of the model.
When any row in the check box and the form is submitted, I want to consume any checked rows to include in the model database.

So the table is like this:

<tbody>
@foreach (var question in Model.question)
 {
  <tr>
     <td>@question.Id</td>
     <td>@question.TestingGroup</td>
     <td>@question.TestArea</td>
     <td>@question.Description</td>
     <td><input type="checkbox" /></td>
 </tr>

 }
</tbody>

This iterates over a table that is dynamic, so the number of rows is different every time.  But when hit save I want to save the selected rows.

I want to do this without including a check box in my model or using javascript.  Is there a way?

Viewing all 9386 articles
Browse latest View live


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