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

Custom Core MVC Folder Structure or special category

$
0
0

Hi

i know some folders in Core Mvc or in MVC Asp.net ....  we have Controllers ,Model ,Views , Share ,Content , ...

 but in some pdf for Example in adam freeman PDF (Pro Asp.net Core MVC ) i saw he used   Infrastructure folder  and Concrete Folder and Abstract Folder ..

i dont know what is  " Infrastructure folder  and Concrete Folder and Abstract Folder" ? when i should use them ?  and which file or class i should put in that folders ?

and finally is there any Custom Core  MVC Folder Structure or special category that i have use in My Project , Please Explain it for Me ..

Tanks


Error TS1148 Cannot use imports, exports, or module augmentations when '--module' is 'none'. TypeScript Virtual Projects

$
0
0

Hello,

I am having trouble getting anything working with Angular 2 and ASP.NET Core. I paste below a few lines from Package.Json

The problem that I have is with my app.component.ts

ErrorTS1148Cannot use imports, exports, or module augmentations when '--module' is 'none'.TypeScript Virtual Projects

then it goes on to fail to find

import { NgModule } from '@angular/core';

app.module.ts just fails to find angular/core

"dependencies": {
"@angular/animations": "4.0.0",
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/compiler-cli": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",

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.

NonFactors Grid MVC 6 and Checkbox / Multiselect

$
0
0

I am working with a problem.  I can currently display data on a page with the NonFactors Grid MVC6, though it is incomplete data.  Currently for Boolean values it is displaying a True or False on the page.  I am having trouble trying to get it to display a checkbox.  I have tried Html.CheckboxFor and <input type="checkbox" /> with no luck.  So here is what I am working with.  I have four viewmodels for the page, and a partial view that works in conjunction with the view.  The page is only for editing, but the only editing that needs to take place is with the Boolean values and a selectlist for each row of the grid.  What I am looking for is advice with the partial view so that I can get the checkbox and selectlist to display.

Here is my viewmodels in question:

public class CharRepViewModel
    {
        public CharRepViewModel()
        {
            this.Name = new CharFullNameViewModel();
            this.Reputation = new List<CharRepListViewModel>();
        }
        public CharFullNameViewModel Name { get; set; }
        public List<CharRepListViewModel> Reputation { get; set; }
    }

public class CharFullNameViewModel
    {
        public int Char_ID { get; set; }
        public string CharFullName { get; set; }
    }

public class CharRepListViewModel
    {
        public CharRepListViewModel()
        {
            this.CharID = CharID;
            this.FactionID = FactionID;
            this.FactionName = FactionName;
            this.FactionSet = FactionSet;
            this.RepLevelID = RepLevelID;
            this.RepLevels = new List<RepLevelListViewModel>();
        }
        public int CharID { get; set; }
        public int FactionID { get; set; }
        public string FactionName { get; set; }
        public bool FactionSet { get; set; }
        public int RepLevelID { get; set; }
        public List<RepLevelListViewModel> RepLevels { get; set; }

    }

public class RepLevelListViewModel
    {
        public int FactionID { get; set; }
        public int RepLevelID { get; set; }
        public string RepLevelName { get; set; }
        public bool RepIsChecked { get; set; }
    }

The RepLevelListViewModel is what I want for the SelectList in the grid.  The FactionSet in the CharRepListViewModel is what I want for a checkbox.  This will hopefully allow the multiselect dropdown to be accessible if checked, and not accessible if uncheck.  Of which I have not figured out how to do yet either.  The CharRepViewModel brings everything together for the main view.  And yes my RepLevelID in the CharRepListViewModel is currently unused, I added it there, but have not been able to make the data use it correctly yet, but I have left it there currently while building the view in case I need it.

Here is my controller:

public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return BadRequest();
            }

            var factIdList = await _db.Database.SqlQuery<CharRepListViewModel>(sql: "GetCharacterReputations @p0", parameters: new object[] { id }).ToListAsync();
            var eReps = await _db.Database.SqlQuery<RepLevelListViewModel>(sql: "GetCharacterReputationsChecks @p0", parameters: new object[] { id }).ToListAsync();
            foreach (CharRepListViewModel cr in factIdList)
            {
                cr.RepLevels.AddRange(eReps.Where(a => a.FactionID == cr.FactionID));
            }

            var characterReputation = new CharRepViewModel()
            {
                Name = await _db.Database.SqlQuery<CharFullNameViewModel>(sql: "GetCharacterFullName @p0", parameters: new object[] { id }).FirstOrDefaultAsync(),
                Reputation = factIdList
            };


            if (characterReputation == null)
            {
                return NotFound();
            }

            return View(characterReputation);
        }

        public async Task<IActionResult> _RepEditPartial(int? id)
        {
            return PartialView();
        }

Here are my views:

Edit.cshtml:
@model WebAppMVC.Models.CharRepViewModels.CharRepViewModel

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_CharEdLayout.cshtml";
}<h2 style="text-align: center; font-family: 'Times New Roman', Times, serif">Character Database Character Reputation Edit Form</h2><form asp-controller="CharReps" asp-action="Edit" method="post"><div class="form-horizontal"><h4>Character Reputation</h4><hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })<b style="text-align: center; font-family: 'Times New Roman', Times, serif; font-size: x-large">@Html.DisplayFor(model => model.Name.CharFullName)</b><div class="form-group"><label asp-for="@Model.Reputation" class="control-label col-md-2"></label>
            @Html.Partial("_RepEditPartial", @Model.Reputation)</div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-default" /></div></div></div></form><div>
    @Html.ActionLink("Back to Edit Character", "EdChar", "Menu")</div>


_RepEditPartial.cshtml:
@model IEnumerable<WebAppMVC.Models.CharRepViewModels.CharRepListViewModel>
    @{

    }

    <div class="form-group"><div class="col-md-12">
            @(Html
            .Grid(Model)
            .Build(columns =>
            {
                columns.Add(model => model.CharID).Css("hidden");
                columns.Add(model => model.FactionID).Css("hidden");
                columns.Add(model => model.FactionName).Titled("Faction");
                columns.Add(model => model.FactionSet).Titled("Available");  //This needs to be a editable checkbox that will enable the select list to open up if checked
                columns.Add(model => model.RepLevels.Select(a => a.RepLevelID).LastOrDefault()).Css("hidden");  //This needs to be part of a multi select list
                columns.Add(model => model.RepLevels.Select(a => a.RepIsChecked).LastOrDefault());  //This needs to be part of a multi select list, this will be what checks the item
                columns.Add(model => model.RepLevels.Select(a => a.RepLevelName).LastOrDefault()).Titled("Reputation");  //This needs to be part of a multi select list

            })
            .Pageable()
            .Empty("No Data Found")
            )</div></div>

You will notice that currently I have .LastOrDefault in there for the last three entries as not having them in there would either give an error on the add, or display Linq on the view.  This was so I could test if the data was making it to the view.  Using the Html.CheckboxFor(model.FactionSet) gave an error on the checkbox for about unable to convert a bool to system.func<IEnumerable<ViewModel>,bool>', adding a new {@checked ="checked" } gave an error at the Add.  Using @<input type="checkbox" asp-for="model.FactionSet" /> gave an error at the add.  I used these both within the parenthesis after the lambda for model.

Any thoughts?

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'.

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

app.config & appsetting.json

$
0
0

In visual c# using-asp.net core web application(.net framework) 

core web using .net fw have a [app.config,appsetting.json] ,so i not sure where to write my connectionstring to make to the db connection?

.so how to use and what are the difference?

Another difference i need to know is the  web.config -app.config-appsetting.json. ?

[SOLVED] Asp Core 1.1 share cookie Auth between application

$
0
0

Hi,

I try to share 2 authentication cookies between 2 applications.

In App1 : Startup.cs

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login"),
                AccessDeniedPath = new PathString("/Home/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = "ASPTest",
                ExpireTimeSpan = new TimeSpan(1, 0, 0) //1 hour
            });

And in App2 : Startup.cs

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login"),
                AccessDeniedPath = new PathString("/Home/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = "ASPTest",
            });

In Ap1 : AccountController.cs

       [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string username, string password, string returnUrl)
        {
            if (username == password)
            {
                var claims = new List<Claim>
        {
            new Claim("Read", "true"),
            new Claim(ClaimTypes.Name, "ayayalar"),
            new Claim(ClaimTypes.Sid, "12345")
        };

                var claimsIdentity = new ClaimsIdentity(claims, "password");
                var claimsPrinciple = new ClaimsPrincipal(claimsIdentity);

                await HttpContext.Authentication.SignInAsync("Cookies", claimsPrinciple,
                    new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties { IsPersistent = true});

                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }

                return Redirect("~/");
            }

            return View();
        }

In both Ap1 and Ap2 : I check after logged in (tested without database and login == password)

        public IActionResult Index()
        {
            var t = HttpContext.User;

            return View();
        }

In Ap1 which allows to login and create cookie, the cookie is created and when going on Home/Index the t variable is feed from Cookie==> it works!
In Ap2  when going on Home/Index the t variable is not feed from Cookie ==> it fails !

In Mozilla I'm able to see the cookie created within both App1 and App2, but App2 seems not able to load it.

I tried to follow the link : https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing but with no success as 

DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"))

does not build.

Did I miss some obvious point when trying to get access the cookie created from Ap1 with Ap2 ? My goal is to create a cookie from Ap1, and get all Claims from Ap2.

Thank you for your help

Nicolas

MySQL Bulk insert .net core

$
0
0

Does anyone know how I can do bulk inserts with MySQL and .Net Core? I've been researching for a while now, and no solution. MySqlDataAdapter doesn't seem to be available yet?


DataProtectionProvider : best pratices using a shared authentication key (share cookie auth session between app)

$
0
0

Hi,

following this link https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing and having received much help on this forum (https://forums.asp.net/t/2120124.aspx?+SOLVED+Asp+Core+1+1+share+cookie+Auth+between+application), I managed  to achieve a session sharing using share cookies between two (or more) Asp Core 1.1 web application.

In Startup.cs / method Configure :

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login"),
                AccessDeniedPath = new PathString("/Home/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = "ASPTest",
                ExpireTimeSpan = new TimeSpan(1, 0, 0), //1 hour,
                DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"))

            });


Well, I have a question about using the the same folder to share the Authenticated encryption key (which allows each App to uncrypt the auth cookie and get all store information). It works with a trivial "c:\shared ...." folder, but what are good practices to store such a file ? I suppose we don't have access to C: disk directly in a production env. 

Where do you suggest to store this file, keeping in mind that the directory has to be the same (so reachable) for all app.

Many thanks for your help

Nicolas

No WriteSync method on HttpResponse

$
0
0

I'm stuck and not sure why this isn't working.  I want to write to the HttpResponse object thusly in my Configure method of Startup.cs:

app.Run(async context =>
{
      await context.Response.WriteAsyc("Return from run.");
});

but VS2017 (with latest update) says:

Error CS1061 'HttpResponse' does not contain a definition for 'WriteAsyc' and no extension method 'WriteAsyc' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?)

It seems this method was moved into an extension class called HttpResponseWritingExtensions in Microsoft.AspNetCore.Http.Abstractions.  I added a reference to this using NuGet Package Manager, but I'm still getting the error.  What am I doing wrong?

Cancel async Ajax Request (CancellationToken)

$
0
0

Hello,

How to cancel a async Ajax Request?

I have the following Controller where I querying a database async and have the need to cancel it if it runs to Long...

  • Is it possible that using CancellationToken in ASP.NET Core is not possible?
  • How to cancel such a Operation from the Client?

public async System.Threading.Tasks.Task<ActionResult> ReadAsync([FromBody] JsonDict jsonDict, [DataSourceRequest] DataSourceRequest request, CancellationToken cancelToken)
        {
            try
            {
                var queryDict = jsonDict["query"] as JsonDict;
                var optionsDict = jsonDict["options"] as JsonDict;
                var query = eqService.GetQueryByJsonDict(queryDict);
                var sql = eqService.BuildQuery(query, optionsDict);

                var result = await Db.QueryAsync<dynamic>(sql, commandType: System.Data.CommandType.Text,cancellationToken: cancelToken);

                return Json(result.ToDataSourceResult(request));
            }
            catch (Exception ex)
            {
                return Json(ex);
            }

        }

Radio Button Tag Helper sets every radio button to checked

$
0
0

Both of these radio buttons will have checked="checked" on them.  Why would the tag helper add that.  How do you specify that none of them should be checked?

<div class="form-group">
<label>
<input name="Answer" type="radio" asp-for="Answer1" value="@Model.Answer1" /> @Model.Answer1
</label>
</div>

<div class="form-group">
<label>
<input name="Answer" type="radio" asp-for="Answer2" value="@Model.Answer2" /> @Model.Answer2
</label>
</div>

basic to expert?

$
0
0

I been learning asp.net core for a while now and I already made a basic ecommerce website using entityframework. So my question is, what should I do to improve my skills, what type of website should I make? I tried looking in some books and video tutorial, but they are all the same from the documentation. I think I already know the basics. So I want to know what's next.

How to Display Total

$
0
0

I have a ViewComponent:

<h4>Kitset Parts</h4><table class="table"><tr><th>
                Product Code</th><th>
                Quantity</th><th>
                Product Description</th><th>
                Cost Price ex G.S.T.</th><th>
                Line Total ex G.S.T.</th></tr>


        @foreach (var p in Model)
        {
            <tr><td>

                    @p.Product.ProductCode
                </td><td>

                    @p.Quantity
                </td><td>
                    @p.Product.ProductDescription.Substring(0, Math.Min(p.Product.ProductDescription.Length, 38))</td><td>

                    @p.Product.CostPrice
                </td><td>
                    @(p.Product.CostPrice * p.Quantity)</td><td><a asp-controller="ProductKitset"
                       asp-action="Details"
                       asp-route-id="@p.ProductKitsetID">More Details</a></td></tr>


        }

        </table>

I know I can get a sum total using @Model.Sum(w.Product.CostPrice*w.Quantity) and this suits me as at this point all I am wanting is a display of the cost price, I don't want to store it, and I don't want to use it other than as information as to what the cost of this specific Kitset is costing at this point.

What I want to display is:

Quantity  Product  Price  Line Total

1         Widget        3.00     3.00

2         THingies      4.00     8.00

Total                                  11.00

I can do the first part easily.  I just don't understand how to show the total line.  I can get the total to repeat on each line, I can get the total to repeat as a separate line within the table, I just don't understand how to add the total in the view I can see it can be done.  Just not how to do it?

Failed to open up Azure web app

$
0
0

I'm building MVC Core app using Visual Studio Code on Mac OS.

I created MVC app using yeo generator working with database EF core, everything works fine on localhost. I put correct connection string for my Azure SQL Server db in appsettings.json and ran app from Azure link but got error - "An error occurred while starting the application." without any details.

I checked my Azure by Kudu "http://<yoursitename>.scm.azurewebsites.net", the files are uploaded properly.
I also had a chance to check my Azure SQL using SQL Server Management Studio on Windows, my database is well published.

In my Azure, I got Web App Service, SQL sever(V12), SQL database under the same Resource name. All of their status are online and running.

I did quite a lot of research online for my problem but still got stuck for 2 days.... Please help!!!

What I did was:

1. dotnet ef migrations add InitialCreate -c ApplicationDbContext ==> Compilation succeeded.

2. dotnet ef database update -c ApplicationDbContext ==> Compilation succeeded.

3. dotnet run ==> Compilation succeeded.

Output of step 3:

info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (373ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE') SELECT 1 ELSE SELECT 0

............... // doing DB seeding

info: Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
User profile is available. Using '/Users/matt/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Hosting environment: Production
Content root path: /Users/matt/Documents/MyApp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

4. git push -u azure master ==> Deployment successful.

Output of step 4:

............... // doing remote stuffs
remote: Finished successfully.
remote: Running post deployment command(s)...
remote: Deployment successful.
To https://myapp.scm.azurewebsites.net:443/myapp.git
85eecb5..914a2a0 master -> master
Branch master set up to track remote branch master from azure.

appsetting.json:

{"ConnectionStrings": {"DefaultConnection": "Server=tcp:myapp-test.database.windows.net,1433 ;Initial Catalog=myapp-test;Persist Security Info=False;User ID=<remove from blog>;Password=<remove from blog>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
   },"Logging": {"IncludeScopes": false,"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"
       }
   }
}

Configure method in Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var configuration = new ConfigurationBuilder()
                            .AddEnvironmentVariables()
                            .AddJsonFile(env.ContentRootPath + "/config.json")
                            .Build();

    if (configuration.GetValue<bool>("EnableDeveloperExceptions"))
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseIdentity();

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

    // Create database on startup
    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
    }

    DbInitializer.Initializer(context);
}

web.config:

<?xml version="1.0" encoding="utf-8"?><configuration><system.webServer><handlers><add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/></handlers><aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/></system.webServer></configuration>

 


Add Azure Active Directory Authentication to ASP.Net Core in Visual Studio 2017

$
0
0

Would someone please help me with finding the steps to add Azure Active Directory authentication to a ASP.Net Core app (using .NET Framework) in Visual Studio 2017?  I can find many examples and steps for how to do this with Visual Studio 2015 - however, the project structure and features have appeared to change quite a bit between 2015 and 2017.  There is no project.json file, for example, etc., etc.  My goal is to have an on-premises hosted web app use Azure AD for authentication.  Thanks.

HttpContext in normal class

$
0
0

I didn't found HttpContext.Current in core framework, looks its already been removed out. now i have several normal class (not middleware,controller) and i want to use HttpContext within the code, how can i to get the HttpContext back for working. Thanks!

Can't get debug working for ASP.NET web project

$
0
0

I have a simple web app that is supposed to run a query against an SQL database and format the returned row as an output xml file on my local drive.  This was working fine a week ago, and now, it is not.  The file used to be overridden by the latest data I selected via the input criteria on my the web page, but now the file remains with the data I last selected on 20 April 2017.

I'd like to see the code in debug mode (have it stop at breakpoints I've set within the OnClick event for the button that is supposed to trigger the above actions, but it never seems to get to those breakpoints.  I've specified ASP.NET under debugging in the project web properties, and debug="true" within the web.config <compilation> section.

I'm running VisualStudio2008 R2 Professional Edition on Windows 7 Professional SP1 .  I'm running the web page locally.

Search for route in RouteCollection

$
0
0

Is there a way to find a specific route and his values / datatokens in RouteCollection by a value.

I get the list with all routes with the code below. In the Collection is a non public member _namedRoutes and _Routes. In those two are the routes with the datatokens and values. But I don't know how to reach them and search for a specific route

RouteCollection Collection = ViewContext.RouteData.Routers.OfType<RouteCollection>().FirstOrDefault() 

Can someone help with this? Thanks in advance

P.S. I'm doing this in razor syntax

Some Errors starting my asp net core project

$
0
0

Hello, i have an error:

Unhandled Exception: System.InvalidOperationException: AddIdentity must be called on the service collection.
at Microsoft.AspNetCore.Builder.BuilderExtensions.UseIdentity(IApplicationBuilder app)
at Altram.Web.Donate.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in D:\Development\C#\Visual Studio\Altram System\Altram.Web.Donate\Startup.cs:line 122
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Altram.Web.Donate.Program.Main(String[] args) in D:\Development\C#\Visual Studio\Altram System\Altram.Web.Donate\Program.cs:line 10

When i start my project on Linux machine, i use Windows 10 as dev platform with VS2017 and Net Core 1.1.1 and i trying to publish the project on my linux machine from windows but i get this error, but when i use Windows, it works well, what can i do to be able to fix this?

Viewing all 9386 articles
Browse latest View live


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