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

Cannot implicitly convert type System.Collections.Generic.IEnumerable to System.Collections.Generic.IEnumerable. An explicit conversion exists

$
0
0

Hi, I'm learning asp.net mvc and I have this error:

Cannot implicitly convert type System.Collections.Generic.IEnumerable<LMS.Models.Tareas> to System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>. An explicit conversion exists

I want to retrieve information from tareas database in a dropdownlist,the error is presented in the view

I have this view model:

 public class CalificacionyTareaViewModel
{
    public IEnumerable<Tareas> TareasList { get; set; }



    public Calificaciones Calificaciones { get; set; }

    public IEnumerable<Estudiantes> EstudiantesList { get; set; }


    public string StatusMessage { get; set; }



}

I have a method called Create:

public async Task<IActionResult> Create()
    {






        CalificacionyTareaViewModel model = new CalificacionyTareaViewModel()
        {
            TareasList = await _db.Tareas.ToListAsync(),

            Calificaciones = new Models.Calificaciones(),




            EstudiantesList = await _db.Estudiantes.ToListAsync()




        };



        return View(model);
    }

And I have a view called create:

<form method="post" asp-action="Create"><div class="border backgroundWhite"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group row"><div class="col-3"><label asp-for="Calificaciones.TareaId" class="col-form-label"></label></div><div class="col-5"><select  asp-for="Calificaciones.TareaId" asp-items="Model.TareasList" class="form-control"></select></div></div><div class="form-group row"><div class="col-5 offset-2"><partial name="_CreateAndBackToListButton" /></div></div></div>

How I can solve this problem?


Identity UserManager CreateAsync does not write to database

$
0
0

It doesn't give any errors or warnings but it doesn't insert in the database. Seems like it's only in memory.

Also UserManager's FindByNameAsync can't check users already created in the database, probably for the same reason.

Here is my Controller:

public class AccountController : Controller
    {
        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;

        public AccountController(UserManager<User> userManager, SignInManager<User> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            if (ModelState.IsValid)
            {
                var result = await _userManager.CreateAsync(user, user.Password);

                if (result.Succeeded)
                {
                    Console.WriteLine("OK");
                }

                var username = await _userManager.FindByNameAsync(user.UserName);

                if (username != null)
                {
                    //sign in
                    var signInResult = await _signInManager.PasswordSignInAsync(user.UserName, user.Password, false, false);

                    if (signInResult.Succeeded)
                    {
                        return RedirectToAction("Index", "ProjectCampaign");
                    }
                }
            }
            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();

            return RedirectToAction("Login", "Account");
        }
    }

Startup.cs

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)
        {
            services.AddDbContext<RandomContext>(config =>
            {
                config.UseInMemoryDatabase("Memory");
            });

            services.AddIdentity<User, Role>(config => {
                config.Password.RequireDigit = false;
                config.Password.RequiredLength = 4;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase = false;
            })
                .AddEntityFrameworkStores<RandomContext>()
                .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                config.Cookie.Name = "AuthCookie";
                config.LoginPath = "/Account/Login";
                config.ExpireTimeSpan = TimeSpan.FromMinutes(1);
            });

            services.AddScoped<RandomContext>();

            services.AddControllersWithViews().AddRazorRuntimeCompilation();
        }

        // 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();
            }
            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.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

User.cs

public partial class User : IdentityUser<int>
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "Username is required")]
        public override string UserName { get; set; }
        [Required(ErrorMessage = "Password is required")]
        public string Password { get; set; }
    }

RandomContext.cs

public partial class RandomContext : IdentityDbContext<User, Role, int>
    {
        public RandomContext()
        {
        }

        public RandomContext(DbContextOptions<RandomContext> options)
            : base(options)
        {
        }

        public virtual DbSet<ProjectCampaign> ProjectCampaigns { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<User> Users { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer("Server=.;Database=Random;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<ProjectCampaign>(entity =>
            {
                entity.ToTable("ProjectCampaign");

                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.Campaign)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.CreateDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())")
                    .HasAnnotation("Relational:ColumnType", "datetime");

                entity.Property(e => e.Project)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Role>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.CreateDate)
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())")
                    .HasAnnotation("Relational:ColumnType", "datetime");

                entity.Property(e => e.Description)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<User>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.Password).IsRequired();

                entity.Property(e => e.UserName)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }

If you need more detail please let me know.

Unable to install nuget packages in Ubuntu 18.

$
0
0

I am following the .NET Core tutorial from Microsoft Official documentation. After installing the sdk I am unable to install the nuget packages.

These are the following error.

Command - dotnet tool install --global dotnet-ef

error : Unable to load the service index for source https://api.nuget.org/v3/index.json. [/tmp/xd3wm00b.zlm/restore.csproj] 

error : The HTTP request to 'GET https://api.nuget.org/v3/index.json' has timed out after 100000ms. [/tmp/xd3wm00b.zlm/restore.csproj]

Notes-

When I am trying to access the following link - https://api.nuget.org/v3/index.json with curl or with my browser I am able to access it.

Also the paths are already properly configured at my end.

export DOTNET_ROOT=$HOME/dotnet
export PATH=$PATH:$HOME/dotnet
export PATH=$PATH:$HOME/.dotnet/tools

But I am still unable to install the nuget packages on my linux machine.

How to bind data from List to cshtml page

$
0
0

Hi, I've get data from API and store in List<Dictionary<string, object>>. But I can't bind this data in *.cshtml page. Can anyone help me how I can bind data from List<Dictionary<string, object>> to html table in *.cshtml page.

Here is my API code:

var contentString = await result.Content.ReadAsStringAsync();
var values = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(contentString);

can't extract data from List<Dictionary<string, object>>. Please anyone help me to extract data from this list. I'm new in asp.net core.

Thanks in advance.

how to redirect UI application to access denied on every type of request in .net core

$
0
0

I have two application one is API and one is UI, in api some methods or permission based return as per below code

if (!await _permissionMasterServcie.Authorize(StandardPermissionProvider.Category, PermissionType.View).ConfigureAwait(false))
        {
            return AccessDenied();
        }

then this consume in UI .net core application. In this application some method is call by jQuery or Kendoui grid, some MVC so when UI .net core application consume API its got status code "401 Unauthorized" so can we redirect every request in UI application to access denied page when status code received "401 Unauthorized". By any attribute or any configuration in startup file. I didn't get how to do that.

UI .net core application consuming api

public virtual async Task<IRestResponse> PostAsync(string request, string endPoint, string action, string token)
    {
        string url = endPoint + action;
        _restClient.BaseUrl = new Uri(url);
        _restRequest.Method = Method.POST;
        _restRequest.Timeout = 900000;
        _restRequest.Parameters.Clear();
        _restRequest.AddHeader("Authorization", token);
        _restRequest.AddParameter("application/json", request, ParameterType.RequestBody);
        IRestResponse response = await _restClient.ExecuteAsync(_restRequest, Method.POST);
        return response;
    }

here I'm getting response and status code both, here can we redirect every request to access denied for 401 code

How to deploy BLAZOR multiproject solution in one app (IIS) ?

applicationsettings.json usage ?

$
0
0

Hi,

I am using Asp.Net Core 3.1 and can see the file appsettings.json.

Can I use more than one application settings file like "appsettings.json", "appsettings.Development.json", "appsettings.Staging.json" & "appsettings.Production.json"?

If yes, could you please explain the steps and json file order, if any?

Thanks in advance.

General Advice on how to copy data when checkbox checked

$
0
0

Hi there,

I just want some general advice on how to achieve something, please.

I have a create form (brand.cs), and I want to stick a checkbox at the top of the form. If the user checks the box then I want to fill some the boxes with existing from a different model (company.cs)

What would be the best way of achieving this? Would it be a viewmodel with Brand and Company together? Then use some type of if statement in the view?

Any thoughts and opinions would be appreciated.

Regards,

Dave.


How to use VB module in asp.net core c# project

Are properties from razor page model that are set through form in same page safe from mass assignment attack?

$
0
0

Is it enought to use [BindProperty] for every field used in form in razor page model to avoid attack?

Where to use Client Certificate, questions needs your answers?

$
0
0

I am building a small feature in ASP.NET Core Certificate authentication as given in official https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1. Note: I am not building APIs, I am just trying to secure some Action methods of some controllers so that these secured action methods are opened only when the client has the client certificate.  

What I want is that when a user opens the URL of these secured Action methods in the browser then only those users that have client certificate in their PCs are able to view them, for others without client certificate - unauthorized message should be shown.

You can also say that I am using this concept in place of login by password feature.

I have few question which needs answers:

  1. After I have creating the Client Certificate from Root certificate as given under the heading (Create child certificate from root certificate), how I should give the certificate to the client - Manually? or there is some automatic procedure? Please provide answer.
  2. Suppose the client has the client certificate, now he opens a URL of the site in the browser that needs client certificate, the question is how the certificate is attached to the browser - what is the procedure in ASP.NET Core 3.1? 

Waiting for your valuable answers.

Thank you so much!

How to delete cookie after the browser closed in asp.net core

$
0
0

I'm implementing an asp.net core 3.1 project. My problem is I want when the user close the browser, the cookie goes to get deleted . For implementing the project, I authenticate the user via ldap with the below expression in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{

services.AddControllersWithViews();

services.AddDbContext<CSDContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CSDContext")));


services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
// Cookie settings

//set the cookie name here
options.Cookie.Name = "UserLoginCookie"; // Name of cookie
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

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

services.AddSession();
services.AddSingleton<MySharedDataViewComponent>();
services.AddHttpContextAccessor();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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.UseSession();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

});
}

I have also a file  that is called, deleteCookie.js and its content is like the following:

function deleteCookie(name) {
setCookie(name, "", -1);
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
$(window).unload(function () {
deleteCookie('UserLoginCookie');
});

function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

And in my index view, I've written following code to use the deleteCookie.js and use the deleteCookie() function.

<script language="JavaScript" type="text/javascript" src="~/js/deleteCookie.js"></script>

@section Scripts{
<script>
$(window).unload(deleteCookie('UserLoginCookie'));
console.log("coockie:" + getCookie('UserLoginCookie'));
</script>

}

But my code doesn't work. I appreciae if anyone helps me to solve the issue.

httpsys on docker with windows container

$
0
0

Hi. I developed the application on .net core 2.2 with

Http.Sys
and I am trying to run it on docker with windows container

Here is the dockerfile

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-nanoserver-1903 AS base
WORKDIR /app
EXPOSE 5003
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-nanoserver-1903 AS build
WORKDIR /src
RUN mkdir IConductAPI.Core


COPY ["IConductAPI.Core/IConductCore.API.csproj", "IConductAPI.Core/"]
COPY ["IConduct.Model/IConductCore.Model.csproj", "IConduct.Model/"]
COPY ["IConduct.DAL/IConductCore.DAL.csproj", "IConduct.DAL/"]
COPY ["IConduct.LicenseCore/IConductCore.LicenseCore.csproj", "IConduct.LicenseCore/"]
COPY ["IConduct.GeneralHelpers/IConductCore.GeneralHelpers.csproj", "IConduct.GeneralHelpers/"]
RUN dotnet restore "IConductAPI.Core/IConductCore.API.csproj"
COPY . .
WORKDIR "/src/IConductAPI.Core"
RUN dotnet build "IConductCore.API.csproj" -c Release -o /app/build

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

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
#ENTRYPOINT ["dotnet", "IConductCore.API.dll"]
CMD ["dotnet","IConductCore.API.dll","--console"]

I run docker build -t iconductapi . to build the image

and run the image with

docker run -it -p 5003:5003 -e ASPNETCORE_URLS="http://+" -e ASPNETCORE_ENVIRONMENT=Development --name icapi iconductapi

The output is :

[16:13:57.865+03:00 (0001)] [INF] Dependency Injection services have been configured.

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]

User profile is available. Using 'C:\Users\ContainerUser\AppData\Local\ASP.NET\DataProtection-Keys' as key reposit

ory and Windows DPAPI to encrypt keys at rest.

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58]

Creating key {b523599c-9920-448c-a0f5-049b3fc06f52} with creation date 2020-08-16 13:13:57Z, activation date 2020-

08-16 13:13:57Z, and expiration date 2020-11-14 13:13:57Z.

info: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[39]

Writing data to file 'C:\Users\ContainerUser\AppData\Local\ASP.NET\DataProtection-Keys\key-b523599c-9920-448c-a0f5

-049b3fc06f52.xml'.

[16:13:58.022+03:00 (0001)] [INF] Applying configuration...

[16:13:58.024+03:00 (0001)] [INF] Use Cloudflare forward header options.

[16:13:59.096+03:00 (0001)] [INF] Use Swagger.

[16:13:59.240+03:00 (0001)] [INF] Use CORS.

[16:13:59.241+03:00 (0001)] [INF] Configuration has been aplied.

warn: Microsoft.AspNetCore.Server.HttpSys.MessagePump[0]

Overriding address(es) 'http://+'. Binding to endpoints added to UrlPrefixes instead.

info: Microsoft.AspNetCore.Server.HttpSys.HttpSysListener[0]

Start

info: Microsoft.AspNetCore.Server.HttpSys.HttpSysListener[0]

Listening on prefix: http://localhost:5003/

netstat on the container shows that the port is listening on 5003

However any end point that I am trying to hit gives me 403 error. For example , I have swagger and access it with ...:5003/swagger.html but get Forbidden URL

The application is NOT NEW and was executed without any problems without DOCKER. There isno authentication defined in the API

ASP.NET Core Web API Controller

$
0
0

I'm trying to write my very first ASP.NET Core Web API Projects for a client.

I'm looking for advice if I'm creating my controllers the right way. Thank you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChaxAPI.Component.Interfaces;
using ChaxAPI.Models;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ChaxAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TransactionController : ControllerBase
    {
        private readonly ITransactionService _transactionService;

        public TransactionController(ITransactionService transactionService)
        {
            _transactionService = transactionService;
        }


        // GET: api/<TransactionController>
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            return Ok(await _transactionService.GetAllAsync());
        }

        // GET api/<TransactionController>/5
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            return Ok(await _transactionService.GetId(id));
        }

        // POST api/<TransactionController>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] TRANSACTION transaction)
        {
            return Ok(await _transactionService.CreateAsync(transaction));
        }

        // PUT api/<TransactionController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, TRANSACTION transaction)
        {
            return Ok(await _transactionService.UpdateAsync(transaction));
        }

        // DELETE api/<TransactionController>/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await _transactionService.DeleteAsync(id));
        }
    }
}

Increment Session Variable Every Second Using A For Loop In The Controller In ASP NET Core

$
0
0

I would like to write a for loop in the controller that increments a session variable every second in ASP Net Core. I would like to only do the for loop in the controller, and display the data in the view.

However, when I write a for loop, the session variable only displays one result, and does not increment.

Ideally, I would like to mimick this example here JS Fiddle Increment Example but it is written in Javascript and jQuery:

$(document).ready(function () {
var number = parseInt($('#test').text(), 10) || 0; // Get the number from paragraph


// Called the function in each second
var interval = setInterval(function () {
    $('#test').text(number++); // Update the value in paragraph

    if (number > 1000) {
        clearInterval(interval); // If exceeded 100, clear interval
    }
}, 1000); // Run for each second
});

Export data to xml File from Controller?

$
0
0

First of all, I have to say that I am not a programmer and that I stumble through the code more than I walk.
So please bear with me.

I want to export data to an xml file.
To display the data, they are generated in the Controller and displayed in a View.
That works so far without any problems.
But now I have to export this data to an xml file.
I started trying that in the Controller. Creating the file with the correct structure already works.
Now I have the problem how to read/generate the data directly in the Controller or write it to my file.

In the View I do this with: "@foreach (var item in Model)"
But that doesn't work in the Controller.
I guess it's very easy, but I can't figure it out.
Can anyone tell me how I can solve this?
Is the Controller the right place for this or do I have to approach it completely differently?

Here is the code from my Controller.

public async Task<IActionResult> Orders(DateTime? startdate, DateTime? enddate, string src_kunde, string src_stadt, int src_order)
{
    ViewData["Message"] = "WooCommerce";
    ViewBag.startdate = startdate;
    ViewBag.enddate = enddate;
    ViewBag.src_kunde = src_kunde;
    ViewBag.src_stadt = src_stadt;
    ViewBag.src_order = src_order;

    RestAPI rest = new RestAPI("https://xxx.com/wp-json/wc/v3/", "ck_xxx", "cs_xxx");
    WCObject wc = new WCObject(rest);

    var orders = await wc.Order.GetAll(dic);

    if (startdate != null && enddate == null)...

    if (startdate == null && enddate != null)...

    if (startdate != null && enddate != null)...

    if (src_kunde != null)...

    // create DataSet
    DataSet ds = CreateDynamicDataSet();
    ds.WriteXml(@"C:\Temp\Orders.xml");
    return View(orders);
}


private DataSet CreateDynamicDataSet()
{
    DataSet ds = new DataSet("ERKLAERUNGS_UEBERMITTLUNG");

    // <INFO_DATEN>
    DataTable INFO_DATEN = new DataTable("INFO_DATEN");
    INFO_DATEN.Columns.Add(new DataColumn("ART_IDENTIFIKATIONSBEGRIFF", Type.GetType("System.String")));
    INFO_DATEN.Columns.Add(new DataColumn("IDENTIFIKATIONSBEGRIFF", Type.GetType("System.String")));
    INFO_DATEN.Columns.Add(new DataColumn("PAKET_NR", Type.GetType("System.String")));
    INFO_DATEN.Columns.Add(new DataColumn("DATUM_ERSTELLUNG", Type.GetType("System.String")));
    INFO_DATEN.Columns.Add(new DataColumn("UHRZEIT_ERSTELLUNG", Type.GetType("System.String")));
    INFO_DATEN.Columns.Add(new DataColumn("ANZAHL_ERKLAERUNGEN", Type.GetType("System.String")));
    ds.Tables.Add(INFO_DATEN);

    // <ERKLAERUNG art="U13">
    DataTable ERKLAERUNG = new DataTable("ERKLAERUNG");
    ERKLAERUNG.Columns.Add(new DataColumn("CatID", Type.GetType("System.Int32")));
    ERKLAERUNG.Columns.Add(new DataColumn("SATZNR", Type.GetType("System.Int32")));
    ERKLAERUNG.PrimaryKey = new DataColumn[] { ERKLAERUNG.Columns["CatID"] };
    ds.Tables.Add(ERKLAERUNG);

    // <ALLGEMEINE_DATEN>
    DataTable ALLGEMEINE_DATEN = new DataTable("ALLGEMEINE_DATEN");
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("ANBRINGEN", Type.GetType("System.String")));
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("ZRVON", Type.GetType("System.String")));
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("ZRBIS", Type.GetType("System.String")));
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("FASTNR", Type.GetType("System.String")));
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("KUNDENINFO", Type.GetType("System.String")));
    ALLGEMEINE_DATEN.Columns.Add(new DataColumn("CatId", Type.GetType("System.Int32")));
    ds.Tables.Add(ALLGEMEINE_DATEN);

    // <ZM>
    DataTable ZM = new DataTable("ZM");
    ZM.Columns.Add(new DataColumn("UID_MS", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("SUM_BGL", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("DREIECK", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("SOLEI", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("KLAG", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("UID_UE", Type.GetType("System.String")));
    ZM.Columns.Add(new DataColumn("CatId", Type.GetType("System.Int32")));
    ds.Tables.Add(ZM);

    // <GESAMTRUECKZIEHUNG>
    DataTable GESAMTRUECKZIEHUNG = new DataTable("GESAMTRUECKZIEHUNG");
    GESAMTRUECKZIEHUNG.Columns.Add(new DataColumn("GESAMTRUECK", Type.GetType("System.String")));
    GESAMTRUECKZIEHUNG.Columns.Add(new DataColumn("CatId", Type.GetType("System.Int32")));
    ds.Tables.Add(GESAMTRUECKZIEHUNG);


    //add relations to the tables here
    ds.Relations.Add("CatSubCat", ERKLAERUNG.Columns["CatID"], ALLGEMEINE_DATEN.Columns["CatID"]);
    ds.Relations["CatSubCat"].Nested = true;
    ds.Relations.Add("CatSubCat2", ERKLAERUNG.Columns["CatID"], ZM.Columns["CatID"]);
    ds.Relations["CatSubCat2"].Nested = true;
    ds.Relations.Add("CatSubCat3", ERKLAERUNG.Columns["CatID"], GESAMTRUECKZIEHUNG.Columns["CatID"]);
    ds.Relations["CatSubCat3"].Nested = true;

    DataRow newRow;
// HERE I HAVE TO INSERT THE DATA // <INFO_DATEN> newRow = INFO_DATEN.NewRow(); newRow["ART_IDENTIFIKATIONSBEGRIFF"] = "FASTNR"; newRow["IDENTIFIKATIONSBEGRIFF"] = "989999999"; newRow["PAKET_NR"] = "999999999"; newRow["DATUM_ERSTELLUNG"] = "JJJJ-MM-TT"; newRow["UHRZEIT_ERSTELLUNG"] = "HH:MM:SS"; newRow["ANZAHL_ERKLAERUNGEN"] = "12"; INFO_DATEN.Rows.Add(newRow); // <ERKLAERUNG art="U13"> newRow = ERKLAERUNG.NewRow(); newRow["CatID"] = "1"; newRow["SATZNR"] = "1234565432"; ERKLAERUNG.Rows.Add(newRow); // <ALLGEMEINE_DATEN> newRow = ALLGEMEINE_DATEN.NewRow(); newRow["ANBRINGEN"] = "U13"; newRow["ZRVON"] = "JJJJ-MM"; newRow["ZRBIS"] = "JJJJ-MM"; newRow["FASTNR"] = "989999999"; newRow["KUNDENINFO"] = "some text"; newRow["CatID"] = "1"; ALLGEMEINE_DATEN.Rows.Add(newRow); // <ZM>
// HERE I NEED A LOOP LIKE @foreach (var in item in Model) newRow = ZM.NewRow(); newRow["UID_MS"] = "DE11111112511"; newRow["SUM_BGL"] = "-9999999999"; newRow["DREIECK"] = "1"; newRow["SOLEI"] = "1"; newRow["KLAG"] = "1"; newRow["UID_UE"] = "DE11111112511"; newRow["CatID"] = "1"; ZM.Rows.Add(newRow); newRow = ZM.NewRow(); newRow["CatID"] = "1"; newRow["UID_MS"] = "DE26790342511"; newRow["SUM_BGL"] = "123.34"; newRow["DREIECK"] = "1"; newRow["SOLEI"] = "1"; newRow["KLAG"] = "1"; newRow["UID_UE"] = "DE11111112511"; ZM.Rows.Add(newRow);
// END OF LOOP // <GESAMTRUECKZIEHUNG> newRow = GESAMTRUECKZIEHUNG.NewRow(); newRow["CatID"] = "1"; newRow["GESAMTRUECK"] = "J"; GESAMTRUECKZIEHUNG.Rows.Add(newRow); ds.AcceptChanges(); return ds; }

Hope that anyone understand my problem an can help me with this.

Pass IEnumerable List of Specific Type To the Post Action

$
0
0

I have a question if any one can help me with tha answer

i'm working with asp.net mvc project

From my understanding the "SentencesList " in the ViewModel would be populated from the get action and passed to the view

then i used it to iterate through and display each record

is there any possible way to pass the "SentencesList" again to the post action if modified and with the new created sentences?

because i want the id's of the passed sentences to update the text if it is modified by the user and create new objects of type "Sentence"

Get Action

        public async Task<IActionResult> Edit(int? id)
        {
........
            var story = await _db.Story.FindAsync(id);
.....
            EditStoryViewModel modelVM = new EditStoryViewModel
{
Child = new Childs(),
Story = story,
ChildrenList = await _db.Childs.Where(c => c.ParentOf.InstitutionId == currentSpecialist.InstitutionId).ToListAsync(),
SentencesList = await _db.Sentence
.Where(s => s.Story.StoryId == story.StoryId)
.Include(s => s.Image)
.ToListAsync()
}; return View(modelVM); }

Post Action

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<IActionResult> Create(CreateStoryViewModel model){}

ViewModel

    public class EditStoryViewModel
    {
        public IEnumerable<Childs> ChildrenList { get; set; }
public Childs Child { get; set; }
public Story Story { get; set; }
public Sentence Sentence { get; set; }
public IEnumerable<Sentence> SentencesList { get; set; } }

cshtml

@model TestApplication.Models.ViewModels.EditStoryViewModel
....................<table id="table-2" class="table order-list datatable"><thead><tr><td class="col-md-4"><h4>
                                                        sentence</h4></td><td class="col-md-2"><h4>
                                                        current image</h4></td><td class="col-md-2"><h4>
                                                         change image</h4></td><td class="col-md-2"><h4>
                                                        change audio</h4></td><td class="col-md-2"><a class="deleteRow"></a><h4>
                                                        delete</h4></td></tr></thead><tbody>
                                            @foreach (var item in Model.SentencesList)
                                            {<tr><td class="col-md-4"><input type="text" class="form-control" name="sent" value="@Html.DisplayFor(s => item.SentenceText)" /></td><td class="text-center col-md-2"><img src="@item.Image.ImageSelected" /></td><td class="col-md-2"><input type="file" class="form-control-file border" name="img"></td><td class="col-md-2"><input type="file" class="form-control-file border" name="aud" disabled></td><td class="col-md-2"><input type="button" class="ibtnDel btn btn-md btn-danger " value="delete"></td></tr>
                                            }</tbody><tfoot><tr><td colspan="5" style="text-align: left;"><input type="button" class="btn btn-primary btn-lg btn-block " id="addrow" value="add row" /></td></tr></tfoot></table>

script

@section Scripts
{<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script><script type="text/javascript">
        var counter = $('tbody tr').length;$(document).ready(function () {$("#addrow").on("click", function () {
                var newRow = $("<tr>");
                var cols = "";
                cols += '<td class="col-md-4"><input type="text" class="form-control" asp-for="Sentence.SentenceText" name="sent" /></td>';
                cols += '<td class="col-md-2"></td>';
                cols += '<td class="col-md-2"><input type="file" class="form-control-file border" name="img"></td>';
                cols += '<td class="col-md-2"><input type="file" class="form-control-file border" name="aud" disabled></td>';
                cols += '<td class="col-md-2"><input type="button" class="ibtnDel btn btn-md btn-danger" value="delete"></td><hr />';

                newRow.append(cols);
                $('tbody').append(newRow);
                counter++;
            });
        });$("table.order-list").on("click", ".ibtnDel", function (event) {
            console.log("Delete");$(this).closest("tr").remove();
            counter -= 1
        });
....................</script>

}

Thank you in advance

System.IO.FileNotFoundException' in System.Private.CoreLib.dll

$
0
0

I have a .NET Core 3.1 Windows(Worker) Service with an assembly reference to a .NET Standard 2.1 Class Library.  (2 separate solutions each with their own project. In a nutshell, I have a windows service project calling another compiled DLL to gain additional functionality (call happens every 60 seconds).

When the Worker Service makes a call to methods in the DLL everything is fine until the DLL tries to create an instance of:

System.Configuration.RegexStringValidator IsValidString = new RegexStringValidator(@"[Some Regular Expression Here]");

As soon as this line is encountered, the debug window of the Worker Service states:

Exception thrown: 'System.IO.FileNotFoundException' in System.Private.CoreLib.dll

All ability to step through and debug both projects stop if the DLL even contains this line of code. Neither putting try/catch blocks around RegexStringValidator statement in the DLL nor calling line of code worker service allow the debugger to continue stepping through the two programs.  The windows service timer keeps running but all breakpoints and debugger no longer work for the current iteration

The latest Microsoft.Configuration libraries have been installed into both project with NuGet.  Some sites says this error is a false positive. That is loaded as part of the default of any project using .NET Core/Standard and is handed even though the output window reports the error.  However, because the debugger wont step out of the DLL and allow the Worker process to report more info on the error, Im at a lost of what do to.

I even installed Microsoft.NETCore.Runtime.CoreCLR hoping it might fix the issue.  It did not

I know what the error should mean, but not sure why OR how to fix it. Im at my wits end

Help is greatly appreciated.

Unsupported Media Type

$
0
0

Hi,

I am using .Net Core 3.1 Web API and jQuery ajax.

I have 2 actions in Web API Controller - 

(1) [HttpPost] public async Task<IActionResult> Post([FromBody] string value)

(2) [HttpPut("{id}")] public async Task<IActionResult> Put(int id, [FromBody] string value)

I have 2 ajax calls in JS file - 

(1) $.ajax({
url: jsClientSettings.getAPI("Home"),
data: { value: "postval" },
method: "POST"
})

(2) $.ajax({
url: jsClientSettings.getAPI("Home") + "/" + 1,
data: { value: "putval" },
method: "PUT"
})

Both ajax calls are throwing same error "415 (Unsupported Media Type)".

If I remove the action param "[FromBody] string value", the ajax call is succeeding.

But I need the value params as well. Could you please guide me?

Web API with Cookie Authentication

$
0
0

Hi,

I am working with.Net Core 3.1 Web Application. I have added both  HttpCookie Authentication and Google OAuth and both are working fine.

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

web application URL is - http://localhost:12345/

Now I have added a new web api project in the same solution and the web api URLs is - http://localhost:23456/ and working fine without any authentications in web api.

I need to use same authentication in both web app and web api. Because already logged in our web application and same users only can able to access the web api as well.

How do I achieve this? How will i pass the tokens from web app to web api?

Viewing all 9386 articles
Browse latest View live


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