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

Authenticating SPA+API with Authentication Server

$
0
0

I have been reading about OAuth and JWT in general. One question that has been troubling me is around authentication of SPA that use APIs to provide data.

As per my understanding -

  1. SPA shows user a login page. 
  2. User grants credentials and hits login button
  3. API takes the credentials verifies it against it's database.
  4. API generates a JWT token and adds a signature using a secret string value that only API knows.
  5. JWT is sent back to SPA and SPA stores it in cookies or just creates a global variable.
  6. SPA sends this JWT to API with each HTTP request. 
  7. API doesn't have to validate it against DB, it just has to verify if it is a valid JWT and is still active. It can do so because it has the secret key with which the Token was signed.

Is my understanding correct? If so then what happens if there is a separate Authentication server?

  1. The SPA will redirect the user to Authentication Server's login page.
  2. User grants credentials and then Authentication server validates it and generates an Authentication Code and sends it back to SPA on the callback URL.
  3. This Authentication Code is sent to API and the API sends it to the Authentication server along with clientId and a clientSecret. 
  4. The Authentication server will generate an access token and send it to API and the API will sent it to SPA
  5. The SPA will carry this token in each request. 

The API is able to verify that it is a valid token since it has the ClientId and Client Secret that was used to generate token by the authentication server?? 

Is that how it works? Is my understanding correct?


Windows authentication propmts for credential

$
0
0

HI,

We have configured the application to use windows authentication and it's published to IIS. The following configurtaion has been completed but still browser propmts for user credential. Please share your suggestions

  • IIS Authentication: disabled all authentication except Windows
  • Internet options - security - local intranet
    • Added site in Intraner sites
    • Custom level - logon - selected Automatic logon only in intranet zone
  • Internet options - advanced - selected Enable integrated windows authentication*

"InvalidOperationException" error showing values from model in ASP.NET Core MVC and Entity Framework Core?

$
0
0
I am trying to show values in table from controller to view using model but it shows an error. I have debugged and checked values are returned OK, but the code shows an error. I don't know where is problem please let me know how can I resolve/fix this issue?

Here is my code:
Model:

public class RoomsStatus
{
[Key]

public int Id { get; set; }
public DateTime CheckInDateTime { get; set; }
public DateTime CheckOutDateTime { get; set; }
public decimal DailyPricePerBed { get; set; }
public int AmountOfBeds { get; set; }
public string PriceType { get; set; }
public bool Paid { get; set; }
public string Name { get; set; }

public int RoomNumber { get; set; }
}
ApplicationDbConext:

public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

public DbSet<RoomsStatus> RSN { get; set; }
}
RoomsController:

//view booking details and rooms status
public async Task<IActionResult> RoomsStatus(int PartnerID,int BuldingID)
{
try
{
return this.View("RoomsStatus", await _context.RSN.FromSqlRaw("EXECUTE dbo.GetRoomsStatusByID {0},{1}", PartnerID, BuldingID).ToListAsync());
}
catch (Exception e)
{
//Logger.LogError(e, "Error while displaying booking.");
return this.RedirectToAction("Error", "Base");
}
}
RoomStatus view:

@model IEnumerable<FewoVerwaltung.Models.RoomsStatus>

<h1>RoomsStatus</h1>

<table class="table">
<thead>
<tr>
<th>
Name
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>

@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</tbody>
</table>
And this is the error I get:
Stack InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus]', but this ViewDataDictionary instance requires a model item of type 'FewoVerwaltung.Models.Base.BaseModel'

Clear user INPUT after submit (OnPost) Task

$
0
0

I have  a razor page for a contact page, once I have submitted a request the email is sent however on success I want the user input to be cleared to prevent them from sending the information several times.

Web page

@page
@model ContactModel
@{
    ViewData["Title"] = "Contact";

}
<h2>@Model.Message</h2><div class="container"><div class=" = row"><div class="col-sm-6"><address>
                One Microsoft Way<br />
                Redmond, WA 98052-6399<br /><abbr title="Phone">P:</abbr>
                425.555.0100</address><address><strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /><strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a></address></div><div class="col-sm-6"><form method="post"><table class="tblcontact"><tr><td><div asp-validation-summary="All" class="text-danger"></div></td></tr><tr><td><input asp-for="ContactEmail.FirstName" id="FirstName" type="text" placeholder="First Name" /><span asp-validation-for="ContactEmail.FirstName" class="text-danger"></span></td></tr><tr><td><input asp-for="ContactEmail.LastName" id="LastName" type="text" placeholder="Last Name" /><span asp-validation-for="ContactEmail.LastName" class="text-danger"></span></td></tr><tr><td><input asp-for="ContactEmail.Email" id="Email" type="text" placeholder="Email" /><span asp-validation-for="ContactEmail.Email" class="text-danger"></span></td></tr><tr><td><select asp-for="ContactEmail.Service" asp-items="Html.GetEnumSelectList<DigitalAcademyCorp.Models.DACServices>()"><option>Select</option></select><span asp-validation-for="ContactEmail.Service" class="text-danger"></span></td></tr><tr><td><textarea asp-for="ContactEmail.Comment" class="ctext" cols="42" row="100" placeholder="Message" required></textarea><span asp-validation-for="ContactEmail.Comment" class="text-danger"></span></td></tr><tr><td><input class="btn contact-submit" id="Submit" type="submit" value="Submit" /></td></tr></table></form></div></div></div>
@section Scripts{ <partial name="_ValidationScriptsPartial" />

Page Controller/Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DigitalAcademyCorp.Models;
using DigitalAcademyCorp.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace DigitalAcademyCorp.Pages
{
    public class ContactModel : PageModel
    {
        private readonly IEmailService _mailSender;

        public ContactModel(IEmailService mailSender)
        {
            _mailSender = mailSender;
        }

        public string Message { get; set; }
        [BindProperty]
        public ContactEmail ContactEmail { get; set; }
        [BindProperty]
        public Message EmailMessage { get; set; }

         public void OnGet()
        {
            Message = "We are keen to hear what you have to say.";
        }

        public async Task OnPost()
        {
            if(ModelState.IsValid)
            {
                EmailMessage.From = ContactEmail.Email;
                EmailMessage.Body = ContactBody(ContactEmail.FirstName, ContactEmail.LastName, ContactEmail.Service.ToString(), ContactEmail.Comment);
                EmailMessage.Subject = ContactEmail.Service.ToString();
                try
                {
                    await _mailSender.Send(EmailMessage); //EMAIL LOW APPS ACCESS GOOGLE
                    

                } catch (Exception)
               {
                   Message = "Oops there seems to be an error sending your message";
               }                
            }
            else
            {
                Message = "Oops you inputs are not valid for the page";
            }
        }
        private string ContactBody(string FName,string LName,string DACService,string Comment)
        {
            string htmlbody = "<table><tr><div>Hi " + FName + " " + LName + "</div> </tr> <tr><div><br><p>Thank you for contacting Example <strong>E</strong>. We are pleased that you are interested in our <strong>" + DACService + "</strong> offering. <br><br> We will be responding to your message below shortly <br><br><em>" + Comment + "</em><br></p> </div> </tr> <tr> <div><br> <p>Thank you <br> <br> <strong>Example</strong> </p> </div> </tr></table>";

            return htmlbody;
        }
    }
}

Please help

Thank you,

Loading different version of strongly typed assembly side by side.

$
0
0

Hello,

I have a dot net core console application which acts as base framework provides some services to client plugin developers. For simplicity lets assume base program exposes a interface called IPlugin, client developer implement this IPlugin. Base framework console application loads different client assemblies using reflection. The client and base framework exposes a rest endpoint with swagger. Rest service developed in ASP .net core Web API project.  

Current Startup.cs

public void ConfigureServices(IServiceCollection services)

{

 services.AddMvc( ).AddControllerAsServices();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

  app.UseOpenApi();

  app.UseSwaggerUi3();

app.UseMvc();

}

In Base application Asp .net core Web API is hosted using following code,

public IWebHostBuilder CreateWebHostBuilder(string[] args) =>  WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((context,config) => 

{

}).ConfigureServices( s => s.AddSingletion(service1)).

.ConfigureServices( s => s.AddSingletion(service2)).

.UseStartup<Startup>( );

So far good. 

Say IPlugin hosts rest service in port P1, 

Now client would like to run different version of IPlugin implementation side by side. New assembly in port P2. 

When we load another version of same IPlugin ( strongly typed) and host rest end point in another port P2. We see both the endpoints ( P1, P2) has duplicated methods from assembly 1 and assembly 2. 

Could anyone please help how to fix this problem?.

Thanks,

Navigation Properties don't Httppost from View to Controller

$
0
0

I have a class whose properties (including a Navigation Property to another table) show up fine in the View.  When I'm editing the properties and hit submit, all the properties get posted to the controller except the Navigation Class.  I tried creating a hidden asp-for"" input tag helper to pass along the Navigation Object, but it doesn't make it to the controller.

View Model Class (there are more fields, but I cut out a bunch of extraneous ones)

    [Table("bagsmvc")]
    public partial class Bagsmvc
    {
        [Key]
        [Column("id", TypeName = "int(11)")]
        public int Id { get; set; }
        [Column(TypeName = "varchar(255)")]
        [Required]
        public string Airline { get; set; } = "No Airline";

        public int? PersonID { get; set; } // Only 1 person obtained from
        public Peoplemvc Person { get; set; } // This is the person bag was obtained from 
    }

And some code from the Edit View

<form asp-controller="Bags" asp-action="Edit" method="post"><input type="hidden" asp-for="@Model.Id" /><label asp-for="@Model.Airline"></label><input asp-for="@Model.Airline" /><label asp-for="@Model.PersonID"></label><input asp-for="@Model.PersonID"><input type="hidden" asp-for="@Model.Person" />

PersonID has a foreign key on another table so I can always get the Person object using .FirstOrDefault() so it's no big deal.  Butwhy doesn't the Person object get posted to the Edit Controller as some kind of payload?

PS:  I realize that changing PersonID will change the person object.  I'll deal with that separately.

How to turn off bundling when debugging

$
0
0

How do I turn off debugging when I am developing?

I have it generating the vendor.css and vendor.js files.

On the javascript side, I do not want it to push to vendor when I'm in VS etc.

I would like the vendor.css to continue to build though and update so when I hit Ctrl F5 it works!

I can't seem to find any help on the web.

.core third part dll, app.config

$
0
0

Hi,

I am trying to convert a project into .net core. It uses a 3rd part dll which I cannot change. 

This 3rd part dll reads from the app.config file. 

I added an app.config to my .dt net core project so that the values the 3rd party dll can be read. This worked fine but the WCF config is causing me issues. I keep getting unrecgnised section error for the WCF config.

Is there a nuget package I can add to resolve this? Or is there another way I can work around this issue?

Thank you..


Accessing ApplicationUser Property in the Login.cshtml.cs page

$
0
0

I'm developing web application using ASP.Net MVC Core. I used "Individual user authentication" so the identity table, Register and Login pages is generated by default.

I extended the identity table with enum column called "AccountStatus" that has Four values as following:

publicclassApplicationUser:IdentityUser{publicintStatusId{get;set;}publicstringStatusName{get;set;}publicAccountStatusIdAccountStatusId{get;set;}publicAccountStatusAccountStatus{get;set;}}publicenumAccountStatusId:int{Active=0,InActive=1,Expired=2,Pending=3}publicclassAccountStatus{publicAccountStatusIdAccountStatusId{get;set;}publicstringStatus{get;set;}publicList<ApplicationUser>Statuses{get;set;}}

I did the migration for the above code and I created 2 roles (Center and Admin).

publicclass SD{publicconststringAdminUser="Admin";publicconststringCenterUser="Center";}

so , I want in the Login.cshtml.cs below to check if the "AccountStatusId = AccountStatusId.Pending" then prevent the user from successful login and display a message "Waits for Approval".

But I'm not sure how can i access the field "AccountStatusId" which is in "ApplicationUser" model and check this field if "Pending" in Login.cshtml.cs page. Any help is appreciated.

Login.cshtml.cs

namespace RegisterTest.Areas.Identity.Pages.Account{[AllowAnonymous]publicclassLoginModel:PageModel{privatereadonlyUserManager<IdentityUser> _userManager;privatereadonlySignInManager<IdentityUser> _signInManager;privatereadonlyILogger<LoginModel> _logger;publicLoginModel(SignInManager<IdentityUser> signInManager,ILogger<LoginModel> logger,UserManager<IdentityUser> userManager){
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;}[BindProperty]publicInputModelInput{get;set;}publicIList<AuthenticationScheme>ExternalLogins{get;set;}publicstringReturnUrl{get;set;}[TempData]publicstringErrorMessage{get;set;}publicclassInputModel{[Required][EmailAddress]publicstringEmail{get;set;}[Required][DataType(DataType.Password)]publicstringPassword{get;set;}[Display(Name="Remember me?")]publicboolRememberMe{get;set;}}publicasyncTaskOnGetAsync(string returnUrl =null){if(!string.IsNullOrEmpty(ErrorMessage)){ModelState.AddModelError(string.Empty,ErrorMessage);}
                returnUrl = returnUrl ??Url.Content("~/");// Clear the existing external cookie to ensure a clean login processawaitHttpContext.SignOutAsync(IdentityConstants.ExternalScheme);ExternalLogins=(await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();ReturnUrl= returnUrl;}publicasyncTask<IActionResult>OnPostAsync(string returnUrl =null){
                returnUrl = returnUrl ??Url.Content("~/");if(ModelState.IsValid){// This doesn't count login failures towards account lockout// To enable password failures to trigger account lockout, set lockoutOnFailure: truevar result =await _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:false);if(result.Succeeded){
                        _logger.LogInformation("User logged in.");returnLocalRedirect(returnUrl);}if(result.RequiresTwoFactor){returnRedirectToPage("./LoginWith2fa",new{ReturnUrl= returnUrl,RememberMe=Input.RememberMe});}if(result.IsLockedOut){
                        _logger.LogWarning("User account locked out.");returnRedirectToPage("./Lockout");}else{ModelState.AddModelError(string.Empty,"Invalid login attempt.");returnPage();}}// If we got this far, something failed, redisplay formreturnPage();}}}

.Net core in Visual Studio 2012

$
0
0

Hi

  Is .net core work with Visual Studio 2012 . If yes wht steps to be done

Thanks

asp.net core enforce https docker

$
0
0
<div>I have an asp.net core API which uses both http and https. To enforce the certificate use, I added the following in my program.cs:</div> <div>```</div> <div> private static IWebHost BuildWebHost(IConfiguration configuration, string[] args) =></div> <div>           WebHost.CreateDefaultBuilder(args)</div> <div>           </div> <div>            .UseKestrel(options =></div> <div>            {</div> <div> </div><div>                options.ConfigureEndpointDefaults(listenOptions =></div> <div>                {</div> <div>                    listenOptions.UseConnectionLogging();</div> <div>                });</div><div>            })</div> <div>               .CaptureStartupErrors(false)</div> <div>               .UseStartup<Startup>()</div> <div>            </div> <div>                .ConfigureKestrel(o =></div><div>                {</div> <div>                    o.ConfigureHttpsDefaults(o =></div> <div>                o.ClientCertificateMode =</div> <div>                    ClientCertificateMode.AllowCertificate);</div><div>                })</div> <div> </div> <div>```</div> <div>If I run my app in my windows machine, everything works correctly. Nevertheless, when I run it in my docker desktop or even in an ubuntu machine I am not able to call my https endpoint and I am getting a "ERR_CONNECTION_CLOSED". I am still able to call my http endpoint. In my docker compose ?I am setting correctly all the parameters:</div> <div> </div> <div>```</div> <div>environment:</div><div>      - ASPNETCORE_ENVIRONMENT=Development</div> <div>      - ASPNETCORE_URLS=https://+:443;http://+:80;https://+;http://+;</div> <div>      - ASPNETCORE_HTTPS_PORT=5001</div> <div>      - ASPNETCORE_Kestrel__Certificates__Default__Password=jtHxcTN</div><div>      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx</div> <div>    volumes:</div> <div>      - ~/.aspnet/https:/https:ro </div> <div>```</div> <div>I even tried to create a new certificate on my ubuntu using openssl but I am still having the same problem.</div> <div>PS: If I comment the line:</div> <div>```</div> <div> </div> <div>.ConfigureKestrel(o =></div> <div>               {</div> <div>                    o.ConfigureHttpsDefaults(o =></div> <div>                o.ClientCertificateMode =</div> <div>                    ClientCertificateMode.AllowCertificate);</div> <div>               })</div> <div>```</div> <div>I am able to call my https endpoint, but no certificate is sent to the server.</div> <div>Any help ?</div> <div>Thank you </div> <div></div>

Accessing Enum Claim in Login.cshtml.cs page

$
0
0

I'm developing a web application with ASP.Net Core MVC and identity. I extend the identity table as following with Enum field type "AccountStatusId" as following:

ApplicationUser.cs

namespace RegisterTest.Models{publicclassApplicationUser:IdentityUser{publicintStatusId{get;set;}publicstringStatusName{get;set;}publicAccountStatusIdAccountStatusId{get;set;}publicAccountStatusAccountStatus{get;set;}}publicenumAccountStatusId:int{Active=0,InActive=1,Expired=2,Locked=3}publicclassAccountStatus{publicAccountStatusIdAccountStatusId{get;set;}publicstringStatus{get;set;}publicList<ApplicationUser>Statuses{get;set;}}}

and to make sure that the account is locked after successful registration i make the AccountStatusId is locked by default in Register.cshtml.cs

var user =newApplicationUser{UserName=Input.Email,Email=Input.Email,AccountStatusId=AccountStatusId.Locked};

And i did all needed configuration in OnModelCreating method in ApplicationDbContext

Now, I want to check the "AccountStatus" field but in the Login.cshtml.cs. So, if the user who trying to log in with (AccountStatus.Locked) value -> display a message "Waiting for approval".

if the value (AccountStatus.Active) -> Successful Login.

After long search, I think i have to use claim in this situation. So, I come up with the following: 1) Creating customize claim: MyUserClaimsPrincipalFactory.cs

namespace RegisterTest.Controllers{publicclassMyUserClaimsPrincipalFactory:UserClaimsPrincipalFactory<ApplicationUser>{publicMyUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager,IOptions<IdentityOptions> optionsAccessor):base(userManager, optionsAccessor){}protectedoverrideasyncTask<ClaimsIdentity>GenerateClaimsAsync(ApplicationUser user){var identity =awaitbase.GenerateClaimsAsync(user);
            identity.AddEnumClaim("AccountStatus",AccountStatusId.Locked);return identity;}}}

2) Creating AddingEnumClaim class since AddClaim method just accept the string and i need it as Enum.

AddEnumClaim.cs

namespace RegisterTest.Controllers{publicstaticclassAddingEnumClaim{publicstaticvoidAddEnumClaim<T>(thisClaimsIdentity identity,String type, T enumvalue)where T :struct{if(!typeof(T).IsEnum)thrownewArgumentException("AddEnumClaim must be an enum");
            identity.AddClaim(newClaim(type, enumvalue.ToString()));}}}

Now all what i want is to chech the account status here in Login.cshtml.cs page, in OnPostAsync method.

publicasyncTask<IActionResult>OnPostAsync(string returnUrl =null){
            returnUrl = returnUrl ??Url.Content("~/");if(ModelState.IsValid){// This doesn't count login failures towards account lockout// To enable password failures to trigger account lockout, set lockoutOnFailure: truevar result =await _signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe, lockoutOnFailure:false);if(result.Succeeded){
                    _logger.LogInformation("User logged in.");returnLocalRedirect(returnUrl);}if(result.RequiresTwoFactor){returnRedirectToPage("./LoginWith2fa",new{ReturnUrl= returnUrl,RememberMe=Input.RememberMe});}if(result.IsLockedOut){
                    _logger.LogWarning("User account locked out.");returnRedirectToPage("./Lockout");}else{ModelState.AddModelError(string.Empty,"Invalid login attempt.");returnPage();}}// If we got this far, something failed, redisplay formreturnPage();}

Am i in the right track or i miss understanding something? Where i can exactly check the AccountStatus for a user while logging ?

Any help is appreciated

Custom Model Validation (IValidatableObject) Not working...

$
0
0

Hello and thanks for reading.  I'm a newbie, trying to learn .net core.  I was learning how to create a custom validator, not using the Validation Attribute but at the class level. Unfortunately, I can't make this one work, please check my code below:  

public class Blog : IValidatableObject
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }
        [Required(ErrorMessage = "Subtitle is required")]
        public string Subtitle { get; set; }

        //[
        //    //ValidarEdad,
        //    Required(AllowEmptyStrings = false, ErrorMessage = "Es mandatorio proveer su fecha de Nacimiento."),
        //    Display(Name = "Fecha de Nacimiento:")
        //    , DataType(DataType.DateTime)
        //]
        public DateTime Nacimiento { get; set; }

        [Required(ErrorMessage = "Url is required"), Display(Name = "URL del Blog:")]
        public string Url { get; set; }
        public string Description { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime ModifiedAt { get; set; }
        public int CreatedBy { get; set; }
        public int ModifiedBy { get; set; }
        public ICollection<Post> Posts { get; set; }

        [Required(ErrorMessage = "Author is required, kindly pick one!"), Display(Name ="Autor:")]
        public int? AuthorId { get; set; }
        public User Author { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            Debug.Write("----------------------------");
            Debug.Write("TEST TEST TEST");
            Debug.Write("----------------------------");

            //Blog myblog = (Blog)validationContext.ObjectInstance;          

            //if (Nacimiento > DateTime.Now)
            //{
                yield return new ValidationResult("There's a problem with this date field!", new []{ nameof(Nacimiento) });
            //}

        }
    }

Basically, I have multiple fields but I'm focusing on one field called "Nacimiento" which is a DateTime type, even if I commented on additional code and try to generate an error, nothing happens... I did try to post a message using the Debug.WriteLine to check if this class is doing something but nothing... it basically doesn't do anything, no error when running the validation of the form (server side), and not producing anything, no error messages, no compilation error messages also... please help.

In registration screen how can I show Isauthorised column just beside of the label

$
0
0

How can I show the IsAuthorised checkbox just close to the of its label

<div class="row"><div class="col-md-4"><form asp-route-returnUrl="@Model.ReturnUrl" method="post"><h4>Create a new account.</h4><hr /><div asp-validation-summary="All" class="text-danger"></div><div class="form-group"><label asp-for="Input.Name"></label><input asp-for="Input.Name" class="form-control" /><span asp-validation-for="Input.Name" class="text-danger"></span></div><div class="form-group"><label asp-for="Input.StreetAddress"></label><input asp-for="Input.StreetAddress" class="form-control" /><span asp-validation-for="Input.StreetAddress" class="text-danger"></span></div><div class="form-group"><label asp-for="Input.City"></label><input asp-for="Input.City" class="form-control" /><span asp-validation-for="Input.City" class="text-danger"></span></div>

            @*<div class="form-group"><label asp-for="Input.State"></label><input asp-for="Input.State" class="form-control" /><span asp-validation-for="Input.State" class="text-danger"></span></div>*@<div class="form-group"><label asp-for="Input.PostalCode"></label><input asp-for="Input.PostalCode" class="form-control" /><span asp-validation-for="Input.PostalCode" class="text-danger"></span></div><div class="form-group"><div class="col-4"><label asp-for="Input.IsAuthorised"> Authorised</label><input type="checkbox" asp-for="Input.IsAuthorised" class="form-control" /></div>
                @*<div class="col-4"><input type="checkbox" asp-for="Input.IsAuthorised" class="form-control" /></div>*@</div><div class="form-group"><label asp-for="Input.Email"></label><input asp-for="Input.Email" class="form-control" /><span asp-validation-for="Input.Email" class="text-danger"></span></div><div class="form-group"><label asp-for="Input.Password"></label><input asp-for="Input.Password" class="form-control" /><span asp-validation-for="Input.Password" class="text-danger"></span></div><div class="form-group"><label asp-for="Input.ConfirmPassword"></label><input asp-for="Input.ConfirmPassword" class="form-control" /><span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span></div><button type="submit" class="btn btn-primary">Register</button></form></div><div class="col-md-6 col-md-offset-2"><section><h4>Use another service to register.</h4><hr />
            @{
                if ((Model.ExternalLogins?.Count ?? 0) == 0)
                {<div><p>
                            There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                            for details on setting up this ASP.NET application to support logging in via external services.</p></div>
                }
                else
                {<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal"><div><p>
                                @foreach (var provider in Model.ExternalLogins)
                                {<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                                }</p></div></form>
                }
            }</section></div></div>

How can I have optional sections in my web form?

$
0
0

Hi,

I was just wondering how I could implement sections that are optional to a user as they are completing a required form? I'm working on a project and depending on user needs they may need to have the option to select different sections that apply to their request. I'm working with Razor Pages, there could be something that I am missing it would be great if someone could help point me in the right direction!

Thanks in advance


Routing to a selected language returns a blank page!

$
0
0

Hi

I've applied this topic for multilingual in mvc core 2.2 web app.:

https://medium.com/swlh/step-by-step-tutorial-to-build-multi-cultural-asp-net-core-web-app-3fac9a960c43

The example above is applied for none mvc core web app and I applied it for mvc one.

firstly, I Installed the required packages:

<PackageReference Include="LazZiya.ExpressLocalization" Version="4.0.0" /><PackageReference Include="LazZiya.TagHelpers" Version="4.0.1" />

Then I created new folder 'LocalizationResources' with two new classes in it:

    public class ExpressLocalizationResource
    {
    }
    public class ViewLocalizationResource
    {
    }

Then created a source file ViewLocalizationResource.ar.resx inside ViewLocalizationResource class with some strings:

Then configured Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    //Some code
            var cultures = new[]
            {
                new CultureInfo("tr"),
                new CultureInfo("ar"),
                new CultureInfo("hi"),
                new CultureInfo("en"),
            };
            services.AddMvc()
                 .AddExpressLocalization<ExpressLocalizationResource, ViewLocalizationResource>(
                 ops =>
                 {
                     ops.ResourcesPath = "LocalizationResources";
                     ops.RequestLocalizationOptions = o =>
                     {
                         o.SupportedCultures = cultures;
                         o.SupportedUICultures = cultures;
                         o.DefaultRequestCulture = new RequestCulture("en");
                     };
                 })
                 .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
             //Some code

            app.UseRequestLocalization();

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

Then _ViewImports.cs:

@using MultiLang
@using MultiLang.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@using System.Globalization

@addTagHelper *, LazZiya.TagHelpers
@addTagHelper *, LazZiya.ExpressLocalization

Then added the method to HomeController:

        public IActionResult SetCultureCookie(string cltr, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cltr)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );

            return LocalRedirect(returnUrl);
        }

Then added the rtl.css and ltr.css to css folder then updated shared _Layout:

@using System.Globalization
@{
    var culture = CultureInfo.CurrentCulture.Name;
    var dirCss = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? "rtl" : "ltr";
}

    @*Some Code*@

    <link rel="stylesheet" href="~/css/site.css" /><link rel="stylesheet" href="@($"/css/{dirCss}.css")" />

    @*Some Code*@

                    <partial name="_LoginPartial" /><language-nav cookie-handler-url="@Url.Action("SetCultureCookie", "Home", new { area="", cltr="{0}", returnUrl="{1}" })"></language-nav>

Then localized Home/Index view:

<div class="text-center"><h1 class="display-4" localize-content>Welcome</h1><p localize-content>Learn about</p></div>

for now every thing is working fine but when I firstly run the app. it is shown sometimes in Arabic and sometimes in English with successfully localized content according to the language.

Then if I navigate to any language of the four langauges, the page is shown blank with the two letters at the last of the url for example '/ar'.

Why? and How to solve please?

Relations between tables - ASP.NET CORE MVC

$
0
0

Hi,

 I need your help again. I have a project in ASP.NET that I have to read data and put this data in a database.

This is done.  The problem now is to relate these two tables.

I already made the relations in SQL Management Studio, but here in the project they don't work.

Explanation of the project:

One product can have more than one description.

So the descriptions must be in a different table

Now I will put the examples:

XML:

<products><product><id>100</id><name>Ball</name><price>15</price><quantity>2</quantity><description><comment>aaa</comment></description><description><comment>bbb</comment></description></product></products>

MODEL:

[Table("Table")]
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
        public int Quantity { get; set; }
    }
   [Table("Comentario")]
   public class Comment
    {
        [Key]
	public int Id {get;set;}

        public string DescriptionComment { get; set; }
    }

CONTROLLER:

private List<Product> ProcessImport(string path)
        {
            XDocument xDocument = XDocument.Load(path);
            List<Product> products = xDocument.Descendants("product").Select
                (p => new Product()
                {
                   Id = Convert.ToInt32(p.Element("id").Value),
                   Name=p.Element("name").Value,
                   Quantity = Convert.ToInt32(p.Element("quantity").Value),
                   Price = Convert.ToInt32(p.Element("price").Value),
                }).ToList();
             List<Comment> comments = xDocument.Descendants("description").Select
                (t => new Comment()
                {
                  DescriptionComment= t.Element("description").Value
                }).ToList();
            foreach(var product in products)
            {
                var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
                if (productInfo != null)
                {
                    productInfo.Id = product.Id;
                    productInfo.Name = product.Name;
                    productInfo.Quantity = product.Quantity;
                    productInfo.Price = product.Price;
                }

                else 
                { 
db.Products.Add(product); } db.SaveChanges(); } foreach (var comment in comments)
{
var commentInfo = db.Comments.SingleOrDefault(t => t.Id.Equals(comment.Id));
if(commentInfo != null)
{
commentInfo.Id = comment.Id;
commentInfo.DescriptionComment = comment.DescriptionComment;

}
else
{
db.Comments.Add(comment);
}
} return products; }

Does anyone have any idea how this is done?

Thanks for help me!

Navigation Property Woes for 1:1 relationship

$
0
0

I have 2 tables. bags and people.  Each bag was obtained from 1 person first.  So I have a foreign key on the bags table field ObtainedFromPerson that references the PersonNumber of the table of People (I've read that the letters ID have some special meaning in Entity Framework defaults, but unfortunately, I didn't use ID as part of either identifier).

When I read in all the bags from my database, I'd like each bag to also load the class member for the corresponding person.  It seems straightforward, but I can't seem to get it right and I don't know enough about the 'magic' EF is performing to figure it out.

For what it's worth, I have successfully implemented a 1->Many navigation that works great, so I'm baffled as to why this one won't work.  I've included the class members for the 1->many just in case they are interfering with the 1->1 somehow.

Here is my bag class (I excised several columns for brevity):

    [Table("bagsmvc")]
    public partial class Bagsmvc
    {
        [Key]
        [Column("id", TypeName = "int(11)")]
        public int Id { get; set; }
        [Column(TypeName = "varchar(255)")]
        [Required]
        public string Airline { get; set; } = "No Airline";
        [Column(TypeName = "int(11)")]
        public int? ObtainedFromPerson { get; set; }

        public int PersonxID { get; set; } // Only 1 person obtained from
        public Peoplemvc Personx { get; set; } // This is the person bag was obtained from 

        public ICollection<Linksmvccore> Links { get; set; }
}

Here is my class for people

    [Table("peoplemvc")]
    public partial class Peoplemvc
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int PersonNumber { get; set; }
        [Column(TypeName = "varchar(255)")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Column(TypeName = "varchar(255)")]
        [Display(Name = "Name")]
        public string LastName { get; set; }

        public ICollection<Linksmvccore> Links { get; set; } // Each person may be associated with lots of links

        // Each person may be associated with lots of bags, but I don't really care about this because it's a collection
        // of bags that sent me this bag *first*.  The Links table has all bags sent to me by this person, so this
        // line is probably unnecessary.
        public ICollection<Bagsmvc> Bags { get; set; } 

        // public Bagsmvc Bag { get; set; } // Each person may be associated with lots of bags
    }

And just in case this is causing the problem (indeed, reading this table is what triggers the error)

    [Table("linksmvccore")]
    public partial class Linksmvccore
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int LinkNumber { get; set; }
        [Column("BagID", TypeName = "int(11)")]
        public int BagId { get; set; }
        [Column("PersonID", TypeName = "int(11)")]
        public int PersonId { get; set; }

        public Bagsmvc Bag { get; set; }
        public Peoplemvc Person { get; set; }
    }

And here's the code that reads the Links table (actually it reads every table because it's generic)

                // First let's see if there are any foreign key navigation properties into another table (Links table)
                // We do this by seeing if there's an ICollection property that references the "many" table
                PropertyInfo property = typeof(T1).GetProperties()
                    .FirstOrDefault(x => x.PropertyType.Name.Contains("ICollection"));

                // If no Navigation Property is found, just read the table.  Otherwise read the table AND the related table
                if (property == null)
                {
                    results = await TableToRead.ToListAsync() as List<T1>;
                } else
                {
                    results = await TableToRead.Include(property.Name).ToListAsync() as List<T1>;
                }

Earlier in the code, TableToRead is set to _context.Linksmvccore.  I realize that as some point I'll need to issue

results = await TableToRead.Include("Personx").ToListAsync() as List<T1>;

to make sure the navigation property is loaded, but it shouldn't break if I don't issue the call.  Instead, I get the following error:

An unhandled exception occurred while processing the request.

<div class="titleerror">MySqlException: Unknown column 'b.PersonxID' in 'field list'</div>

MySqlConnector.Core.ServerSession.ReceiveReplyAsyncAwaited(ValueTask<ArraySegment<byte>> task) in ServerSession.cs, line 774

<div class="titleerror">MySqlException: Unknown column 'b.PersonxID' in 'field list'</div>

MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet() in MySqlDataReader.cs, line 130

You can now see why I used the property name PersonxID ... so there would be no ambiguity as to which similarly named field is causing the problem.  I even tried stripping out all the navigation properties from the linksmvccore table as well as the properties in bagsmvc and peoplemvc, but I still get the error.  

Any help appreciated.

How to remove Hours From Date Control

$
0
0

Hello

I have this control

<div> </div> <div>        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]</div> <div>        [Required(ErrorMessage = "Captura este campo")]</div> <div>        public DateTime? BirthDate { get; set; }</div> <div></div> <div><div class="row">
<div class="col-md-12">
<div class="form-group">
<label asp-for="BirthDate" class="control-label"></label>
<input asp-for="BirthDate" asp-format="{0:dd/MM/yyyy}" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
</div>
</div>
</div> <div></div> <div>I want to ask only for Date and not the hours and the minutes, how can i do this ?</div>

Want to update all three textbox using update button

$
0
0
  • <div class="comment-right-col comment-body"> <div>

    hello

    in my code i created store procedure in database sp_updatepackage and in the where condition of procedure i used package_name which is the first textbox in aspx package name in this where condition i dont want to update package_name because where condition package_name is used

    so my requirement is how to update package_name without it use as where is there any change in procedure or in frontend

    please execute them?

    here is my code

    aspx

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="WebForm61.aspx.cs" Inherits="WebApplication14.WebForm61" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="server">

    <div >
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

    <table>

    <tr>

    <td><span style="margin-left:20px">Package name</span><br />
    <span style="margin-left:20px"><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </span>
    </td>

    <td ><span style="margin-left:100px">Reward</span><br />
    <span style="margin-left:100px"><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </span>
    </td>

    <td><span style="margin-left:100px">Remarks</span><br />
    <span style="margin-left:100px"><asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
    </span>
    </td>
    </tr>

    </table>

    <br />

    <br />

    <asp:Button ID="Button2" runat="server" Text="Save" OnClick="Button2_Click" />
    <asp:button ID="Button3" runat="server" Text="update" OnClick="Button3_Click" />
    <br />
    <br />

    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="both"
    AutoGenerateColumns="False"
    DataKeyNames="tbl_id" Height="264px" Width="100%"
    BorderColor="#FF0066" >
    <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:TemplateField>

    <ItemTemplate>
    <asp:LinkButton ID="Button1" runat="server" Width="25px" OnClick="Button1_Click">edit</asp:LinkButton>
    </ItemTemplate>

    </asp:TemplateField>
    <asp:BoundField DataField="package_name" HeaderText="Package name" />
    <asp:BoundField DataField="reward" HeaderText="Reward" />
    <asp:BoundField DataField="remarks" HeaderText="Remarks" />

    </Columns>
    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
    <SelectedRowStyle BackColor="#FF66FF" />
    </asp:GridView>

    </ContentTemplate>
    </asp:UpdatePanel>

    </div>


    </asp:Content>

    css

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;

    namespace WebApplication14
    {
    public partial class WebForm61 : System.Web.UI.Page
    {
    SqlCommand cmd = new SqlCommand();
    SqlConnection con = new SqlConnection();
    string connection = System.Configuration.ConfigurationManager.AppSettings["con"].ToString();


    public void EstablishConnection(string storeprocedure)
    {
    con.ConnectionString = connection;
    cmd.Connection = con;
    cmd.Connection.Open();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = storeprocedure;
    }


    public void CloseConnection()
    {
    cmd.Connection.Close();
    cmd.Connection.Dispose();
    con.Close();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    FillGridview();
    Button3.Visible = false;
    }
    }

    public void FillGridview()
    {
    SqlDataAdapter adp = new SqlDataAdapter(" select * from tbl_package", connection);
    DataTable DT = new DataTable();
    adp.Fill(DT);
    GridView1.DataSource = DT;
    GridView1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    LinkButton btn = (LinkButton)sender;
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
    TextBox2.Text = gvr.Cells[0].Text;
    TextBox3.Text = gvr.Cells[1].Text;
    TextBox4.Text = gvr.Cells[2].Text;

    Button2.Visible = false;
    Button3.Visible = true;

    }


    protected void Button2_Click(object sender, EventArgs e)
    {
    EstablishConnection("sp_insert_package");
    cmd.Parameters.Add("@package_name", SqlDbType.VarChar, 255).Value = TextBox2.Text;
    cmd.Parameters.Add("@reward", SqlDbType.VarChar, 255).Value = TextBox3.Text;
    cmd.Parameters.Add("@remarks", SqlDbType.NVarChar, 255).Value = TextBox4.Text;
    cmd.Parameters.Add("@by_whom", SqlDbType.VarChar, 255).Value = "1";
    cmd.Parameters.Add("@date_time", SqlDbType.VarChar, 255).Value = System.DateTime.Now.ToString();
    cmd.Parameters.Add("@status", SqlDbType.VarChar, 255).Value = "1";

    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "anything", "alert('Record Add Sucessfully');", true);
    try { cmd.ExecuteNonQuery(); }
    catch (Exception ex1) { Response.Write("<script language=javascript>alert('" + ex1.Message.ToString() + ".')</script>"); }

    FillGridview();

    con.Close();
    CloseConnection();
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
    EstablishConnection("sp_update_package");
    cmd.Parameters.Add("@package_name", SqlDbType.VarChar, 255).Value = TextBox2.Text;
    cmd.Parameters.Add("@reward", SqlDbType.VarChar, 255).Value = TextBox3.Text;
    cmd.Parameters.Add("@remarks", SqlDbType.NVarChar, 255).Value = TextBox4.Text;
    cmd.Parameters.Add("@by_whom", SqlDbType.VarChar, 255).Value = "1";
    cmd.Parameters.Add("@date_time", SqlDbType.VarChar, 255).Value = System.DateTime.Now.ToString();
    cmd.Parameters.Add("@status", SqlDbType.VarChar, 255).Value = "1";

    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "anything", "alert('Record Add Sucessfully');", true);
    try { cmd.ExecuteNonQuery(); }
    catch (Exception ex1) { Response.Write("<script language=javascript>alert('" + ex1.Message.ToString() + ".')</script>"); }

    FillGridview();

    con.Close();
    CloseConnection();
    }

    }
    }

    </div> </div>
Viewing all 9386 articles
Browse latest View live


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