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

Webpack Dev Middleware - Different behavior on .Net Core 2.1 and 2.2?

$
0
0

I recently started using the Webpack Dev Middleware on a Vue + .Net Core 2.1 project and it was working correctly.

Then I decided to create a sample project with the bare minimum dependencies on .Net Core 2.2 but I coudln't get it to work, modifying a Vue File wouldn't trigger changes on the web page. As it turns out it seems that the exact same setup works correctly on .Net Core 2.1 !

I created a repo with 2 projects, exact same setup for each but diferent .Net Core versions

https://github.com/vlaem/HR-Behavior

Is there any specific reason as of why this would be the case? Since the problem happens only with 2.2 Im guessing the problem might be somewhere on the midleware plugin?


DB Schemas not being detected

$
0
0

I have 2 applications named ManagementStudio and DocumentStudio. DocumentStudio references ManagementStudio via its compiled dlls. However, when I login via DocumentStudio, I get an error asking for IdentityUserClaim. I then proceeded to create a IdentityUserClaim table that looked like this ManagementStudio.IdentityUserClaim.

However, that didn't work as well as DocumentStudio does not recognise ManagementStudios schema for some reason.

I also added an annotation above all my classes and in the OnModelBuilding specifying its schema. I still get the same error.

The only time it works is if I remove ManagementStudios schema entirely. I'm not sure why this is happening but it seems to be the only workaround for now?

The main place where this error is happening here at the sign in process:

var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);

For some reason the Claims section keeps asking for a schema-less table. This isn't an issue with ManagementStudio that uses the same method to login but for DocumentStudio which is another application, I get errors.

Is it possible to use a db schema for Identity items and let other applications reference you?

I noticed also that I have duplicate tables for similar items named IdentityUserRole and IdentityUserClaim. I have tried to merge them in this question but that just gave me more issues:

This is how I did it:

I overrode the IdentityUserRole class

[Table("IdentityUserRole",Schema="ManagementStudio")]publicclassUserRoles:IdentityUserRole<string>{[Key]publicstringId{ get;set;}[ForeignKey("Users")]publicoverridestringUserId{ get;set;}publicvirtualApplicationUsersUsers{ get;set;}[ForeignKey("Roles")]publicoverridestringRoleId{ get;set;}publicvirtualRolesRoles{ get;set;}}

In my DbContext class:

publicDbSet<UserRoles>UserRoles{ get;set;}

In my onModelBuilding

modelBuilder.Entity<UserRoles>().ToTable("IdentityUserRole", schema:"ManagementStudio");

This is the error I get when I try to login:

An unhandled exception occurred while processing the request. InvalidOperationException: Cannot create a DbSet for 'IdentityUserRole' because this type is not included in the model for the context. Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType()

This happens for IdentityUserClaim as well.

Adding references to of system under test to MSunit test project in asp.net core

$
0
0

How project reference should be added in asp.net core testproject for project system under test.<br>
Should it be a .dll or it should be project file?
We are using asp.net core 2.2, for main project as well as it's Unit test project with MSTest.

Asp.Net Core 2.2 ValidateAntiForgeryToken produces a 400 exception on an Ajax call

$
0
0

Hello Everyone,

In my Asp.Net Core 2.2 I have an Ajax call where I would like via Ajax to invoke ValidateAntiForgeryToken but it produces a 400 exception. Without the ValidateAntiForgeryToken the code works fine. I would appreciate any help greatly.

Thanks, kindest blessings, Andreas

View:

<divid="root"></div>

<scripttype="text/javascript">

$(function () {

$(document).ready(function () {

$.ajax({

type:"post",

contentType:"application/json",

dataType:"json",

url:"https://www.xxx.com/api/GetTagItem",

beforeSend:function (request) { request.setRequestHeader("RequestVerificationToken",$("[name='__RequestVerificationToken']").val());},

data: JSON.stringify({"Key":"News" }),

success:function (data) {

$("#root").html(data.Value);

}

});

});

});

</script>

C#:

[HttpPost]

[Route("~/api/GetTagItem")]

[ValidateAntiForgeryToken]

publicasync Task<JObject> GetTagItem([FromBody]KeyValueViewModel input)

{

……...

}

Model First approach in entityframework core

$
0
0

Hi,

Can any one please guide me that is there Model First approach in entityframwork core. 

Please try to help with some reference of authentic materials.

Thanks

ASP.net Core Web Application Hosting on window 10 Pro

$
0
0

Firstly I am new to Web App but I am ok with C#/VB.Net.  I have VS2017 community installed in my window 10 Pro laptop, iiS running at the background.

1) wrote a very simple ASP.net Core Web App, A button and A input box(Textbox),. Then  publish it to a specific folder. 

 2) setup the a website and application pool at iis (laptop with VS and Window10 Pro) pointing to that folder.

3) No problem opening from Chrome/Edge  either by IP/Port No or by Web site name (using the same laptop and not running from VS)

4) With another laptop using WIFI or cable, I am unable to access the Web App. By using Cable/Wifi."The site can't be reached, it take too long to respond"

Is there any more step i need to do?

My aim is to make an WebApp that can only be access by Local Area Network only (off line WebServer).

Thnaks

Correct way to initialize settings in .net core 2.2?

$
0
0

I created an REST api application which has many settings and stored in database. These settings are used during filtering and inserting data to the table.

Because I need to access settings every time I need to insert data. Instead of accessing settings from database, I created a global settings class and I put every settings in that class.

publicstaticclassGlobalSettings{publicstaticstringSetting_1;publicstaticstringSetting_2;publicstaticstringSetting_3;publicstaticstringSetting_4;publicstaticvoidInitialize(ISettingsRepo repo){try{var settings =newGSettings(repo);Setting_1= settings.SetSetting_1();Setting_2= settings.SetSetting_2();Setting_3= settings.SetSetting_3();Setting_4= settings.SetSetting_4();}catch(Exception ex){thrownewException("Error when loading settings.\r\n"+ ex.Message);}}}

Here  ISettingsRepo is scoped service that will load the settings from database. The functions will initialize the settings to the properties. The functions will initialize the settings to the properties.

Now to initialize GlobalSettings I used configure method in startup class like this.

using(var scope = app.ApplicationServices.CreateScope()){Settings.GlobalSettings.Initialize(scope.ServiceProvider.GetRequiredService<Data_Repo.Settings.ISettingsRepo>());}

Now I can use this in controller or anywhere in my api and get settings without accessing database. 

Also I tried to use CustomConfigurationProvider. While it is good, I am unable to update the settings without restarting the server. So I didn't use CustomConfigurationProvider.

With the above method I can reload the settings from database any time I want from admin controller. But does this method correct way or has memory leak problems?

Is there any better method to do this.?

maintain user login Session for mutiple dimain from single project

$
0
0

Hi Expert

I have a project where mutiple domain are ruuning for single project means all domain have same A record mapped and we have hosted project  on IIS.and its working fine but I want to use same session if use switch from www.abc.com towww.xyz.com ( we have 1000  diffrent domains) he dont need to login again as its part of same project.

 please suggest me best way. please dont  suggest  post message. WE are using  ASP.net core MVC.


How to make login page home page

$
0
0

I have a login page in the Views/Account directory and I want to make that the home page instead of the Index.cshtml in the Views/Home directory. How do I do that?

@Html.ActionLink with an id for the link not working

$
0
0

When I click on the edit link, I get a page not found error. I can see the url when I hover over the edit link as /editprofile/Edit/0E... but should it be /editprofile/Edit/id=0E... and that is why I get page not found. Here is my code with the Html Action link for edit.

@model IEnumerable<FE.Models.EditProfile>

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h2>Index</h2><p><a asp-action="Create">Profiles</a></p><table class="table"><thead><tr><th></th><th>
                @Html.DisplayNameFor(model => model.UserName)</th><th>
                @Html.DisplayNameFor(model => model.Email)</th><th>
                @Html.DisplayNameFor(model => model.PhoneNumber)</th></tr></thead><tbody>
@foreach (var item in Model) {<tr><td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { id = "@Id" }) |</td><td>
                @Html.DisplayFor(modelItem => item.UserName)</td><td>
                @Html.DisplayFor(modelItem => item.Email)</td><td>
                @Html.DisplayFor(modelItem => item.PhoneNumber)</td></tr>}</tbody></table>

What is the AddScoped truely use for?

$
0
0

I am learning to connect the database by EntityFramework.

Soon I found that I should define an interface A, and then code a concrete type B which implements the interface.

Finally, add the Scoped like this:

services.AddScoped<A, B>();

I feel troublesome to define an interface and implements it. 

Why not coding a brand new class and just use it only?

I am sorry that I am a beginner by asking so stupid question. Meanwhile, would you please tell me? Thank you.

Asp.Net Core 3.0 ¿What is supposed to be with UseStartup?

$
0
0

Hello, 


I would like to ask.

How do I add the UseStartup extension method if I decide to start the host as an instance of new WebHostBuilder () instead of the static class WebHost?

What purpose is supposed of each one?

Something special to know about UseStartup future?

Is there that "we" are trying to avoid static behaviours?

What about extension methods?

So many questions?

 
Thanks beforehand.

Sam.

onSelect Datepicker event change the returned value when submit

$
0
0

Hi

I'm using core 2.1.

I have these three dates properties in a model:

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Required]
    public DateTime HkmDate { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Required]
    public DateTime SDate { get; set; }
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Required]
    public DateTime EDate { get; set; }

I'm using this 2 JS files to get single datepicker and another start and end dates in shared _Layout page:

datepicker:

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {
		define([ "../jquery.ui.datepicker" ], factory );
	} else {

		// Browser globals
		factory( jQuery.datepicker );
	}
}(function( datepicker ) {
	datepicker.regional['ar'] = {
		dateFormat: 'yy/mm/dd',
  		isRTL: true,
		showMonthAfterYear: false,
		yearSuffix: ''};
	datepicker.setDefaults(datepicker.regional['ar']);

	return datepicker.regional['ar'];

}));$("#datepicker").datepicker({
    isRTL: true,
    changeMonth: true,
    changeYear: true
});

sedatepicker:

$(function () {$("#txtFrom").datepicker({
        numberOfMonths: 2,
        dateFormat: 'yy/mm/dd',
        changeMonth: true,
        changeYear: true,
        onSelect: function (selected) {
            var dt = new Date(selected);
            dt.setDate(dt.getDate() + 1);$("#txtTo").datepicker("option", "minDate", dt);
        }
    });$("#txtTo").datepicker({
        numberOfMonths: 2,
        dateFormat: 'yy/mm/dd',
        changeMonth: true,
        changeYear: true,
        onSelect: function (selected) {
            var dt = new Date(selected);
            dt.setDate(dt.getDate() - 1);$("#txtFrom").datepicker("option", "maxDate", dt);
        }
    });
});

So I'm using these tow datepickers in one view to enter a single date and a start and end dates (3 text items)

I have this code to return the previous day of some day returned by the sedatepicker:

$("#txtFrom").datepicker({
                onSelect: function () {$(this).change();
                }
                }).on("change", function() {
                    var sd = document.getElementsByName("sd")[0].value;
                    var sd_d = new Date(sd);
                    //var ed = date.setDate(sd_d - 1);
                    var ed = new Date(sd_d - 1);
                    var edString = ed.getFullYear() + '/' + (ed.getMonth() + 1) + '/' + ed.getDate();$("#ed").val(edString);
                });
<div class="col-md-3"><div class="form-group"><label asp-for="SDate" class="control-label"></label>
                @*<input asp-for="SDate" class="form-control" id="txtFrom" oninput="handler(event);" name="sd" />*@<input asp-for="SDate" class="form-control" id="txtFrom" name="sd" readonly/><span asp-validation-for="SDate" class="text-danger"></span></div></div><div class="col-md-3"><div class="form-group"><label asp-for="EDate" class="control-label"></label><input asp-for="EDate" class="form-control"  id="ed" /><span asp-validation-for="EDate" class="text-danger"></span></div></div>
       ...... Some code<input type="submit" value="Save" class="btn btn-primary" />

Now when I select some date from txtFrom datepicker the values are returned correctly for it and the previous day for the other text item EDate, But when I submit the form the value of Sdate is changed itself to 0001-01-01! Why? and How solve please?

Send email on Azure

$
0
0

Hi,

   I am trying to run code that has worked when hosted with other hosting providers.

I am using a newly created outlook account to send the email, is there something I have to  do in outlook (SMTP)?

I can't get it to run Azure. Is there something I have to select or install on to Azure?

Thanks,

How can I set a task in asp.net core?

$
0
0

I wanna achieve this: whenever someone login his account failed for 3 times(for example input wrong password). The system will stop him from login in for 30 minutes.

In my opinion, it should work by back-end but not the database.

I think the asp.net core should record his IP&Time in a list and check if time is over every minute.

Meanwhile, how can I set a task in asp.net core? Besides, I want to know if my idea is right? Thank you.


How to Upload Image/File in Asp.net Core 2.0

$
0
0

I try so many time but it didnt work. 
please check my code

<form enctype="multipart/form-data" asp-action="Create"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Title" class="control-label"></label><input asp-for="Title" class="form-control" /><span asp-validation-for="Title" class="text-danger"></span></div><div class="form-group"><label asp-for="Subtitle" class="control-label"></label><input asp-for="Subtitle" class="form-control" /><span asp-validation-for="Subtitle" class="text-danger"></span></div><div class="form-group"><label asp-for="Body" class="control-label"></label><textarea asp-for="Body" class="form-control"></textarea><span asp-validation-for="Body" class="text-danger"></span></div><div class="form-group"><div class="custom-file"><input asp-for="Image1" name="Image1" id="Image1" class="form-control custom-file-input" /><label class="custom-file-label">Choose File</label></div></div><div class="form-group"><label asp-for="Image2" class="control-label"></label><input asp-for="Image2" type="file" class="form-control" /><span asp-validation-for="Image2" class="text-danger"></span></div><div class="form-group"><label asp-for="CreatedOn" class="control-label"></label><input asp-for="CreatedOn" class="form-control" /><span asp-validation-for="CreatedOn" class="text-danger"></span></div><div class="form-group"><label asp-for="Eta" class="control-label"></label><input asp-for="Eta" class="form-control" /><span asp-validation-for="Eta" class="text-danger"></span></div><div class="form-group"><input type="submit" value="Create" class="btn btn-success" /> <a asp-action="Index" class="btn btn-link">Back to List</a></div></form>
//controller
 private readonly InnovusTechCoreContext _context;
        private readonly IHostingEnvironment _hosting;

        public BlogsController(InnovusTechCoreContext context, IHostingEnvironment hosting)
        {
            _context = context;
            _hosting = hosting;

        }

public IActionResult Upload()
        {
            return View();
        }
        [HttpPost]
        public  IActionResult Upload(BlogViewModel model)
        {



            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Image1 != null)
                {
                    string uploadfolder = Path.Combine(_hosting.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Image1.FileName;
                    string filePath = Path.Combine(uploadfolder, uniqueFileName);
                    model.Image1.CopyTo(new FileStream(filePath, FileMode.Create));


                    Blog b = new Blog
                    {
                        Title = model.Title,
                        Subtitle = model.Subtitle,
                        Body = model.Body,
                        Image1 = uniqueFileName.ToString(),
                        Image2 = uniqueFileName,
                        CreatedOn = model.CreatedOn,
                        Eta = model.Eta
                    };

                   _context.Blogs.Add(b);
                   _context.SaveChanges();

                }
            }
            return View();
        }
//model

namespace InnovusTechCore.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Blog")]
    public partial class Blog
    {
        public int Id { get; set; }

        [StringLength(140)]
        [Required]
        public string Title { get; set; }

        [Required]
        [StringLength(140)]
        public string Subtitle { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        public string Body { get; set; }

        [StringLength(100)]
        public string Image1 { get; set; }

        [StringLength(100)]
        public string Image2 { get; set; }

        public DateTime? CreatedOn { get; set; }

        [StringLength(20)]
        public string Eta { get; set; }
    }
}
//ViewModel
   public class BlogViewModel
    {
        [StringLength(140)]
        [Required]
        public string Title { get; set; }

        [Required]
        [StringLength(140)]
        public string Subtitle { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        public string Body { get; set; }

        
        public IFormFile Image1 { get; set; }

        
        public IFormFile Image2 { get; set; }

        public DateTime? CreatedOn { get; set; }

        [StringLength(20)]
        public string Eta { get; set; }
    }

I tried this but it does not work. the image is not upload and save into images folder inside wwwroot. and it does not save the name of file in database. 
I still dont the exact problem.

follow up question to roles in the _layout menu file

$
0
0

I asked this question 

https://forums.asp.net/t/2157053.aspx?Proper+way+to+have+different+menus+based+on+roles

but doing as the answer suggests seems to be less obvious than it at first appeared.

If I am writing code in the _Layout file, how do I access the database?

Also, I found this link, 

https://social.technet.microsoft.com/wiki/contents/articles/51391.asp-net-core-2-0-user-role-base-dynamic-menu-using-dependency-injection.aspx

and the last coding example at the bottom of the page shows them using @If(User.IsInRole("Admin") and that is the part that is not working correctly for me, so I cannot use this example.

I have pasted the example code from the link.  For my _Layout file, , the "@If(User.IsInRole("Admin") does not appear to work consistently for my page, which is shown (and presumably works as expected) in this example.

<div class="navbar-collapse collapse"><ul class="nav navbar-nav"><li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
 @if (User.Identity.IsAuthenticated)
        {
            var UserRoles = "";
            if (@User.IsInRole("Admin"))
            {
                UserRoles = "Admin";
            }
            else
            {
                UserRoles = "Manager";
            }
                @if (menus.GetMenuMaster(@UserRoles).Any())
                {
                @if (menus.GetMenuMaster(@UserRoles).Any())
                {
                @foreach (var menuNames in menus.GetMenuMaster(@UserRoles).Where(n => n.Parent_MenuID == "*"))
                {<li><a asp-area="" asp-controller=@menuNames.MenuURL asp-action=@menuNames.MenuFileName>@menuNames.MenuName</a><ul class="sub-menu">
                                @foreach (var subMenu in menus.GetMenuMaster(@UserRoles).Where(n => n.Parent_MenuID == @menuNames.MenuID))
                                  {<li><a asp-area="" asp-controller=@subMenu.MenuURL asp-action=@subMenu.MenuFileName>@subMenu.MenuName</a></li>
                                   }</ul></li>
                }
                }
                }
            }</ul>

thanks

@Html.ActionLink assistance

$
0
0

I create a controller to Delete a user and when I add the View from the controller it creates a Delete subfolder in Views folder with the Delete.cshtml view inside that subfolder. The problem is I have a view that has Edit, Delete, and Details link on that view that displays all of the users. That is in the Views >Edit folder. When I click on the Delete link or  hover over it on this view it shows ../Edit/{id for that user} and comes up with 'Page can't be displayed' because I don't have a delete view in the Edit folder. How do I get the Delete link to show the path for Delete folder view? Here is the code for the links on the edit view.

<td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id },  new { id = @"Id" }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })                 </td>

JSON Deserialization from premade .JSON File

$
0
0

I hope I'm posting this in the correct space and if not if someone can move it if they have that ability or just post back with where this belongs I'm happy to post in the correct area!

I have a project I'm working on that I need to pull a member from a JSON file. The file is premade but later will have a random member's values pulled.

My file looks something like this:

{"Member 0": {"Date": "Date","Name": "First and Last Name","Image": "Path to Image","Content": "Content"
  },"Member 1": {"Date": "Date","Name": "First and Last Name","Image": "Path to Image","Content": "Content"
  },"Member 2": {"Date": "Date","Name": "First and Last Name","Image": "Path to Image","Content": "Content"
  }
}

Basically this will have unique data in it once I have it working, it will expand more the the 3 members that are in there it's just like that for testing.

What I want to do exactly with this file is pull a random member and use the Date, Name, Image, and Content string data to insert into my webpage.

I am trying to use version 11 of the built in JSON.NET Framework in ASP.NET Core 2.2 also am using Razor pages.

Error CS0246 The type or namespace name 'XModels' could not be found - VS 2019 Community preview with asp.net 3.0

$
0
0

hi guys

I am playing around VS2019 community Preview version and was creating my models. Instead of putting my models in the default model folder, I put them in a folder called X_Models and getting this error. I then removed the Underscore and still get the same error, I have closed and restarted VS and it wont build.

I have now excluded the folder and copied the classes and datacontext file into the original models folder and it works

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'XModels' could not be found (are you missing a using directive or an assembly reference?) 1 Active

Viewing all 9386 articles
Browse latest View live


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