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

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

$
0
0

Hi,

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


when to create a method for a service?

$
0
0

Let's say I have a service called BookService, and I have method called GetAllBooks, GetBookById, and so on. Now I want to get all books that are recently modified, so do I need another method? or should I useGetAllBooks().Where(....)?

And in the code below, is there a difference between GetBooksByAuthorA and GetBooksByAuthorB?

public List<Book> GetAllBooks()
{
   return _context.Books.ToList();
}

public List<Book> GetBooksByAuthorA(string author)
{
   return _context.Books.Where(a => a.Author == author);
}

public List<Book> GetBooksByAuthorB(string author)
{
   return GetAllBooks().Where(a => a.Author == author);
}

PS: The code above is not tested and I only write it as an example of what point I'm trying to tell.

Identity: Creating password change token from a netstandard 1.6 console app doesn't work for the user in the netcore asp.net webapi app

$
0
0

I have a large netcore WebAPI application with multiple databases, each serving a different client. Data is shared via a queue that is handled by a netstandard 1.6 console app. Here's the relevant identity setup code in startup.cs (for the WebAPI app)

Services.AddEntityFramework()
                .AddEntityFrameworkNpgsql()
                .AddDbContext<Repository.IdentityDbContext>();

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Cookies.ApplicationCookie.AutomaticChallenge = false;
                options.Cookies.ApplicationCookie.AutomaticAuthenticate = false;

                // Password settings
                options.Password.RequireDigit = Convert.ToBoolean(Configuration.GetSection("PasswordStrengthSettings")["RequireDigit"]);
                options.Password.RequiredLength = Convert.ToInt32(Configuration.GetSection("PasswordStrengthSettings")["MinimumPasswordLength"]);
                options.Password.RequireNonAlphanumeric = Convert.ToBoolean(Configuration.GetSection("PasswordStrengthSettings")["RequireNonAlphanumeric"]);
                options.Password.RequireUppercase = Convert.ToBoolean(Configuration.GetSection("PasswordStrengthSettings")["RequireUppercase"]);
                options.Password.RequireLowercase = Convert.ToBoolean(Configuration.GetSection("PasswordStrengthSettings")["RequireLowercase"]);
                options.Tokens.ProviderMap.Add("Default", new TokenProviderDescriptor(typeof(IUserTwoFactorTokenProvider<ApplicationUser>)));

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(Configuration.GetSection("SecuritySettings")["LockoutDurationInMinutes"]));
                options.Lockout.MaxFailedAccessAttempts = Convert.ToInt32(Configuration.GetSection("SecuritySettings")["NumberOfAttemptsUntilLockout"]);

                // User settings
                options.User.RequireUniqueEmail = true;
            }).AddDefaultTokenProviders().AddEntityFrameworkStores<Repository.IdentityDbContext>();

            services.Configure<DataProtectionTokenProviderOptions>(o =>
            {
                o.Name = "Default";
                o.TokenLifespan = TimeSpan.FromMinutes(Convert.ToDouble(Configuration.GetSection("SecuritySettings")["PasswordChangeTokenExpirationInMinutes"]));
            });

Here's the (identical) code in my DI setup in my console app:

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Cookies.ApplicationCookie.AutomaticChallenge = false;
                options.Cookies.ApplicationCookie.AutomaticAuthenticate = false;

                // Password settings
                options.Password.RequireDigit = Convert.ToBoolean(configuration.GetSection("PasswordStrengthSettings")["RequireDigit"]);
                options.Password.RequiredLength = Convert.ToInt32(configuration.GetSection("PasswordStrengthSettings")["MinimumPasswordLength"]);
                options.Password.RequireNonAlphanumeric = Convert.ToBoolean(configuration.GetSection("PasswordStrengthSettings")["RequireNonAlphanumeric"]);
                options.Password.RequireUppercase = Convert.ToBoolean(configuration.GetSection("PasswordStrengthSettings")["RequireUppercase"]);
                options.Password.RequireLowercase = Convert.ToBoolean(configuration.GetSection("PasswordStrengthSettings")["RequireLowercase"]);
                options.Tokens.ProviderMap.Add("Default", new TokenProviderDescriptor(typeof(IUserTwoFactorTokenProvider<ApplicationUser>)));

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(configuration.GetSection("SecuritySettings")["LockoutDurationInMinutes"]));
                options.Lockout.MaxFailedAccessAttempts = Convert.ToInt32(configuration.GetSection("SecuritySettings")["NumberOfAttemptsUntilLockout"]);

                // User settings
                options.User.RequireUniqueEmail = true;
            }).AddDefaultTokenProviders().AddEntityFrameworkStores<Repository.IdentityDbContext>();

            services.Configure<DataProtectionTokenProviderOptions>(o =>
            {
                o.Name = "Default";
                o.TokenLifespan = TimeSpan.FromMinutes(Convert.ToDouble(configuration.GetSection("SecuritySettings")["PasswordChangeTokenExpirationInMinutes"]));
            });

When the console app generates a password change token, it is rejected as "invalid" by Identity in the API endpoint to change password. If I create a password change token for the same user via the WebAPI, it works fine for the same endpoint. Thoughts? Any help would be most appreciated, as I'm sure I'm missing something!

Edit: I have ensured that the PasswordChangeTokenExpiration setting is identical in both json config files and is being picked up by both apps. Also, here's the code that generates a token and sends an email: both apps call the same function (it's in its own DLL):

private async Task SendNewUserEmail()
        {
            if (!_serviceResult.HasAnyError)
            {
                var token = await _userManager.GeneratePasswordResetTokenAsync(_userModel);
                if (token != null)
                {
                    var template = _emailTemplates.GetEmailTemplate("new-user");
                    var emailBody = template.Body
                        .Replace("~~~BaseUrl~~~", _emailSettings.FrontEndBaseUrl.Replace("~~~Subdomain~~~", _currentUserTools.GetCurrentDestination()))
                        .Replace("~~~Token~~~", HtmlEncoder.Default.Encode(token))
                        .Replace("~~~FirstName~~~", HtmlEncoder.Default.Encode(_userModel.FirstName ?? ""))
                        .Replace("~~~LastName~~~", HtmlEncoder.Default.Encode(_userModel.LastName ?? ""))
                        .Replace("~~~Type~~~", HtmlEncoder.Default.Encode("NEW_USER"))
                        .Replace("~~~Email~~~", HtmlEncoder.Default.Encode(_userModel.Email));

                    await _emailSender.SendEmail(
                        new EmailTools.Models.MailParticipant(_emailSettings.DefaultFromEmailName, _emailSettings.DefaultFromEmailAddress),
                        new EmailTools.Models.MailParticipant("", _userModel.Email),
                        template.Subject,
                        emailBody);
                }

                _serviceResult.Data = UserDto.GetDto(_userModel);
            }
        }


kestrel-hellomvc.service: Failed at step USER spawning /usr/bin/dotnet: No such process

$
0
0

I was following the tutorial https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction on publish asp.net core project on nginx

the previous steps all seem successfully,

but while 

systemctl start kestrel-hellomvc.service
    systemctl status kestrel-hellomvc.service

I got

● kestrel-hellomvc.service - Example .NET Web API Application running on Ubuntu
   Loaded: loaded (/etc/systemd/system/kestrel-hellomvc.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2017-04-24 03:12:42 UTC; 8s ago
  Process: 4285 ExecStart=/usr/bin/dotnet /home/84999/Demo4/Demo4.dll (code=exited, status=217/USER)
 Main PID: 4285 (code=exited, status=217/USER)

Apr 24 03:12:42 instance-5 systemd[1]: Started Example .NET Web API Application running on Ubuntu.
Apr 24 03:12:42 instance-5 systemd[4285]: kestrel-hellomvc.service: Failed at step USER spawning /usr/bin/dotnet: No such process
Apr 24 03:12:42 instance-5 systemd[1]: kestrel-hellomvc.service: Main process exited, code=exited, status=217/USER
Apr 24 03:12:42 instance-5 systemd[1]: kestrel-hellomvc.service: Unit entered failed state.
Apr 24 03:12:42 instance-5 systemd[1]: kestrel-hellomvc.service: Failed with result 'exit-code'.
  • <div class="comment-right-col"> <div>

    does anybody know the solution, seem I dont have the /usr/bin/dotnet folder

    </div> </div>

Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: DI Error

$
0
0

After I created a base servise class I got this exception on the index.cshtml

System.Exception: Call to Node module failed with error: Error: Uncaught (in promise): Error: DI Error Error: DI Error at NoProviderError.ZoneAwareError (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74842:33) at NoProviderError.BaseError [as constructor] (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:1312:20) at NoProviderError.AbstractProviderError [as constructor] (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:1438:20) at new NoProviderError (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:1478:20) at ReflectiveInjector_._throwOrNull (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:3010:23) at ReflectiveInjector_._getByKeyDefault (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:3049:29) at ReflectiveInjector_._getByKey (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:2981:29) at ReflectiveInjector_.get (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:2850:25) at AppModuleInjector.NgModuleInjector.get (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:8564:56) at CompiledTemplate.proxyViewClass.AppView.injectorGet (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:12008:49) at ElementInjector.get (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:11863:31) at ReflectiveInjector_._getByKeyDefault (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:3046:28) at ReflectiveInjector_._getByKey (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:2981:29) at ReflectiveInjector_.get (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:2850:25) at CompiledTemplate.proxyViewClass.AppView.injectorGet (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:12008:49) at resolvePromise (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74515:31) [angular] at resolvePromise (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74486:17) [angular] at C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74563:17 [angular] at Object.onInvokeTask (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:4044:41) [angular] at ZoneDelegate.module.exports.ZoneDelegate.invokeTask (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74216:36) [angular] at Zone.module.exports.Zone.runTask (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74016:47) [ => angular] at drainMicroTaskQueue (C:\Projetos\Despesas\Desenv\20170313_Inicio\Fontes\Despesas\WA\ClientApp\dist\vendor.js:74396:35) [] at runMicrotasksCallback (internal/process/next_tick.js:58:5) [] at _combinedTickCallback (internal/process/next_tick.js:67:7) [] at process._tickCallback (internal/process/next_tick.js:98:9) []

at Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance.d__7`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance.d__14`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.d__10`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.d__10`1.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.SpaServices.Prerendering.PrerenderTagHelper.d__33.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.d__0.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

at AspNetCore._Views_Home_Index_cshtml.d__31.MoveNext() in /Views/Home/Index.cshtml:line 2

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Razor.RazorView.d__14.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Razor.RazorView.d__13.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.d__18.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.ViewResult.d__26.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__30.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__28.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__22.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.d__5.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__7.MoveNext()

My code:

BaseService:

export class BaseService {
    private configApi = {
        host: "http://localhost:5000"
    };
    http: Http;
    mensagemService: MensagemService;

    constructor(_http: Http, _mensagenService: MensagemService) {
        this.http = _http;
        this.mensagemService = _mensagenService;
    }

    private obterOpcaoesRequest(sendToken: boolean): RequestOptions {
        let header = new Headers();

        header.append('Content-Type', 'application/json');

        if (sendToken) {
            header.append('Authorization', 'Bearer ' + "[TOKEN]");
        }

        let options = new RequestOptions({ headers: header });

        return options;
    }

    post<T>(url: string, data: any, callback: (retorno: T) => void, sendToken: boolean = true) {

        let dataJson = JSON.stringify(data);
        let options = this.obterOpcaoesRequest(sendToken);

        try {

            this.http.post(this.configApi.host + url, dataJson, options)
                .map(r => r.json())
                .subscribe(res => {
                    var result = res as ResultadoValidacao;

                    if (result.success) {
                        callback(result.objectReturn as T);
                    } else {
                        this.mensagemService.ShowInfos(result.infos);
                    }
                });

        } catch (e) {
            console.log(e);
        }
    }

}

UsuarioService:

@Injectable()
export class UsuarioService extends BaseService {

    constructor(_http: Http, _mensagemService: MensagemService) {
        super(_http, _mensagemService);
    }

    public criarUsuario(usuario: NovoUsuario, callback: (usuario: NovoUsuario) => void) {

        super.post<NovoUsuario>("/api/usuarios/criar", usuario, (user: NovoUsuario) => {
            callback(user);
        }, false);

    }
}

When I comment the constructor in the UsuarioService, the exception doesn't occurs. But the injectable parameters in the parameters constructor base class are not setted.

Host .net core web api on iis

$
0
0

Hello everybody,

i try to publish .net core web api on iis , create iis web webapp under defaultwebsite, applicatio pool with no managed code, but i have 404 error.
after i  manually added wwwroot on deploy folder and put inside example.gif , and from browser go to localhost/mywebapi/example.gif works ok.

After that, i create  another .net core webapp (webapp this time not web api)  then deploy and create another iis webapp with the same applicationpoll used before.  

This works perfectly

Why web app project work's and web api don't ?

How to read session in static method in ASP.Net Core

$
0
0

I wanna read session value in ASP.Net Core. If anyone have idea or suggestion please help.

Thanks.

ASP.NET Core EntityFramework

$
0
0

Hi,

    I have a tutorial example that uses EF to create two databases.

I have been deploying to a remote server for testing in the real world.

My hosting provider only allows me one Database. So I would like to put all the tables in the one database.

One of the database was for the built in Identity - security setup and the other for a blog.

If I can get it working locally first.

From the config.developement.json below

"BlogDataContext": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DB_******_*******;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;",
    "IdentityDataContext": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DB_DB_******_*******;;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"

The above does not seem to work as only the Identity tables are added to the Database.

Not sure what is the way to go about this?

Thanks,


project.json dependencies and tools

$
0
0

why does some tools are in the dependencies section, and what is the meaning of "type": "build". And why there are duplicate package in dependencies and tools?

here is the default project.json in asp.net core mvc 1.0 with individual authentication

"dependencies": {"Microsoft.NETCore.App": {"version": "1.0.1","type": "platform"
    },"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0","Microsoft.AspNetCore.Diagnostics": "1.0.0","Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0","Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0","Microsoft.AspNetCore.Mvc": "1.0.1","Microsoft.AspNetCore.Razor.Tools": {"version": "1.0.0-preview2-final","type": "build"
    },"Microsoft.AspNetCore.Routing": "1.0.1","Microsoft.AspNetCore.Server.IISIntegration": "1.0.0","Microsoft.AspNetCore.Server.Kestrel": "1.0.1","Microsoft.AspNetCore.StaticFiles": "1.0.0","Microsoft.EntityFrameworkCore.SqlServer": "1.0.1","Microsoft.EntityFrameworkCore.SqlServer.Design": {"version": "1.0.1","type": "build"
    },"Microsoft.EntityFrameworkCore.Tools": {"version": "1.0.0-preview2-final","type": "build"
    },"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0","Microsoft.Extensions.Configuration.Json": "1.0.0","Microsoft.Extensions.Configuration.UserSecrets": "1.0.0","Microsoft.Extensions.Logging": "1.0.0","Microsoft.Extensions.Logging.Console": "1.0.0","Microsoft.Extensions.Logging.Debug": "1.0.0","Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0","Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0","Microsoft.VisualStudio.Web.CodeGeneration.Tools": {"version": "1.0.0-preview2-final","type": "build"
    },"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {"version": "1.0.0-preview2-final","type": "build"
    }
  },"tools": {"BundlerMinifier.Core": "2.0.238","Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final","Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final","Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final","Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final","Microsoft.VisualStudio.Web.CodeGeneration.Tools": {"version": "1.0.0-preview2-final","imports": ["portable-net45+win8"
      ]
    }
  }

ASP.NET Core Identity - Not able to use Role

$
0
0

I am currently adding Roles to our Database using the RoleManager with the CreateAsync(newRoleName) Method - which works correctly.  But when I try to query that Role, it always returns that it doesn't exist (even though I can see it in the database).

Can anyone provide some insight on why I am not able to use the Role?  

            var roleExists = roleManager.RoleExistsAsync(role);
            if (!roleExists.Result)
            {
                var newRole = new IdentityRole(role)
                {
                    Name = role,
                    NormalizedName = role.ToUpper(),
                };

                var roleCreated = roleManager.CreateAsync(newRole);

                Thread.Sleep(500);  // Used to get result back first.

                var roleExistsYet = roleManager.RoleExistsAsync(role);
                if (!roleExists.Result)
                {
                    // ALWAYS Returns [False]
                }
            }

The initial problem came about when we were creating a new User with the UserManager, and the following method would result in an error 

var roleAddResult = userManager.AddToRoleAsync(newUser, "TestRole123");

Exception Error:  Role [TESTROLE123] does not exist.

Note:  I can see the entry for the Role 'TestRole123' (or any other role) in the Database in the table dbo.AspNetRoles.

Any insight or help is appreciated.

View Model with Base class and Model binding is with post method is failed to populate base class properties.

$
0
0

In Asp.net core When i use base class for view model and when i use that in post method ,Model binder is unable to populate base class properties in model. 

public class AppDTO

{

public string Name{get;set;}

public string Email {get;set;}

}

public class AppViewModel:AppDTO

{

public string Address {get;set;}

}

And in Action method

public JsonResult PostApp(AppViewModel model)

{

// here when i try to access model values only address property is populated and name and email are null.

}

}

Any Recommentations ?

How to return Unauthorized result in OnActionExecuting method

$
0
0
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   var authenticateKey = filterContext.HttpContext.Request.Headers["AuthenticateKey"];
   if (String.IsNullOrEmpty(authenticateKey))
   {
       base.OnActionExecuting(filterContext);
   }
   else
   {
       filterContext.Result = new JsonResult(new { HttpStatusCode.Unauthorized });
//Instead of jsonresult, here I want to return response Unauthorized to browser } }

How do I add a .NET Core 1.1 Class Library dll to ASP.Net core 1.1 project

$
0
0

Both project are on .NET core 1.1.

The dll is added to the project in Dependencies -> Assemblies. When I publish the asp.net core web site, I can see the dll in the root folder. The web application runs fine until my code calls the dll, which gives me:

FileNotFoundException: Could not load file or assembly 'Test.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Is there a config/json file that I need to update the reference?

How can I make this work?

Thanks,
Patrick

Adding a reference to .net class library from ASP.net core web application

$
0
0

I have added a reference to a class library project in the same project as my asp.net core web application. It shows up under Dependencies/Projects

However when I try to refer to any namespace/class inside this referenced project from a asp.net core controller action it just says "the type or namespace name XXX could not be found..."

The refernced DLL/project is full .net framework, not core.

[MVC Core] BaseControoler: Header + Footer

$
0
0

Hello guys,

Thank you for your help, I am starting to learn ASP.NET Core. :)

I started my web application without ASP.NET Core, but right now I prefer to upgrade to Visual Studio 2017 + Core.

I am facing one single problem: All my pages should inherit my header and footer views. And both of them have Models, and their Models aren't just text (for example, in the header I need to show notifications to the user).

In the current project - working like a charm - I have this BaseController:

 public class BaseController : Controller
  {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var model = filterContext.Controller.ViewData.Model as BaseViewModel;

            if (model != null)
            {
                model.HeaderModel = this.getHeaderModel();
                model.FooterModel = this.getFooterModel();
            }
        }

        protected HeaderModel getHeaderModel()
        {
            HeaderModel model = new HeaderModel()
            {
                //...
            };
            return model;
        }

        protected FooterModel getFooterModel()
        {
            FooterModel model = new FooterModel()
            {
                //...
            };
            return model;
        }
}

My BaseViewModel:

    public class BaseViewModel
    {
        public HeaderModel HeaderModel { get; set; }
        public FooterModel FooterModel { get; set; }
    }

My Controllers inherit BaseController and return some View(model) [model inherit BaseViewModel].

With that in mind, I can populate my header and footer views.

@model Dashboard.Models.Dashboard.BaseViewModel<!DOCTYPE html><html lang="en"><head>
....</head><body class="nav-md"><div class="container body"><div class="main_container">
            @{ Html.RenderPartial("_Header", Model.HeaderModel); }
            @RenderBody()
            @{ Html.RenderPartial("_Footer", Model.FooterModel); }</div></div></body></html>

In ASP.NET Core I can not use:

            var model = filterContext.Controller.ViewData.Model as BaseViewModel;

What are your advice? Do you have any example I can follow?

Best regards,
Nelson.

EDIT: I am interested in following the best practises.


Does Angular2 can directly access the images under app folder ?

$
0
0
<div class="vote">
0
down votefavorite<div class="favoritecount"></div> </div>
<div> <div class="post-text" itemprop="text">

I am using a jquery theme in my ASP.NET MVC core Application (angularjs2). Some sections are properly working but some of the plugins are not working.

Like own-carousel is not getting the images and displaying anything.

I have placed the images folder under angular app folder as well under root project directory but it couldn't work in any case.

i am placing some code sample here:

please see and suggest.

index.component.html

<div id="hero"><div id="owl-main" class="owl-carousel owl-inner-nav owl-ui-sm"><div class="item" style="background-image:  url('app/assets/images/sliders/slider01.jpg');"><div class="container-fluid"><div class="caption vertical-center text-left"><div class="big-text fadeInDown-1">
            Save up to a<span class="big"><span class="sign">$</span>400</span></div><div class="excerpt fadeInDown-2">
            on selected laptops<br> & desktop pcs or<br> smartphones</div><div class="small fadeInDown-2">
            terms and conditions apply</div><div class="button-holder fadeInDown-3"><a href="single-product.html" class="big le-button ">shop now</a></div></div><!-- /.caption --></div><!-- /.container-fluid --></div><!-- /.item --><div class="item" style="background-image: url('../assets/images/sliders/slider01.jpg');"><div class="container-fluid"><div class="caption vertical-center text-left"><div class="big-text fadeInDown-1">
            Want a<span class="big"><span class="sign">$</span>200</span>Discount?</div><div class="excerpt fadeInDown-2">
            on selected <br>desktop pcs<br></div><div class="small fadeInDown-2">
            terms and conditions apply</div><div class="button-holder fadeInDown-3"><a href="single-product.html" class="big le-button ">shop now</a></div></div><!-- /.caption --></div><!-- /.container-fluid --></div><!-- /.item --></div><!-- /.owl-carousel --></div>

Images folder is currently available under app folder in assets folder.

and this is parent/master layout which have that plugins

<!DOCTYPE html><html><headlang="en"><basehref="/"><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1"><linkhref="node_modules/bootstrap/dist/css/bootstrap.css"rel="stylesheet"/><linkhref="app/app.component.css"rel="stylesheet"/><linkhref="node_modules/assets/css/style.css"rel="stylesheet"/><linkrel="stylesheet"href="node_modules/assets/css/style.css"><linkrel="stylesheet"href="node_modules/assets/css/colors/green.css"><linkrel="stylesheet"href="node_modules/assets/css/owl.carousel.css"><linkrel="stylesheet"href="node_modules/assets/css/owl.transitions.css"><linkrel="stylesheet"href="node_modules/assets/css/animate.min.css"><!-- Fonts --><linkhref='//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800'rel='stylesheet'type='text/css'><!-- Icons/Glyphs --><linkrel="stylesheet"href="node_modules/Cartjs/assets/css/font-awesome.min.css"><!-- Favicon --><linkrel="shortcut icon"href="node_modules/Cartjs/assets/images/favicon.ico"><!-- Polyfill(s) for older browsers --><scriptsrc="node_modules/client/shim.min.js"></script><scriptsrc="node_modules/zone.js/dist/zone.js"></script><scriptsrc="node_modules/reflect-metadata/Reflect.js"></script><scriptsrc="node_modules/systemjs/dist/system.src.js"></script><!-- Configure SystemJS --><scriptsrc="systemjs.config.js"></script><scriptsrc="node_modules/assets/js/jquery.js"></script><scriptsrc="node_modules/assets/js/jquery-migrate-1.2.1.js"></script><scriptsrc="node_modules/bootstrap/dist/js/bootstrap.min.js"></script><scriptsrc="//maps.google.com/maps/api/js?key=AIzaSyDDZJO4F0d17RnFoi1F2qtw4wn6Wcaqxao&sensor=false&amp;language=en"></script><scriptsrc="node_modules/assets/js/gmap3.min.js"></script><scriptsrc="node_modules/assets/js/bootstrap-hover-dropdown.min.js"></script><scriptsrc="node_modules/assets/js/owl.carousel.min.js"></script><scriptsrc="node_modules/assets/js/css_browser_selector.min.js"></script><scriptsrc="node_modules/assets/js/echo.min.js"></script><scriptsrc="node_modules/assets/js/jquery.easing-1.3.min.js"></script><scriptsrc="node_modules/assets/js/bootstrap-slider.min.js"></script><scriptsrc="node_modules/assets/js/jquery.raty.min.js"></script><scriptsrc="node_modules/assets/js/jquery.prettyPhoto.min.js"></script><scriptsrc="node_modules/assets/js/jquery.customSelect.min.js"></script><scriptsrc="node_modules/assets/js/wow.min.js"></script><scriptsrc="node_modules/assets/js/buttons.js"></script><scriptsrc="node_modules/assets/js/scripts.js"></script><!-- End Customizable plugins For Sale Cart Portal  --><script>System.import('app').catch(function(err){ console.error(err);});</script></head><body><pm-app>Loading App...</pm-app></body></html>

systemjs.config.js

(function(global){System.config({
    paths:{// paths serve as alias'npm:':'node_modules/'},// map tells the System loader where to look for things
    map:{// our app is within the app folder
      app:'app',// angular bundles'@angular/core':'npm:@angular/core/bundles/core.umd.js','@angular/common':'npm:@angular/common/bundles/common.umd.js','@angular/compiler':'npm:@angular/compiler/bundles/compiler.umd.js','@angular/platform-browser':'npm:@angular/platform-browser/bundles/platform-browser.umd.js','@angular/platform-browser-dynamic':'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js','@angular/http':'npm:@angular/http/bundles/http.umd.js','@angular/router':'npm:@angular/router/bundles/router.umd.js','@angular/forms':'npm:@angular/forms/bundles/forms.umd.js',// other libraries'rxjs':'npm:rxjs','angular-in-memory-web-api':'npm:angular-in-memory-web-api',},// packages tells the System loader how to load when no filename and/or no extension
    packages:{
      app:{
        main:'./main.js',
        defaultExtension:'js'},
      rxjs:{
        defaultExtension:'js'},'angular-in-memory-web-api':{
        main:'./index.js',
        defaultExtension:'js'}}});})(this);
</div></div>

Entit Framework Core

$
0
0

Hi,

    how do I create an Edit for below.

All the examples I have found don't seem to work?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ExploreCalifornia.Models;
using Microsoft.AspNetCore.Authorization;

namespace ExploreCalifornia.Controllers
{
    [Route("blog")]
    public class BlogController : Controller
    {
        private readonly BlogDataContext _db;

        public BlogController(BlogDataContext db)
        {
            _db = db;
        }

        [Route("")]
        public IActionResult Index(int page = 0)
        {
            var pageSize = 2;
            var totalPosts = _db.Posts.Count();
            var totalPages = totalPosts / pageSize;
            var previousPage = page - 1;
            var nextPage = page + 1;

            ViewBag.PreviousPage = previousPage;
            ViewBag.HasPreviousPage = previousPage >= 0;
            ViewBag.NextPage = nextPage;
            ViewBag.HasNextPage = nextPage < totalPages;

            var posts =
                _db.Posts
                    .OrderByDescending(x => x.Posted)
                    .Skip(pageSize * page)
                    .Take(pageSize)
                    .ToArray();

            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                return PartialView(posts);

            return View(posts);
        }

        [Route("{year:min(2000)}/{month:range(1,12)}/{key}")]
        public IActionResult Post(int year, int month, string key)
        {
            var post = _db.Posts.FirstOrDefault(x => x.Key == key);
            return View(post);
        }

        [Authorize]
        [HttpGet, Route("create")]
        public IActionResult Create()
        {
            return View();
        }

        [Authorize]
        [HttpPost, Route("create")]
        public IActionResult Create(Post post)
        {
            if (!ModelState.IsValid)
                return View();

            post.Author = User.Identity.Name;
            post.Posted = DateTime.Now;

            _db.Posts.Add(post);
            _db.SaveChanges();

            return RedirectToAction("Post", "Blog", new
            {
                year = post.Posted.Year,
                month = post.Posted.Month,
                key = post.Key
            });
        }
    }
}

Thanks,

Trying to port WebApi (ApiController based) code to .Net Core

$
0
0

It seemed like the answer to all my problems was Microsoft.AspNet.Mvc.WebApiCompatShimbut when I try to install it it says  Webapi.Client 5.2.2 is not compatible with net core app1.1.

I am having so many problems trying to get around this.. any tips?

Just using [Controller] there are so many ApiController pieces of functionality missing that it seems impossible to build a webapi project!!

ASP.NET Core How to bind data from body

$
0
0

I am really disappointed about all new staff of ASP.NET Core, the reason I cant bind data from request body to my Model (the most ordinary thing).  I have checked all my configuration, I have updated all my dependencies and run-time. Unfortunately still stacked with model binding.

This is my api method

[HttpPost("attach")]
[AllowAnonymous]
public async Task<IActionResult> AttachToBuilding([FromBody]AttachmentDto dto)

After sending request, dto always null

This is my model

public class AttachmentDto
{
    public string Identity { get; set; }
    public Guid BuildingId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Phone { get; set; }
    [Required]
    public string UniqueDeviceId { get; set; }
    [Required]
    public int ApartmentNumber { get; set; }
    [Required]
    public int AgreementNumber { get; set; }
    [Required]
    public int FloorNumber { get; set; }
}

My Startup.cs ConfigurationServices method

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddOptions();

        services.AddCors(options =>
        {
            options.AddPolicy("AllowAnyOrigin",
                    builder =>
                    {
                        builder.AllowAnyOrigin();
                        builder.AllowAnyMethod();
                        builder.AllowAnyHeader();
                    });
        });

        services.AddDbContext<KskEfContext>(options => options.UseSqlServer(Configuration.GetConnectionString(ConnectionName)));

        services.AddSingleton<IConfiguration>(Configuration);

        AddDependencies(services);

        services.AddMvcCore()
            .AddFormatterMappings()
            //for aspe.net core  need to add explicitly the Api Explorer service (swagger)
            .AddApiExplorer()
            .AddDataAnnotations()
        .AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver());


        services.AddAutoMapper();

        //Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "KSK api", Version = "v1" });
            c.IncludeXmlComments(GetXmlCommentsPath());
        });
    }

I find my configuration correct and I designed my api method like in previeos ASP.NET WebApi nothing extraordinary. It might be problem with framework version.

My dependencies from project.json (after I updated my dependencies)

{"dependencies": {"Ksk.DataAccess": "1.0.0-*","Ksk.Domain": "1.0.0-*","Microsoft.AspNetCore.Cors": "1.1.1","Microsoft.NETCore.App": {"version": "1.1.1","type": "platform"
    },"AutoMapper": "6.0.2","AutoMapper.Extensions.Microsoft.DependencyInjection": "2.0.1","Microsoft.ApplicationInsights.AspNetCore": "2.0.0","Microsoft.AspNetCore.Authentication.JwtBearer": "1.1.1","Microsoft.AspNetCore.Mvc": "1.1.2","Microsoft.AspNetCore.Routing": "1.1.1","Microsoft.AspNetCore.Server.IISIntegration": "1.1.1","Microsoft.AspNetCore.Server.Kestrel": "1.1.1","Microsoft.AspNetCore.StaticFiles": "1.1.1","Microsoft.EntityFrameworkCore.Design": "1.1.1","Microsoft.EntityFrameworkCore.SqlServer": "1.1.1","Microsoft.EntityFrameworkCore.Tools": "1.1.0","Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.1","Microsoft.Extensions.Configuration.FileExtensions": "1.1.1","Microsoft.Extensions.Configuration.Json": "1.1.1","Microsoft.Extensions.Logging": "1.1.1","Microsoft.Extensions.Logging.Console": "1.1.1","Microsoft.Extensions.Logging.Debug": "1.1.1","Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.1","Swashbuckle.AspNetCore": "1.0.0"
  },"tools": {"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },"frameworks": {"netcoreapp1.0": {"imports": ["dotnet5.6","portable-net45+win8"
      ]
    }
  },"buildOptions": {"emitEntryPoint": true,"preserveCompilationContext": true,"xmlDoc": true
  },"runtimeOptions": {"configProperties": {"System.GC.Server": true
    }
  },"publishOptions": {"include": ["wwwroot","**/*.cshtml","appsettings.json","web.config"
    ]
  },"scripts": {"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

My request details

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Content-Length:280
Content-Type:application/json
Host:localhost:5000
Origin:http://localhost:5000
Proxy-Connection:keep-alive
Referer:http://localhost:5000/docs/index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36

Request Payload
{
  "Identity": "AST-25","BuildingId": "","FirstName": "Petr","LastName": "Petrov","MiddleName": "Petrovich","Phone": "+77012223344","UniqueDeviceId": "68753A44-4D6F-1226-9C60-0050E4C00067","ApartmentNumber": 20,"AgreementNumber": 292,"FloorNumber": 5
}

asp.net core scaffolding issue

$
0
0

I created a new project of asp.net core web application using .net framework.

Then I created a model with its attribute and also have created a key in the model.

When I am trying to scaffold using the entity framework which adds controller and view I am getting error. Please find the error attached with this question.

https://drive.google.com/file/d/0Bx-b6FLAaKCwX3Myd3Z5MUpUa0E/view?usp=sharing

My .csproj code:

<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup Label="Globals"><SccProjectName>SAK</SccProjectName><SccProvider>SAK</SccProvider><SccAuxPath>SAK</SccAuxPath><SccLocalPath>SAK</SccLocalPath></PropertyGroup><PropertyGroup><TargetFramework>net452</TargetFramework><RuntimeIdentifier>win7-x86</RuntimeIdentifier></PropertyGroup><PropertyGroup><UserSecretsId>aspnet-webapplication</UserSecretsId></PropertyGroup><ItemGroup><Content Include="wwwroot\css\animate.min.css" /><Content Include="wwwroot\lib\moment\moment.min.js" /></ItemGroup><ItemGroup><PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" /><PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" /><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /><PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" PrivateAssets="All" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" PrivateAssets="All" /><PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /><PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" PrivateAssets="All" /><PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" /></ItemGroup><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></Project>
Viewing all 9386 articles
Browse latest View live


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