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

Localization

$
0
0

Hi!

Im trying to get localization to work in a ASP.NET Core project. (Visual Studio 2017)

In my view /Views/Home/Index.chtml I whant to print out @Localizer["StartPageTitle"] (Now only shows "StartPageTitle")
I also print out current culture, which is correct set. (sv-SE)

In the Resource folder I got an resourcefile "Views.Home.Index.sv-SE.resx", with the "StartPageTitle" translation.

In Startup.cs / ConfigureServices:

services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddMvc(options =>
            {
                options.SslPort = 44300;
                options.Filters.Add(new RequireHttpsAttribute());
            }).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization();

In Startup.cs / Configure

 var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("en"),
                new CultureInfo("sv-SE"),
                new CultureInfo("sv")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("sv-SE"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

Any one have any ideas or suggestions?

/Jonas


Composite Query (Core 1.1)

$
0
0

Hi,

I just started with the Contoso University sample project and found it tremendously great. But as I started on the same track with my personal Database, I realized that having Composite Keys I couldn't return back records because of the two (or more) arguments. I can load the list and create a new record but can't return details, edit or delete pages.

Most probably because of the sections like:

var student = await _context.Students
.Include(s => s.Enrollments)
.ThenInclude(e => e.Course)
.AsNoTracking()
.SingleOrDefaultAsync(m => m.ID == id);

as against mine, where two or more are to be considered as ids.

Any idea how to overcome the problem?

Re-indexing an array

$
0
0

Hi guys,

     I'm working with some data that I'm currently getting back from my models as Dbset.ToList(). The data contains dates, similar to this:

{id: 1, date: 2017-03-01, attribute1: red, attribute2: 10 }, 

{id: 2, date: 2017-03-02, attribute1: green, attribute2: 20 }, 

{id: 3, date: 2017-03-03, attribute1: red, attribute2: 10 }, 

{id: 4, date: 2017-03-03, attribute1: green, attribute2: 5 }

I want to be able to access my 'attribute2' by referring to the date and 'attribute1' ..... so for example accessing x["2017-03-03"]["green"] should give 5.

Is there some nicely packaged, entity framework-esque way of transforming my list in this way? or should I do I just create it manually?

.... Ultimately, I just need to display the data in a table with all dates (including those without data) to be displayed as row headers and 'attribute1' to be displayed as column headers. Any suggestions on how I should approach this?

the "Getting started with ASP.NET Core and Entity Framework Core using Visual Studio" Tutorials required version is VS 2017

$
0
0

the Tutorial "Getting started with ASP.NET Core and Entity Framework Core using Visual Studio" at https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/index is very useful.

but the version is wrote error at the beginning of the tutorial.

is you use the tutorial, please note that the required version is VS 2017, it use ASP.Net Core 1.1 now.

thks.

How to create a Q R Code Generator in Asp.Net Core

$
0
0

Hi,

There have any examples in Q R Code Generator in ASP.NET Core ?

Server Error 401 - Unauthorized: Access is denied due to invalid credentials

$
0
0

This is my first, hopefully not last, web app - so, I expect I'll be posting a few more pleas for help before all is said and done.

I have an app created in VisualStudio 2008 that accesses an SQL database on another server within our network.  The app worked fine when launched locally from VS2008.  Now, I'm trying to get it to actually run on a network server.  I've gotten numerous errors during trying to get this working, and seem to be going around in circles, so I'm posting the latest one with the expectation that there will be more to come.

The error I'm getting at the moment is "Server Error 401 - Unauthorized: Access is denied due to invalid credentials."

The app is on a Windows 2008 R2 server running IIS 7.5.  It is compiled (I used the Publish option in VS2008).  My domain account is a member of the Administrators group on the hosting PC, and the Administrators have full access to the application folder. 

The app has its own AppPool, running under a custom domain account.  This domain account has also been given full access to the app folder.  The app has authentication enabled for ASP.NET Impersonation and Windows Authentication only.

UPDATE:

I couldn't help myself and continued to tinker.  Now I'm getting a login prompt for the server on which the app is hosted, and, when I cancel it, I get "HTTP Error 401. The requested resource requires user authentication."  What I had done was change the order of the providers for Window Authentication so that Negotiate comes before NTLM, which gave me the error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'".  I changed the order back to NTLM followed by Negotiate, and got the HTTP Error 401.

Debug log slow down website

$
0
0

Hello, I have converted a web project from PHP and while the logic is identical the execution in C# is very slow. But I assume that the SQL Outputs by Visual Studio are the issue but I am unable to disable them. How can i disable it or simply bypass temporarily? When I select "Release" nothing changes. I currently build locally to ILS Express.

I am using MVC6. In My Startup I have this:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
	loggerFactory.AddConsole(Configuration.GetSection("Logging"));
	loggerFactory.AddDebug();

I read somewhere that the following should work but Log no longer is available:

context.Database.log = null;

Radio button not binding to value

$
0
0

I am using a radio button among selectable option.  Though when I go to an edit view the value of the selected option is not binding to the radio button.  It is possible that I have the code wrong, but I am working it the same way as the checkboxes that I am also using on the page, and they work correctly.

Here is my model that I am working with:

public class FactionViewModel    {        public FactionViewModel()        {            this.FactionNames = new FactionNamesListViewModel();            this.ReputationTypes = new List<ReputationTypeNamesListViewModel>();            this.ReputationLevels = new List<ReputationLevelNamesListViewModel>();        }        public FactionNamesListViewModel FactionNames { get; set; }        [Required]        [Display(Name = "Reputation Type to be associated with Faction")]        public int ReputationTypesID { get; set; }        public List<ReputationTypeNamesListViewModel> ReputationTypes { get; set; }        [Required]        [Display(Name = "Reputation Levels that apply to the Faction")]        public List<ReputationLevelNamesListViewModel> ReputationLevels { get; set; }    }

public class ReputationTypeNamesListViewModel
    {        public int ReputationTypeID { get; set; }        public string ReputationTypeName { get; set; }        public bool IsSelected { get; set; }    }

Here is my controller:

// GET: Factions/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return BadRequest();
            }
            var eFaction = new FactionViewModel()
            {
                FactionNames = await _db.Database.SqlQuery<FactionNamesListViewModel>(sql: "SELECT Faction_ID AS FactionID, Faction_Name AS FactionName FROM Faction WHERE Faction_ID = @p0", parameters: new object[] { id }).FirstOrDefaultAsync(),
                ReputationTypes = await _db.Database.SqlQuery<ReputationTypeNamesListViewModel>(sql: "SELECT Reputation_Type_ID AS ReputationTypeID, Reputation_Type_Name AS ReputationTypeName, CAST (CASE WHEN  Reputation_Type_ID IN (SELECT ReputationTypeReputation_Type_ID FROM Faction WHERE Faction_ID = @p0) THEN 1 ELSE 0 END AS bit) AS IsSelected FROM ReputationType", parameters: new object[] { id }).ToListAsync(),
                ReputationLevels = await _db.Database.SqlQuery<ReputationLevelNamesListViewModel>(sql: "GetRepLevelList @p0", parameters: new object[] { id }).ToListAsync()
            };
            if (eFaction == null)
            {
                return NotFound();
            }

            return View(eFaction);
        }

Here is the view:

@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_GameDataLayout.cshtml";
}

@model Lotro.WebAppMVC.Models.FactionViewModels.FactionViewModel

<h2>Edit</h2><form asp-controller="Factions" asp-action="Edit" method="post"><div class="form-horizontal"><h4>Class</h4><hr /><div asp-validation-summary="All" class="text-danger"></div><div class="form-group"><label asp-for="@Model.FactionNames.FactionName" class="control-label col-md-2"></label><div class="col-md-10"><input asp-for="@Model.FactionNames.FactionName" class="form-control" /></div></div><div class="form-group"><label asp-for="@Model.ReputationTypesID" class="control-label col-md-12" style="text-align:center"></label><div class="col-md-12">
                @for (var i = 0; i < @Model.ReputationTypes.Count; i++)
                {<div class="col-md-2"><input type="hidden" asp-for="@Model.ReputationTypes[i].ReputationTypeID" /><input type="radio" asp-for="@Model.ReputationTypes[i].IsSelected" value="@Model.ReputationTypes[i].ReputationTypeID"/><b>@Html.DisplayFor(model => model.ReputationTypes[i].ReputationTypeName)</b></div>
                }</div></div><div class="form-group"><label asp-for="@Model.ReputationLevels" class="control-label col-md-12" style="text-align:center"></label><div class="col-md-12">
                @{ int j = 0; }
                @for (var i = 0; i < Model.ReputationLevels.Count; i++)
                {<input type="hidden" asp-for="@Model.ReputationLevels[i].ReputationLevelID" /><div class="col-md-1"><input type="checkbox" asp-for="@Model.ReputationLevels[i].IsChecked" /></div><div class="col-md-2 pull-col-md-1">
                            @Html.DisplayFor(model => model.ReputationLevels[i].ReputationLevelName)</div>
                    j++;
                    if (j == 4)
                    {<div class="col-md-12"><br /></div>
                        j = 0;
                    }
                    else
                    {
                        continue;
                    }
                }</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Create" class="btn btn-default" /></div></div></div><div><a asp-action="Index">Back to List</a></div></form>

This is what the output of the view is on the page:

<div class="form-group"><label class="control-label col-md-12" style="text-align:center" for="ReputationTypesID">Reputation Type to be associated with Faction</label><div class="col-md-12"><div class="col-md-2"><input name="ReputationTypes[0].ReputationTypeID" id="ReputationTypes_0__ReputationTypeID" type="hidden" value="1" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[0].IsSelected" id="ReputationTypes_0__IsSelected" type="radio" value="1" data-val-required="The IsSelected field is required." data-val="true"><b>Crafting</b></div><div class="col-md-2"><input name="ReputationTypes[1].ReputationTypeID" id="ReputationTypes_1__ReputationTypeID" type="hidden" value="2" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[1].IsSelected" id="ReputationTypes_1__IsSelected" type="radio" value="2" data-val-required="The IsSelected field is required." data-val="true"><b>Drinking</b></div><div class="col-md-2"><input name="ReputationTypes[2].ReputationTypeID" id="ReputationTypes_2__ReputationTypeID" type="hidden" value="3" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[2].IsSelected" id="ReputationTypes_2__IsSelected" type="radio" value="3" data-val-required="The IsSelected field is required." data-val="true"><b>Dwarves</b></div><div class="col-md-2"><input name="ReputationTypes[3].ReputationTypeID" id="ReputationTypes_3__ReputationTypeID" type="hidden" value="4" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[3].IsSelected" id="ReputationTypes_3__IsSelected" type="radio" value="4" data-val-required="The IsSelected field is required." data-val="true"><b>Elves</b></div><div class="col-md-2"><input name="ReputationTypes[4].ReputationTypeID" id="ReputationTypes_4__ReputationTypeID" type="hidden" value="5" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[4].IsSelected" id="ReputationTypes_4__IsSelected" type="radio" value="5" data-val-required="The IsSelected field is required." data-val="true"><b>Men</b></div><div class="col-md-2"><input name="ReputationTypes[5].ReputationTypeID" id="ReputationTypes_5__ReputationTypeID" type="hidden" value="6" data-val-required="The ReputationTypeID field is required." data-val="true"><input name="ReputationTypes[5].IsSelected" id="ReputationTypes_5__IsSelected" type="radio" value="6" data-val-required="The IsSelected field is required." data-val="true"><b>Other</b></div></div></div>

Also looking at the output from Visual Studio when debugging I see the following:

[0]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  false
   ReputationTypeID:  1
   ReputationTypeName: "Crafting"
[1]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  true
   ReputationTypeID:  2
   ReputationTypeName: "Drinking"
[2]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  false
   ReputationTypeID:  3
   ReputationTypeName: "Dwarves"
[3]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  false
   ReputationTypeID:  4
   ReputationTypeName: "Elves"
[4]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  false
   ReputationTypeID:  5
   ReputationTypeName: "Men"
[5]    {Lotro.WebAppMVC.Models.ReputationTypesViewModel.ReputationTypeNamesListViewModel}
   IsSelected:  false
   ReputationTypeID:  6
   ReputationTypeName: "Other"

So it is only getting 1 true value.  If I look at the checkboxes on the page they display correctly.  So I am not sure where it is I went wrong, the radio button code and checkbox code should work the same.


Three different browsers yield different results for ASP.NET Core MVC/EF tutorial

$
0
0

Hello,

I'm having a problem with the running of the application from this tutorial: EF-MVC Tutorial

I'm getting different results from three different browsers; IE 11.0 version 11.953.14393.0, Mozilla Firefox version 52.0.2 and Edge version 38.14393.0.0.

I first started getting an error when running the code that I created by following the tutorial and running it in IE 11.0.  If I edit an instructor, leave the Hire date blank and click The Save button, it gives a "An unhandled exception occurred while processing the request" error.  It blows up on line 51 of the Edit.cshtml.  It's supposed to give a field error on the entry screen.

I run it by using the Start Without Debugging(Ctrl+F5) option.

I tried to debug it, but I can't figure out what the problem is and I also asked Tom_Dykstra-MSFT moderator and he suggested that I try to ask for help at Stackoverflow.  I tried Stackoverflow and did not get any answers to resolve this issue.

I also downloaded the tutorial's completed application and tried running it and got the same error.  Tom tried it and it did not blow up for him.  He received the proper field error message.

I tried running it in Firefox and it worked without a problem giving the proper field error message.

I also tried it in Edge and when I go to the Hire date field on the Edit screen, it gives a date selection method that I never saw before and it won't allow me to blank out the date as I do in IE 11 and Firefox.

Does anybody know why I get three different results from the three different browsers that I tried and how to make it so that it works the same way in each browser?  Also, why is it only blowing up in IE 11?

I am running it in Visual Studio 2017 on a Dell laptop 64 bit computer with Windows 10 and all updates applied.

Thanks, Tony

ASP.NET Core on IIS: 502 - Web server received an invalid response while acting as a gateway or proxy server.

$
0
0

Hi guys,

I try to performence test my asp.net core 1.0.1 website. I use loader.io to get 4000 client's to run this site but i get this error on asp.net core. If i run the same code in asp.net 4.6 it runs very well. Can anybody tell my why i cant handle same load on my asp.net core site like my asp.net 4.6?

502 - Web server received an invalid response while acting as a gateway or proxy server.

There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

Screenshots: https://thusan.tinytake.com/sf/MTA4Mzg1NV80MzMzNzMw

ASP.NET 4.6: https://thusan.tinytake.com/sf/MTA4Mzg1OF80MzMzNzMz

ASP.NET core: https://thusan.tinytake.com/sf/MTA4Mzg1OV80MzMzNzM0 

I'm running both sites from IIS on a Windows 2012 r2.

Problem with my controller when using dapper on Asp.Net Core identity.

$
0
0

my user model

    public class User : IdentityUser
    {

    }

my userStore

public class UserStore : IUserStore<User>
{ private readonly string connectionString; public UserStore() { IConfiguration configuration = null; connectionString = configuration.GetValue<string>("DBInfo:ConnectionString"); } public void Dispose() { } public async Task<IdentityResult> CreateAsync(User user, CancellationToken cancellationToken = default(CancellationToken)) { using (SqlConnection conn = new SqlConnection(connectionString)) { if (user == null) throw new ArgumentNullException("user"); using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.ExecuteAsync("INSERT INTO Users(Id,UserName,Nickname,PasswordHash,SecurityStamp,IsConfirmed,ConfirmationToken,CreatedDate) VALUES(@Id,@UserName,@Nickname,@PasswordHash,@SecurityStamp,@IsConfirmed,@ConfirmationToken,@CreatedDate)", user); } return IdentityResult.Success; } } public Task<string> GetUserIdAsync(User user, CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult<string>(user.Id); } public Task<string> GetUserNameAsync(User user, CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult<string>(user.UserName); } public async Task<IdentityResult> UpdateAsync(User user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) throw new ArgumentNullException("user"); using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.ExecuteAsync("UPDATE Users SET UserName = @userName, PasswordHash = @passwordHash, SecurityStamp = @securityStamp WHERE UserId = @userId", user); } return IdentityResult.Success; } public async Task<IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) throw new ArgumentNullException("user"); using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.ExecuteAsync("DELETE FROM Users WHERE UserId = @userId", user); } return IdentityResult.Success; } public async Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(userId)) throw new ArgumentNullException("userId"); Guid parsedUserId; if (!Guid.TryParse(userId, out parsedUserId)) throw new ArgumentOutOfRangeException("userId", string.Format("'{0}' is not a valid GUID.", new { userId })); using (SqlConnection connection = new SqlConnection(connectionString)) { var user = await connection.QueryAsync<User>("SELECT * FROM Users WHERE Id = @Id", new {userId = parsedUserId}); return user.SingleOrDefault(); //connection.Query<User>("select * from Users where UserId = @userId", new { userId = parsedUserId }).SingleOrDefault(); } } public async Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(normalizedUserName)) throw new ArgumentNullException("userName"); using (SqlConnection connection = new SqlConnection(connectionString)) { var user = await connection.QueryAsync<User>("SELECT * FROM Users WHERE lower(UserName) = lower(@userName)", new {normalizedUserName}); return user.FirstOrDefault(); } }
}


And the problem is here. In my controller, when trying to use UserManager it says has 9 parameters...but is this an core.identity model, because in asp.identity it doesn't need all arguments.

        public LoginController()
            : this(new UserManager<User>(new UserStore()))
        {
        }

        public LoginController(UserManager<User> userManager)
        {
            this.userManager = userManager;
        }

        public UserManager<User> UserManager { get; private set; }

thanx 

How to Change web.config ConnectionString dynamically

$
0
0

Hi, 

I want to be able to change my web site web.config dynamically so that any time i made changes to the application i don't need to download the web config and re-upload, i have tried the following

// ===========================================
        // The content of pathname is shown below
        //  string pathname = "~/web.config";
        //============================================

        System.Configuration.Configuration Config1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(pathname);
        ConnectionStringsSection conSetting = (ConnectionStringsSection)Config1.GetSection("connectionString");
        ConnectionStringSettings StringSettings = new ConnectionStringSettings("NIQSDB", "Data Source=" + ServerName + ";Database=" + DBaseName + ";User ID=" + UserID + ";Password=" + PSSWD + ";");
        conSetting.ConnectionStrings.Remove(StringSettings);
        conSetting.ConnectionStrings.Add(StringSettings);
        Config1.Save(ConfigurationSaveMode.Modified);  

and i get the following error :

Object reference not set to an instance of an object.

 at 

conSetting.ConnectionStrings.Remove(StringSettings);
please what am i doing wrongly.
thank you

I need help Cash book in asp.net

$
0
0

Hi

I am quit new to this forum and I want to create a cash book in asp.net which is performing calculation of money in, money out and balance.

Please help me if have an idea about how to create this.

thank you

regard,

Abdirizak

In javascript how to intercept events selection, collapsing and expanding of the tag and

$
0
0

Hello everyone, I'm developing in asp.net mvc and core'm creating a hierarchical structure with the html tag <ul> and <li>. How can I intercept the selection of a node?

Where do I get a free document viewer for Word, Excel and PDF

$
0
0

Hello everyone, I have to give a chance to a user to have a preview and to download then a word document, excel or pdf on a page of a site developed into a core application asp.net mvc. Do You know tell me a free document viewer that makes the preview, zoom and downloading files mentioned in the subject?


Any way to add mailbox info for email in .net core?

$
0
0

I am learning asp.net core and following this doc - https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm

I see the doc explains how to user email confirmation option using SendGrid account. 

But what if someone do not want to user Sendgrid?

How SMTP settings used to be in webconfig in asp.net mvc websites, there is no way to do that in asp.net core?

How can I user a normal mailbox for emails purpose? so that all email functions use that mailbox credentials?

Plz help?

angular template question

There is no way to add roles in .net core?

showing all error messages

$
0
0

Hi ,

I'm developing an application(during a training course) and I have provided appropriate error message for each field in a form.Fields are required and have character limits.

however if we leave fields empty ,we will face as follows:

http://uupload.ir/files/qv6b_asp_error_message.png

But it also has length constraint for example :

http://uupload.ir/files/nj_asp_error_message_2.png

and after that if the user says  "It  could be told at that stage too" he or she is absolutely right.
How to make the app render all error messages?

Can i create plugins for .NET CORE website?

$
0
0

i am learning .NET CORE first time from this doc - https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/

this doc is great but i want to know is it possible to create plugins in .net core site?

if we take example of default .net core site from this documentation, instead of adding search, new field ets in the main site, how can i do the same by adding a new plugin? how to create plugin architect?

can anyone help with code by using .net core default site as base? i am new to all this and still learning

Viewing all 9386 articles
Browse latest View live


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