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

UserManager problem

$
0
0

I upgraded to VS 2017 and am having all sorts of problems, this time with the User Manager in my project when I try to seed the database. See below. I can't believe something so basic would have changed.

System.AggregateException occurred
HResult=0x80131500
Message=One or more errors occurred.
Source=<Cannot evaluate the exception source>
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at RIMS.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DataSeeder seeder) in[path]\Startup.cs:line 135

Inner Exception 1:
SqlException: Invalid object name '[appName].Users'.


ASP.NET Web pages on ASP.NET Core

$
0
0

Are you able to create a ASP.NET Web Pages website on ASP.Net Core or are you tide only to MVC?

Alternative for BeginCollectionItem?

$
0
0

I'm using 'BeginCollectionItem" for dynamic fieldset which rendering a sequence of items that should later be model bound to a single collection.

Just wonder is there any other alternative to implement the same thing?

@using (Html.BeginCollectionItem("books"))
{

}

Received error message "Package 'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.0' has a package type 'DotnetCliTool' that is not supported by project 'ContosoUniversity'"

$
0
0

I am trying to follow this tutorial on creating an ASP.NET Core MVC and Entity Framework Core app, and I tried installing the NuGet package Microsoft.EntityFrameworkCore.Tools.DotNet, as the topic "Entity Framework Core NuGet packages" in the tutorial instructs. I received the error message "Package 'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.0' has a package type 'DotnetCliTool' that is not supported by project 'ContosoUniversity'".

Whether I try installing the package using the Package Manager Console or the NuGet Package Manager, I get the error message. The full error message that the Package Manager Console shows is the following:

Install-Package : Package 'Microsoft.EntityFrameworkCore.Tools.DotNet 1.0.0' has a package type 'DotnetCliTool' that is not
supported by project 'ContosoUniversity'.
At line:1 char:1
+ Install-Package Microsoft.EntityFrameworkCore.Tools.DotNet
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
 

I made sure that my ContosoUniversity.csproj file included the DotNetCliToolReference for Microsoft.EntityFrameworkCore.Tools.DotNet, as suggested in Stack Overflow:

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
  </ItemGroup>

This issue has been reported on GitHub, already. I am using Visual Studio 2017. Thank you.

RESTFUL API's

$
0
0

I am trying to learn Restful api's using Asp.net core can anyone kindly guide me .Thank you :)

How to retrieve data of nested class instance from parent class instance in ASP.NET Core?

$
0
0

I am trying to modeling a class at school, and I end up with something like this:

public class Class
{
    public int ID { get; set; }
    public int Grade { get; set; }
    public Teacher ClassTeacher { get; set; }
}

This is the Teacher class:

public class Teacher
{
    public int ID { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    public DateTime Birthday { get; set; }
}

When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me:

dbo.Class:
ID: int
ClassTeacherID: int
Grade: int

dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)

I want to display the Teacher's FirstName in Views\Classes\Details.cshtml, but the Model.ClassTeacher is null, even after I created a Teacher instance in the database and set ClassTeacherID to the newly created Teacher's ID. Looking for your helps.

install .net core sdk on centos 7.2

Doubts about the access from the WAN on site asp.net core ...

$
0
0

Hello to all, Icreated a websitewithasp.net1.1coreMVCI havemade all the necessaryconfigurations, i can connecttothe home pageonly ifI map"127.0.0.1"or "public IP"withvirtual sitename in the hosts fileof the machinefrom whichI connect(serverin the first caseandfrom anyremote machinein the second case)with the address"http: //virtualsitename: port"Otherwiseif I connectwith the followingURL"http://IP:9191/ virtualsitename"or "http://IP:9191" I havethe following error:

Bad Request - Invalid Hostname

HTTP Error 400. The request hostname is invalid.

Ifto get to mysiteIuse a link locatedon another siteas it should be thelink?


Web api is removed in asp.net core

$
0
0

i heard that now we can do http service based apps using mvc so from now on we do not need web api template in asp.net core. is it true?

if it is true.....web api was service and has no UI but mvc app is UI architecture. so how one can develop service which will have no UI with asp.net mvc core.

please some one discuss this issue. thanks

Special characters in c#,Asp.net

$
0
0

Original file name in .csv file -:

Stockinger Jörg 71105 (U).pdf

After reading file name in c#-:

Stockinger J�rg 71105 (U).pdf

how can i read original file path without change in special chars in c#,Asp.net?

please provide solution if anybody have an idea,Thanks in advance

Visual Studio 2015 Web Deploy And Entity Framework Failing To Create Trigger

$
0
0

I'm using Web Deploy to publish my website to a Azure Web Application with a SQL Database. I'm testing with MSSQL 2016 on my development machine. I'm using the code first model. I created a model to store security questions.

SecurityQuestion Model:

public class SecurityQuestion
{
    public int Id { get; set; }

    [Column(TypeName = "NVARCHAR(250)")]
    public string Description { get; set; }

    [Column(TypeName = "NVARCHAR(250)")]
    public string NormalizeDescription { get; set; }

    [Column(TypeName = "NVARCHAR(450)")]
    [ForeignKey("IdentityCreated")]
    public string CreatedIdentityId { get; set; }

    public DateTime Created { get; set; }

    [Column(TypeName = "NVARCHAR(450)")]
    [ForeignKey("IdentityDisabled")]
    public string DisabledIdentityId { get; set; }

    public DateTime? Disabled { get; set; }

    public ApplicationUser IdentityCreated { get; set; }
    public ApplicationUser IdentityDisabled { get; set; }
}

I wanted to be able to only add a Description and then have a trigger on the back end set the NormalizeDescription to the UPPERCASE version of the description after insert.

I created a migration to create the SecurityQuestion Table. Before I updated the database with the migration I added this bit of code to create a trigger after the table is created.

Trigger:

migrationBuilder.Sql("CREATE TRIGGER [dbo].[Trigger_SecurityQuestions_NormalizeDescription_AfterInsert] ON [dbo].[SecurityQuestions] AFTER INSERT AS BEGIN SET NOCOUNT ON; Update [dbo].[SecurityQuestions] Set [NormalizeDescription] = UPPER([Description]) Where [NormalizeDescription] is NULL; END");

I use the Update-Database command to push the changes to the database in development. The trigger is created just find and works properly. I publish the changes to my Azure account and the TRIGGER causes a error. The error says "Incorrect syntax near the keyword Trigger". This also has a side effect of not publishing my site correctly and the fails to displayed correctly after that.

I had to eliminate the trigger for now because I have no clue why it's not working correctly.

Any Ideas why this TRIGGER is causing this error?

Asp.net Core Data Annotations failing to decorated multiples of the same model type.

$
0
0

I'm using a partial view to create a security question and answer view using a model. Besides the issue of naming each one with a index number. That is a whole seperate issue all together.
I want 3 security questions and answers. I add the partial view 3 times to create 3 security questions and answers. Of those 3 only the the first security question and answer is decorated with
model requirements. The next 2 is missing the model requirements. I decided this is a [BUG]. At some point the web controls get decorated with the model requirements. For some reason it only does one
and ignores the reset.

What is going on here and why is this not working failing

Model:

public class QNAViewModel
{
     [Required(ErrorMessage = "The question field is required")]
     public String Question { get; set;}

     [Required(ErrorMessage = "The answer field is required")]
     [StringLength(250, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
     public String Answer { get; set; }

}

Partial View:

@model MyNameSpace.Models.ProfileViewModels.QNAViewModel
@{
    string qId = String.Format("Question{0}", ViewData["Index"]);
    string aId = String.Format("Answer{0}", ViewData["Index"]);
}<div class="form-group"><label asp-for="Question" for="@qId" class="col-md-2 control-label"></label><div class="col-md-5"><select asp-for="Question" id="@qId" name="@qId" class="form-control" asp-type="securityquestion"></select><span asp-validation-for="Question" data-valmsg-for="@qId" class="text-danger"></span></div></div><div class="form-group"><label asp-for="Answer" for="@aId" class="col-md-2 control-label"></label><div class="col-md-5"><input asp-for="Answer" id="@aId" name="@aId" class="form-control" /><span asp-validation-for="Answer" data-valmsg-for="@aId" class="text-danger"></span></div></div>

Model Attributes Not Working

$
0
0

I have a view model that looks like the following:

LandingViewModel.cs

public class LandingViewModel : IValidatableObject
{
	[Required(ErrorMessage = "Required")]
	[Display(Name = "State")]
	public string RatingState;

	IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
	{
		// just testing to see if POST will validate
		yield return new ValidationResult("Required", new[] { "RatingState" });
	}
}

I have a view that looks like the following:

Landing.cshtml

@model Project.Features.Landing.LandingViewModel<!-- removed code --><label asp-for="RatingState" class="description-label col-sm-2"></label>

I have the following in my controller:

LandingController.cs

[HttpGet]
[Route("/landing")]
public IActionResult Landing()
{
	var viewModel = new LandingViewModel();
	return View(viewModel);
}


When my Landing view renders I'm not seeing the 'State' label...I see 'RatingState'. Also, if I POST, the [Required] attribute isn't setting the ModelState to invalid. However, my IValidatableObject does work and will validate the view correctly.

Why aren't my attributes working? What am I missing?

RenderPartial / ViewDataDictionary

$
0
0

I am re-writing a website in VS 2017 that was originally written in VS 2010.
The command I used originally to display my visitor count in the footer was:-

@Html.RenderPartial( "/Counter/Counter.ascx", new ViewDataDictionary {{ "digits", 6 }, { "id", "Count" }}). 

This displayed the number in Count.txt as 6 digits using digits.gif as the pattern.
When I try and use the same code in VS 2017, I get the following error message: 

'ViewDataDictionary' does not contain a constructor that takes 0 arguments.

I have spent a lot of time looking at similar questions in this forum and on other sites and have been unable to find an answer.
Any help you can give me will be most appreciated.

ArgumentException: The 'ClientId' option must be provided

$
0
0

Attempting to do 3rd party authentication using Facebook.  This used to work under .Net Core 1.0, but I just upgraded to VS2017 and .Net Core 1.1.

Complete error is:

ArgumentException: The 'ClientId' option must be provided.

Microsoft.AspNetCore.Authentication.OAuth.OAuthMiddleware..ctor(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<TOptions> options)

ArgumentException: The 'ClientId' option must be provided.

Microsoft.AspNetCore.Authentication.OAuth.OAuthMiddleware..ctor(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<TOptions> options)

Microsoft.AspNetCore.Authentication.Facebook.FacebookMiddleware..ctor(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<FacebookOptions> options)

Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider)

Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)

Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass3_0.<UseMiddleware>b__0(RequestDelegate next)

Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()

Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

I noted that .AddUserSecrets() deprecated so I updated to .AddUserSecrets<Startup>();

.csproj is as follows:

<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>netcoreapp1.1</TargetFramework><PreserveCompilationContext>true</PreserveCompilationContext><AssemblyName>SP_Reports</AssemblyName><OutputType>Exe</OutputType><PackageId>SP_Reports</PackageId><UserSecretsId>aspnet-SP_Reports-fe51af8e-b15e-40b8-a748-9260b3185259</UserSecretsId><PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback><RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion></PropertyGroup><ItemGroup><None Update="wwwroot\**\*;Views\**\*;Areas\**\Views"><CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory></None></ItemGroup><ItemGroup><ProjectReference Include="..\SP_Common_Classes\SP_Common_Classes.csproj" /></ItemGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /><PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" /><PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" /><PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" /></ItemGroup><Target Name="PrepublishScript" BeforeTargets="PrepareForPublish"><Exec Command="bower install" /><Exec Command="dotnet bundle" /></Target><ItemGroup><DotNetCliToolReference Include="BundlerMinifier.Core" Version="2.2.301" /><DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" /></ItemGroup></Project>

Any suggestions??


Cookie Middleware without Core Identity

$
0
0

I'm following the directions in this article:  https://docs.asp.net/en/latest/security/authentication/cookie.html

I
get "No authentication handler is configured to handle the scheme MyCookieMiddlewareInstance.


Startup.cs :


   app.UseCookieAuthentication( new CookieAuthenticationOptions( )
   {
    AuthenticationScheme = "MyCookieMiddlewareInstance",
    LoginPath = new PathString( "/Account/Signin/" ),
    AccessDeniedPath = new PathString( "/Account/Forbidden/" ),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
   } );

.

AccountController.cs :

   var identity = new ClaimsIdentity( claims );

   var claimsPrincipal = new ClaimsPrincipal( identity );

   var authenticationProperties = new AuthenticationProperties( )
   {
    IsPersistent = true
   };

   await _httpContext.Authentication.SignInAsync( "MyCookieMiddlewareInstance", claimsPrincipal, authenticationProperties );


Any ideas?

 

Hangfire Implementation with MVC Asp.net core

$
0
0

Hi,

I have a requirement that implementing the hangfire dashboard inside my application itself.I have a link "Dashboard" in my home page clicking on that Hangfire dashboard should open as the part of my application.

The below code i tried

On click of Dashboard link

public void BuildNavigation(string name, NavigationBuilder builder)
        {
            if (!String.Equals(name, "menu", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            builder
                   .Add(T["Dashboard"], "1", installed => installed.Action("Index", "HangfireDashboard", "Modules.HangfireDashboard"));
        }


Startup.cs

publicclassStartup:StartupBase{publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory,IServiceProvider serviceProvider){

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

        app.UseHangfireServer(options:newBackgroundJobServerOptions(){Activator=newJobActivator()});
        app.UseHangfireDashboard("/TestPage");}publicoverridevoidConfigureServices(IServiceCollection services){
        services.AddHangfire(configuration => configuration.UseSqlServerStorage(TenenatDbConfigurationProvider.GetDefaultConnectionString()));
        services.AddScoped<INavigationProvider,ModulesMenu>();}}

this is opening the index page of the modules not the hangfire dash board.

let me know if anybody have implemented this inside your modules

Thanks

Dev

Generic Web handler ashx in .net core

$
0
0

   Hi in mvc5 i have a NotificationHandler.ashx  handler and i make something 

if (context.Request.HttpMethod == "POST") { i get a json context and do something.... }
and the url is https://mysite/HttpHandler/NotificationHandler.ashx

h
ow do i make exactly the same in a Middleware handler in .net core ? My proble is the url in mvc5 i made ashx (it is url) in .net core how can
do that ?

    public class NotificationHandler    {        private readonly RequestDelegate _next;public NotificationHandler(RequestDelegate next)        {            _next = next;        }        public async Task Invoke(HttpContext httpContext)        {        if (httpContext.Request.Method == "POST"){   //do something.....i get json here        }                return _next(httpContext);
	}    }    // Extension method used to add the middleware to the HTTP request pipeline.    public static class NotificationHandlerExtensions    {        public static IApplicationBuilder UseNotificationHandler(this IApplicationBuilder builder)        {            return builder.UseMiddleware<NotificationHandler>();        }    }
I am confused because i need a url to send me cloud services json

VS community 2017 and Loading depandances

$
0
0

Hello,

I'm following a online pluralsight course but they are using an older version (Visual Studio 2015 update 3), and it taking about added extra dependences to the global.json or Project.json file (which is no longer around in 2017).

The new (empty "hello world" ) project also has no dependences folder.

The course is going thought adding RAZOR, STATIC FILES and MVC.

How do I do this in the lastest version of VS community 2017 ?

thanks

Consume wcf service from asp.net core Credentials not found

$
0
0

I have added a service reference with Visual studio WCF connected service.

When i try to consume i receive the exception that the credentials are not found.

I´ve been able to consume this service in asp.net mvc but to make this work i made a trick to overriding the headers in the request:

 

 public class AgendasWs2 : CatalogosAgendasWS_A
    {
        protected override System.Net.WebRequest GetWebRequest(Uri uri)
        {

            HttpWebRequest request;
            request = (HttpWebRequest)base.GetWebRequest(uri);

            if (PreAuthenticate)
            {
                NetworkCredential networkCredentials = Credentials.GetCredential(uri, "Basic");
                if (networkCredentials != null)
                {

                    byte[] credentialBuffer = new UTF8Encoding().GetBytes(networkCredentials.UserName + ":" + networkCredentials.Password);

                    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
                }
                else
                {
                    throw new ApplicationException("No network credentials");
                }
            }
            return request;
        }
    }

As you can see i override the headers before sendind the request.

The service has a Preemptive authentication type

I dont have any idea of making this in asp.net core.

Any help :)

Viewing all 9386 articles
Browse latest View live


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