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

.Net Core Email Confirm Gmail smtp problems

$
0
0

I have a .net core 2.2 app with identity package and email confirmation required for users who register. I was able to have this send successfully after configuring my gmail to "allow less secure apps" . Now I am receiving error :"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required " when new user registers. I have a class called emailsender that draws from appsettings.json file. 

Emailsender.cs:

using Microsoft.Extensions.Options;
using RequireConfirmedEmail.Entities;
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
///

namespace RequireConfirmedEmail.Services
{
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string htmlMessage);
}

public class EmailSender : IEmailSender
{
private readonly EmailSettings _emailSettings;

public EmailSender(IOptions<EmailSettings> emailSettings)
{
_emailSettings = emailSettings.Value;
}

public Task SendEmailAsync(string email, string subject, string message)
{
try
{
// Credentials
var credentials = new NetworkCredential(_emailSettings.Sender, _emailSettings.Password);

///
// Mail message
var mail = new MailMessage()
{
From = new MailAddress(_emailSettings.Sender, _emailSettings.SenderName),
Subject = subject,
Body = message,
IsBodyHtml = true
};

mail.To.Add(new MailAddress(email));

// Smtp client
var client = new SmtpClient()
{
Port = _emailSettings.MailPort,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = _emailSettings.MailServer,
EnableSsl = true,
Credentials = credentials
};

// Send it...
client.Send(mail);
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}

return Task.CompletedTask;
}
}
}

====================appsettings.json

{
"ConnectionStrings": {
"DefaultConnection": "Data Source=111.111.111.11;initial catalog=mydb;persist security info=True;user id=myusername;password=yyy;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"EmailSettings": {
"MailServer": "smtp.gmail.com",
"MailPort": 587,
"SenderName": "My Company",
"Sender": "mymail@gmail.com",

"Password": "zzz"

}
}

My gmail is configured for "allow less secure apps" , takes 587 for port via ssl 

??
thanks in advance

Ned


TrustServerCertificate=false

$
0
0

Hi Expert,

I set  TrustServerCertificate=false; Encrypt=True" in webconfig and using sql server TLS certificate getting error message

Server Error in '/' Application.


The target principal name is incorrect

Connection string

<add name="SQLConnectionString" providerName="System.Data.SqlClient" connectionString="Server=xxx;Database=xxx;User ID=xxxx;Password=xxx1;MultipleActiveResultSets=True;Use Encryption for Data=True; TrustServerCertificate=false; Encrypt=True" />

asp.net core razor page checkboxes model binding (always false)

$
0
0

i have a razor page in asp.net core with the following input tag:

<input asp-for="chkPref" />

in the code-behind i have:

public bool chkPref { getset; }

so when i run the app, i can confirm in `Request.Form` that I'm getting...

checkbox checked = {true,false}

checkbox unchecked = {false}

which is expected, according to https://www.learnrazorpages.com/razor-pages/forms/checkboxes

however, that page states that the model binding will figure out that `{true,false}` is actually `true` but i'm getting `false` no matter what.

the website above alludes to the fact that this "just happens"...

If the checkbox is checked, the posted value will be true,false. The model binder will correctly extract true from the value. Otherwise it will be false.

but that doesn't seem to be working, or at least isn't that obvious how it works.

How to handle url redirect in dotnet core

$
0
0

I have a web application that wants to do authentication on every http request. I am trying to build a custom middle ware to do this

here is what I am looking to do

1. a user makes a request to an end point in my application http://localhost:5000/api/get-------> 302 Response

  1. I generate a redirect to do authorization http://{domain}/authorize ----------> 200 response if successful

  2. I return 200 with results if authorization is success or 401 if not http://localhost:5000/api/get-------> 200 or 401 response

in my middles ware I am calling httpContext.Response.Redirect("http://{domain}/authorize", false);

which generates the redirect, but how can I go from there? 

How can I capture the new httpContext which in that case the authorize call and how can I go back to the original context to return 200 after success?

How to format a date as a constant.

$
0
0

I have a Constants class file in my solution that is used for roles and messages and I need to create one for date formatting. Currently on several views, I have the date formatted as 

<div><div class="card-body"><h4 class="card-title"><a class="forum-orange"
                       style="text-decoration:underline"
                       asp-action="Packet"
                       asp-controller="Home"
                       asp-route-packetId="@Model.PacketId">
                        Meeting: 
                        @Model.Title</a></h4><div class="card-text">
                    Meeting date: <b> @Model.MeetingDateTime.ToString("dddd, MMMM dd yyyy h:mm tt")</b></div><div class="card-text">
                    Meeting time:<b> @Model.MeetingDateTime.ToString("hh:mm tt") </b></div><p class="card-text"><h6 class="forum-orange">
                        Voting has expired on<br/>  @Model.CODateTime.ToString("dddd, MMMM dd yyyy h:mm tt")</h6></p></div></div>

I added this to my constants class:

 public static class FormatDate
        {

           public const string DEFAULT_DATE_FORMAT = "dddd, MMMM dd yyyy h:mm tt";

        }

And this updated the view:

<div><div class="card-body"><h4 class="card-title"><a class="forum-orange"
                       style="text-decoration:underline"
                       asp-action="Packet"
                       asp-controller="Home"
                       asp-route-packetId="@Model.PacketId">
                        Meeting: 
                        @Model.Title</a></h4><div class="card-text">
                    Meeting date: <b> @Model.MeetingDateTime.ToString(Constants.FormatDate.DEFAULT_DATE_FORMAT)</b></div><div class="card-text">
                    Meeting time:<b> @Model.MeetingDateTime.ToString("hh:mm tt") </b></div><p class="card-text"><h6 class="forum-orange">
                        Voting has expired on<br/> @Model.CODateTime.ToString(Constants.FormatDate.DEFAULT_DATE_FORMAT)</h6></p></div></div>

Would this be correct?

Using a Queueing System for notification Messages. For 100 % Delivery Gauranttee

$
0
0

Dear All,

So I have built an application that handles several kinds of transactions for merchant. I am trying to build a microservice that would give notification to my merchants.

So my requirement is to ensure that messages deliver even if there is network problems. I am suppose to ensure that there is not failure point at any conditions.

So technical requirement involves I ensure that messages are queued so if there is network problems. So I send messages to another services that would be needing it.

I would also send messages to my merchants through a web hook or call back url. Please Queueing system do I use.

Any materials that I can read up on.

Best Regards,

JIde

Problema com retorno Json - asp.net core

$
0
0

Olá, boa noite!

Estou tentando carregar um DropDownList em cascata via Ajax no asp.net core / C #, mas não estou conseguindo, alguém pode me ajudar.

Carrega na DropDownList o valor UNDFINED.

MEU SCRIPT:<script type="text/javascript">$(document).ready(function(){$('#idDepartamento').change(function(){
        var idDep = $('#idDepartamento').val();
        if (idDep > 0){$.post('@Url.Action("ListaPerfil","AcessoUsuario")', {'idDep': idDep}, function (data) {
                if (data.length > 0){$('#idPerfilUsuario').empty();
                    for (var i = 0; i < data.length; i++){
                        //$('#idPerfilUsuario').append('<option value="' + data[i].Id + '">' + data[i].Nome + '</option>');
                        //$('#idPerfilUsuario').append("<option>" + data.Nome + "</option>");$('#idPerfil').append('<option value="' + data[i].Id + '">' + data[i].DescricaoPerfil + '</option>');
                    }
                }
            });
        }
    });
});</script>
MINHA VIEW:

<div class="form-group"><label asp-for="IdDepartamento" class="control-label" ></label><select asp-for="IdDepartamento" class ="form-control" id="idDepartamento" asp-items="ViewBag.IdDepartamento"><option value="">Departamento...</option></select></div><div class="form-group"><label asp-for="IdPerfil" class="control-label"></label><select asp-for="IdPerfil" class ="form-control" id="idPerfil"><option value="">Perfil...</option></select></div>
MEU CONTROLLER:

[HttpPost]
        public ActionResult ListaPerfil(int idDep)
        {
            //ViewData["IdPerfil"] = new SelectList(_context.PerfilUsuario, "Id", "DescricaoPerfil");
            //return RedirectToAction(nameof(Index));
            //return View();
            List<PerfilUsuario> list = new List<PerfilUsuario>();
            list = _context.PerfilUsuario.Where(p => p.IdDepartamento == idDep).ToList();

            return Json(new SelectList(list, "Id", "DescricaoPerfil"));

        }




Class Library Tag Helper for Partial Pages not working in ASP.NET Core Razor Pages application

$
0
0

As part of my work on an ASP.NET Core 3.1 Razor Pages web application, I created several custom Tag Helpers. Once I had all of these working the way I wanted and expected (as part of the ASP.NET Core 3.1 application), I moved the Tag Helpers to a Razor Class Library (.NET Standard 2.1), so I could use the custom Tag Helpers in other applications.

That is where I ran into a problem with a Tag Helper to render a Partial Page using the PartialTagHelper class:

TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope' from assembly 'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

The constructor for the PartialTagHelper class requires the IViewBufferScope parameter noted in this error and is passed into the custom Tag Helper code via Dependency Injection.

In the ASP.NET Core 3.1 Razor Page, the custom Tag Helper code requires a 'using' reference to the Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers namespace.

In the Razor Class Library, the custom Tag Helper code requires a 'using' reference to the Microsoft.AspNetCore.Mvc.ViewFeatures.Internal namespace. 

I also tried using .NET Standard 2.0 and 2.1 as well as .NET Core 3.1 Class Libraries.  In all of these situations, the Class Library required references to Microsoft.AspNetCore.Mvc.ViewFeatures version 2.2.0 and Microsoft.AspNetCore.Razor version 2.2.0 in order to compile.

So, the error sounds like ASP.NET Core 3.1 Razor Page is injecting the 3.1.3 Microsoft.AspNetCore.Mvc.ViewFeatures assembly and this does not contain the IViewBufferScope parameter from the correct assembly.

Is there a way to resolve this?

Thanks


How to store exponential value in sql server

$
0
0

I want to store exponential value as it is in database in sql server.How can I store exponential value in sql server as it is without any formatting?

Please help me out with same.

Thanking you.

ASP.NET Core 2.2 Web API Angular. Hosting provider says 500 - Internal server error.

$
0
0

Summary of the problem I am having:

I am trying to publish ASP.NET Core 2.2 Web API and Angular 8 project with a hosting provider SmarterASP.NET that supports ASP.NET Core. However, I am getting an error.

However, the project works perfectly if I start it locally.

I searched through the Internet and various forums and see this questionanother one question and this github post.

Error I am receiving:

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.

My code:

This is my `Main` method:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        WebHost.CreateDefaultBuilder(args)
           .UseSetting(WebHostDefaults.DetailedErrorsKey, "true");
        host.Run();
    }
}

This is my `Configure()` of `StartUp` class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    IServiceProvider provider)
{
    if (env.IsDevelopment())
    {
	app.UseDeveloperExceptionPage();
    }
    else
    {
	// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
	app.UseHsts();
    }		
    app.Use(async (context, next) =>
    {
	await next();
        if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
	{
	    context.Request.Path = "/index.html";
            await next();
	}
    });		
    app.ConfigureCustomExceptionMiddleware();
    app.UseCors("ApiCorsPolicy");
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles")),
            RequestPath = new PathString("/StaticFiles")
    });
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseMvc();
    app.UseDeveloperExceptionPage();
}

And this is my `web.config` file:

<?xml version="1.0" encoding="utf-8"?><configuration><location path="." inheritInChildApplications="false"><system.webServer><httpErrors errorMode="Detailed" /><aspNetCore processPath="dotnet"><environmentVariables><environmentVariable name="ASPNETCORE_DETAILEDERRORS" value="true" /></environmentVariables></aspNetCore><handlers><add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" 
                    resourceType="Unspecified" /></handlers><aspNetCore processPath="dotnet" arguments=".\fooappl.dll" 
                stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" 
                hostingModel="InProcess" /></system.webServer></location><system.web><customErrors mode="Off"/></system.web></configuration><!--ProjectGuid: 25e0e882-c3ff-4f8d-98cc-f26a692fa019-->

I am little bit stuck. Could you say what am I doing wrong?

can i get a value from a Type?

$
0
0

i have a class which has a value

public class foo
{
   public string SomeValue => "999";
}

i only have the Type,is there a way to

public void SomeWork(Type type)
{
 var avariable = //get 999 from the Type
}

the value is fixed in the class, which will then be used to inherite from.

i am trying to not need to manually put the value in the method.

any suggestions appriciated.

Creating non-hackable User Registration Page using Data Annotations

$
0
0

I have a user registration razor page and corresponding action that uses UserManager and SignInManager to create user accounts.  It works just fine.

However, I only want a few people to be able to register so I have disabled all links to /Accounts/Register.  But it's easy enough for someone or some bot to guess at the registration route, register and then log in.  I am not sure what the best way to "hide" the registration might be.  Here are possibilities I came up with:

  • Create a hard-to-guess route and corresponding action such as /Accounts/xpflqj7t99y  Only those who are sent the route can register.
  • Let anyone register but make the default roles as restrictive as possible
  • Add a field to the view model called something like "Secret" (which is sent to select people only) and decorate it with a data annotation such as 
[RegularExpression("^Th1s1sAnUnl1kelyS3cr3t$", ErrorMessage = "Incorrect Secret")]
public string Secret { get; set; }

The last one seems to be the easiest but I don't know if Data Annotations are secure.  Is there some accepted convention of doing this that I'm missing?

Page Routing based on a custom value

$
0
0

Hello:

I need to authorize MVC pages based on a combination of custom values that I obtain from the user logged in, for example:

A logged in user will see a certain page(s) if they have a code value of "ABCD" that I generate from querying certain values from their extension attributes. If the code value is "WXYZ" then they will see another page.

Thanks.

Web App Recommendation

$
0
0

Hello all:

I understand it might be difficult making a recommendation without full details, but due to privacy concerns I cannot relate all details, and will give as much info as possible.

I need a web site built for an industrial application, like say a factory, that might have up to 5000 users, and 20000+ IOT or other devices as part of a project at the facility. User interactions with the IOT devices will need to be captured in the database and the web site will produce dashboards on the activities, but note it is not a high demand for concurrent transactions. The web site will also need to perform administrative functions like adding users, assigning user permissions, adding IOT devices, adding facility machines and equipment, etc.

So I have been reading about ASP.NET Core

https://docs.microsoft.com/en-us/aspnet/core/introduction-to-aspnet-core?view=aspnetcore-3.1

but am a bit confused how it all comes together. If I create an ASP.NET Core Web Project in Visual Studio, I see the Options for MVC, Angular, React. Etc. When I select MVC I am able to add APIs for communicating with an Azure database and allow things like an IOS app to go through the Web APIs to the database, so do options like Angular and React provide the ability to style the front end? I am trying to understand out how I go from the rather bland ASP.NET Core MVC site, to things like this demo, but still using .NET for the APIs?

https://coderthemes.com/zircos/layouts/vertical/chart-morris.html

That demo says it was built using CSS, HTML, JS, so what would Angular or React have to do with that? Wouldn't .NET APIs be used to get the data from the database in JSON format, and then I guess JS would be used to parse the data to the right charts? Or is that where Angular or React would come in?

Thanks for any and all input.

John.

Bind certain properties of the navigation properties inside my action method

$
0
0

I have the following 2 model classes:-

 public Submission()
        {
            SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Npi { get; set; }
        public bool Independent { get; set; }
        public string Comment { get; set; }

        public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
    }


public partial class SubmissionQuestionSubmission
    {
        public int SubmissionQuestionId { get; set; }
        public int SubmissionId { get; set; }
        public string Answer { get; set; }

        public virtual Submission Submission { get; set; }
    }

and i created the following view model:-

public class SubmissionCreate
    {
        public Submission Submission {set; get;}
        public IList<SubmissionQuestion> SubmissionQuestion { set; get; }

        public IList<SubmissionQuestionSubmission> SubmissionQuestionSubmission { set; get; }

    }

then inside my view i only need to submit back the following fields:-

@model LandingPageFinal3.ViewModels.SubmissionCreate<form asp-action="Create"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Submission.FirstName" class="control-label"></label><input asp-for="Submission.FirstName" class="form-control" /><span asp-validation-for="Submission.FirstName" class="text-danger"></span></div><div class="form-group"><label asp-for="Submission.LastName" class="control-label"></label><input asp-for="Submission.LastName" class="form-control" /><span asp-validation-for="Submission.LastName" class="text-danger"></span></div><div class="form-group"><label asp-for="Submission.Npi" class="control-label"></label><input asp-for="Submission.Npi" class="form-control" /><span asp-validation-for="Submission.Npi" class="text-danger"></span></div><div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" asp-for="Submission.Independent" /> @Html.DisplayNameFor(model => model.Submission.Independent)</label></div><div class="form-group"><label asp-for="Submission.Comment" class="control-label"></label><textarea asp-for="Submission.Comment" class="form-control"></textarea><span asp-validation-for="Submission.Comment" class="text-danger"></span></div><div id="additionalInfo">
                    @for (var i = 0; i < Model.SubmissionQuestion.Count(); i++)
                    {<label>@Model.SubmissionQuestion[i].Question</label><br /><input asp-for="@Model.SubmissionQuestion[i].Question" hidden /><textarea asp-for="@Model.SubmissionQuestionSubmission[i].Answer" class="form-control"></textarea><input asp-for="@Model.SubmissionQuestionSubmission[i].SubmissionQuestionId" hidden /><br />
                    }</div>

so i define the following binding inside my post action method, to only bind the fields inside my view, as follow:-

public async Task<IActionResult> Create([Bind(Submission.FirstName,Submission.LastName,Submission.Npi,Submission.Independent" +"Submission.Comment,SubmissionQuestionSubmission.Answer,SubmissionQuestionSubmission.SubmissionQuestionId")] SubmissionCreate sc )
        {

but the sc.Submission and the sc.SubmissionQuestionSubmission will be null inside my action method... so not sure what is the minimum binding i should define?


Calling a WCF web service

KB4556813 or KB4552926 broke .NET, has anyone else experienced this?

$
0
0

Hello all,

Last night we installed two updates on a 2016 Data Center edition server, KB4556813 or KB4552926. 2926 specifically dealing with .NET. The server is configured as a web application server which runs APIs configured to use .NET. When going to the API on an individual server, we were receiving a 500 error. Looking at the event logs on the server it was telling us it could not find the .NET Core framework for the application. What we ended up doing is going in the program and features and clicking on the repair option for the framework and running the repair. After that, the API starts to work. Please let me know. Thanks!

how to migrate wcf in .net core

$
0
0

Hi team

i am migarting asp.net project to ,net core 3.1

how to migrate wcf  here , shall i migrate wcf or use rest api for this or any other better suggestion

please suggest

How to load Navigation Properties in a generic method

$
0
0

I would like to read data from a DB context and eagerly load the navigation properties.  My code successfully does this:

List<Peoplemvc> ap = await _context.People.Include(x => x.Links).ToListAsync();

The model I'm using is this

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

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

The navigation property references the following model

    [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; }
    }

I currently have a generic method that reads tables successfully

public async Task<List<T1>> GetFromTable<T1>(DbSet<T1> TableToRead) where T1 : class
        {
            List<T1> results = new List<T1>();
            results = await TableToRead.ToListAsync() as List<T1>;
            return results;
         }

The question is how do I get this method to include / populate navigation properties if they exist in my model?  I imagine I'd use reflection but not sure how to implement it.  I am fine passing along an argument to the method with the navigation property like this, but don't know how to do it.

// I know this is not correct!
public async Task<List<T1>> GetFromTable<T1, T2>(DbSet<T1> TableToRead, Icollection<T2> nav) 
where T1 : class
where T2 : class
{
List<T1> results = new List<T1>();
results = await TableToRead.Include(x => x.nav).ToListAsync() as List<T1>;
return results;
}

Any help appreciated

use existing dll

$
0
0

Hi Team,

I am doing migration asp.net project 4.5 framework to asp.net core 3.1

how to use code which is poiting to system.windows.form in .net framework can i add same dll in my .net core project as i am not able to add from nugest package installer

second doubt is can i use dll in .net framework to .net core as in .net core i am not able to add via nuget package manager

any suggestion and help will be highly appreciated on how to proceed further on this.
Regards

Viewing all 9386 articles
Browse latest View live


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