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

DbContext is getting disposed - Dependency Injection EF Core (Simple App)

$
0
0

Hello everyone! I've been searching for a while, but I haven't spot anything unusual... Maybe some configuration I've been missing? I'm injecting a dependency file which at the same time contains an injected DbContext. Problem is that the context is being disposed before I can access it.

The flow is at follows:

User access HomeController. Sends email to the RegisterEmail method. RegisterEmail method works with an injected RegisterEmail object, which at the same time has an injected EmailContext. 

Whenever I'm in the CheckIfEmailExists method I receive an error that it has been disposed.

Here's my code:

HomeController.cs

 public class HomeController : Controller
    {
        private readonly IRegisterEmail _registerEmail;
        public HomeController(IRegisterEmail registerEmail)
        {
            _registerEmail = registerEmail;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult RegisterEmail(RegisterInputViewModel model)
        {
            if (!ModelState.IsValid)
                return View("Index",model);
            TempData["msg"] = _registerEmail.NewEmailRegistration(model.Email);

            return RedirectToAction("Index");
        }
    }

RegisterEmail.cs

ublic class RegisterEmail : IRegisterEmail
    {
        private readonly ILogger _logger;
        private readonly EmailContext _emailContext;
        private string _error;

        public RegisterEmail(ILogger<RegisterEmail> logger, EmailContext emailContext)
        {
            _logger = logger;
            _emailContext = emailContext;
        }

        private async Task<bool> AddEmail(Register email)
        {
            _emailContext.RegisterDb.Add(email);
            try
            {
               await _emailContext.SaveChangesAsync();
               return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _error = ex.Message;
                return false;
            }

        }

        public async Task<string> NewEmailRegistration(string emailAddress)
        {
            if (string.IsNullOrWhiteSpace(emailAddress))
                throw new ArgumentException("Email Address can't be blank or null");

            if (await CheckIfEmailExists(emailAddress))
                return "Email exists!";

            return await AddEmail(Register.NewRegistration(emailAddress))
                    ? "Email has been added"
                    : $"The following error has occured: {_error}";

        }



        private async Task<bool> CheckIfEmailExists(string emailAddress)
        {
            try
            {
                return await _emailContext.RegisterDb
                                   .FirstOrDefaultAsync(x => x.Email.ToLowerInvariant() == emailAddress.ToLowerInvariant())
                                   != null;


            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw;
            }
        }


    }

IRegisterEmail.cs:

    public interface IRegisterEmail
    {
        Task<string> NewEmailRegistration(string emailAddress);
    }

Startup.cs:

 public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            //Enable Session Before MVC
            services.AddMemoryCache();
            services.AddSession();

            //DI here:
            services.AddTransient<IRegisterEmail, RegisterEmail>();
            services.AddDbContext<EmailContext>(options =>
                   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add framework services.
            services.AddMvc();
            services.AddLogging();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

Anything unusual? 


Problem with the passage of a json string in javascript

$
0
0

Hello everyone, I'm developing in asp.net mvc core and use c #, I need to move to javascript a json string representing an array of objects.

After processing "ViewData["Data"] = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectsArray);" get :

[{"id":"0","parent":"#","text":"server","level":0,"folderName":"server","folderPath":"Z:\\csi\\server","fileItems":[
{"fileName":"serverfile1","filePath":"Z:\\csi\\server\\serverfile1.txt","fileExtension":".txt"},
{"fileName":"serverfile2","filePath":"Z:\\csi\\server\\serverfile2.txt","fileExtension":".txt"},
{"fileName":"serverfile3","filePath":"Z:\\csi\\server\\serverfile3.txt","fileExtension":".txt"}]}]

In javascript I process the following statement "var data = JSON.parse(@Convert.ToString(ViewData["Data"]));" giving me this error:

Errore critico JavaScript alla riga 87, colonna 36 in http://localhost:9191/\n\nSCRIPT1028: Previsto identificatore, stringa o numero

at this row:

var data = JSON.parse([{&quot;id&quot;:&quot;0&quot;,&quot;parent&quot;:&quot;#&quot;,&quot;text&quot;:&quot;server&quot;,&quot;level&quot;:0,&quot;folderName&quot;:&quot;server&quot;,&quot;folderPath&quot;:&quot;Z:\\csi\\server&quot;,&quot;fileItems&quot;:[
{&quot;fileName&quot;:&quot;serverfile1&quot;,&quot;filePath&quot;:&quot;Z:\\csi\\server\\serverfile1.txt&quot;,&quot;fileExtension&quot;:&quot;.txt&quot;},
{&quot;fileName&quot;:&quot;serverfile2&quot;,&quot;filePath&quot;:&quot;Z:\\csi\\server\\serverfile2.txt&quot;,&quot;fileExtension&quot;:&quot;.txt&quot;},
{&quot;fileName&quot;:&quot;serverfile3&quot;,&quot;filePath&quot;:&quot;Z:\\csi\\server\\serverfile3.txt&quot;,&quot;fileExtension&quot;:&quot;.txt&quot;}]}];

The statement I took during debugging.

.Net Core - windows explorer has stopped working

$
0
0

When I try to run any .net core app on my machine I get an error saying windows explorer has stopped working.

The code compiles on my machine fine and works until it gets to host.Run() in Main..

I tried IIS express, tried running from dotnet command line, all the same result..

Here is a sample incident report

Problem signature:
Problem Event Name: BEX64
Application Name: explorer.exe
Application Version: 6.1.7601.17567
Application Timestamp: 4d672ee4
Fault Module Name: CreateProcessHook64.dll
Fault Module Version: 7.6.0.5015
Fault Module Timestamp: 54102da4
Exception Offset: 000000000004798a
Exception Code: c000000d
Exception Data: 0000000000000000
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1033
Additional Information 1: e5be
Additional Information 2: e5be2c022a5d10933ffa1d5fa6cae64c
Additional Information 3: 258f
Additional Information 4: 258f09d1c274ba58c11566f728a6a266

Where from to start learning asp.net.core 1.0

$
0
0

sir

Please guide where from I should start learning to become an expert in asp.net core 1.0.

Regards

Mocking framework for core

$
0
0

Hi,

When I tried to add Moq(4.7.8) from nuget package for my asp.net core project , I got following error.  What is the correct version of Moq I should use..

Error One or more packages are incompatible with .NETCoreApp,Version=v1.1.
Error Package Microsoft.Composition 1.0.27 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1).
Package Microsoft.Composition 1.0.27 supports: portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
Error Package restore failed. Rolling back package changes for 'WebAPI.Test'.

my Current xUnit test project version is 

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="xunit" Version="2.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />

SCD Deployment

$
0
0

 I've created a very simple project in VS 2017 using the standard template ASP.NET Core Web Application (.Net Core) and edited the csproj per SCD recommendations in MS docs:

Adding this to  the property group:

<OutputType>Exe</OutputType><TargetFramework>netcoreapp1.1</TargetFramework> <RuntimeIdentifiers>win10-x64;osx.10.11-x64</RuntimeIdentifiers>

But, I can't get past 4 errors:
Unable to resolve 'runtime.win7-x64.Microsoft.NETCore.Runtime.CoreCLR (>= 1.1.1)' for '.NETCoreApp,Version=v1.1 (win10-x64)'.

Unable to resolve 'runtime.win7-x64.Microsoft.NETCore.Jit (>= 1.1.1)' for '.NETCoreApp,Version=v1.1 (win10-x64)'.

Unexpected dependency 'runtime.win7-x64.Microsoft.NETCore.Jit' with no version number.	Precompile	C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets  line 154

Unexpected dependency 'runtime.win7-x64.Microsoft.NETCore.Runtime.CoreCLR' with no version number.	Precompile	C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets  line 154	



SignalR and SQL Dependency in asp.netCore 1.1

$
0
0

I'm working on a project whereby i want to pust notifications to the client when database changes. Can i use SignalR and Sql dependency with asp.net core 1.1. Thanks for your Help

How many servers are available to deploy a asp-net core web applications? Please mention.

$
0
0

Sir

How many servers are available to deploy a asp-net core web applications? Please mention.

Regards


How I can read for 10 images two api call the most efficient foreach(item in collection)    {        output 1 = await await Client.GetStringAsync(url1)        output2 =  await Client.GetStringAsync(url2) }

$
0
0

Hello,

I have a IEnumerable<string> that contains objectNumbers.

Now for each objectNumber I have to read two different api endpoints.

If I have read both I will filter some data out of both and sends it to a view.

But my question is how can I do the calling and fetching the best

I now do :

  

foreach(item in collection)   {       output 1 = await await Client.GetStringAsync(url1)       output2 =  await Client.GetStringAsync(url2)
} 

but then it takes some 3 - 4 seconds to fetch and filter all the data.

So can I do this more effcient so it will costs me around 1 sec maybe.

Regards,

Roelof

I can not open the files when I start the browser in debugging mode with visual studio 2015 ...

$
0
0

Hello everyone, I am developing an application asp.net core mvc with Visual Studio 2015, and within a html page I have placed links to files of different types (for. Example: pdf, xls, txt, etc ...) however, when running in debug if I use Internet explorer gives me an error of lack of authorization. If you use Chrome instead it does nothing. Trying the same javascript code in Notes ++. I have no problem opening the files with both browsers.

How do I get route values from inside a View Component controller?

$
0
0

I have a View Component in _Layout.cshtml. My application has a route of /home/{id}. How can I get the id value in my URL route from the View Component controller?

public class LayoutViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        //how do I get the value of {id} here?

        return View();
    }
}

Changes to files aren't reflected in web page

$
0
0

I have found one issue with automatically getting new page when refreshing it after changing some source file in VS. The explanation of this issue is here. Any ideas?

Replace the RouteHandler in custom route

$
0
0

In MVC 5 I can do stuff like

<div class="comment-right-col">
publicclassCustomRouteHandler:MvcRouteHandler{protectedoverrideIHttpHandlerGetHttpHandler(RequestContext requestContext){// add to HttpContext
           requestContext.HttpContext.Items["Custom"]= data;// or RouteData
           requestContext.RouteData.Values.Add(key, value);}returnbase.GetHttpHandler(requestContext);}}// define route with custom handler Route customRoute =newRoute(
    url:...,
    defaults:null,
    constraints:...,
    routeHandler:newCustomRouteHandler()});

routes.Add(customRoute);

How can I do this in MVC 6 / vNext?

</div>

Is there a filter for static file request?

$
0
0

is there a way to intercept or filter the request before serving the file? like if i request 

localhost:5000/images/random.jpg?w=100&h=100

so i can get the random.jpg the w and the h, then return it as an image

i tried intercepting it using MapRoute and it doesn't work when i use app.UseStaticFiles();

Memory increase when make multiple requests to .Net Core WebAPI


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>

Xunit and .net core

$
0
0

 

I am having strange problems trying to get Xunit to work on .net core.  

The latest issue I am having is that xunit seems to depend upon System.Xml.Linq (which of course is not available in .net core!!)

Help!!

P.S I tried upgrading to the latest pre-releases as someone suggested that might solve the issue - instead I got another similar error but just for "System"

An exception occurred while test discoverer 'VsTestRunner' was loading tests. Exception: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.

Make a pdf and print a file

$
0
0

Hello everyone

I'm really new to .NET Core and we have to make a webapplication for some company. We have an Excel-template which we can fill in with some data, then we have to create a PDF from this Excel. We use Shaman.EPPlus to make the Excel.

Now we want to create a pdf from that excel, but every package we try seems to be not compatible with .NET Core 1.0. I tried iText, PDFSharp and some other. Does anyone know a package which works fine with .NET Core 1.0?

And does anyone know how to open a PrintDialog? Because that won't work as well. I can create one, but when I call ShowDialog() I get some error about an assembly. Has anyone a solution?

Thanks!
Thomas

code first using vs2017

$
0
0

The only visual studio i have used so far is -Visual studio 2012 express for web.Well i have created few mvc application with the help of local database(without use of ssms),by using the code first migrations creating local Db in the name u have given in the model & webconfig file.

Recently i have installed VS-2017 for community. I have tried both .net and core  to create MVC application but cant create local db(mdf) using code first.I am sure why,anyone can help regrading this.

is it possibly to create a local db(without connecting to ssms) like in express using code first.Help me with ya tutorial.

Thanks

How Are You Calling Your Development vs. Production Web Service in ASP.NET CORE

$
0
0

i m working with .net core recently. 

In my scenario i have to use different web services for test and production in my application. (same functionality but with different service address)

for testing it is pointing to one service address and for production it is pointing to other  service address. 

in asp.net mvc we use different web.config files but in asp.net core where i have to provide the binding settings for web service with different address .plz tell me  whats the way to do. it would be great helpful for me. 

Thank u

Viewing all 9386 articles
Browse latest View live


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