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

accessing the Entity Framework 6 CodeFirst db in BaseController

$
0
0

Hi,

I am using ASPNet Core, EntityFramework 6 CodeFirst.

I have a BaseController which will get the User Information by accessing the Entity Framework 6 Code First database.  This will be inherited for all controllers in the app. On the class BaseController, event "OnActionExecuting", line "using (SVPData context1 = new SVPData())", I am running into error:

error:  "No connection string named SVPData could be found in the application config file."

Project: SVPWebApp

appSettings.json

 "ConnectionStrings": {
    
  "DefaultConnection":"Server=devserversql001;Database=SVP;Trusted_Connection=True;MultipleActiveResultSets=true"
 
  }

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddScoped<SVPData>(_ => new SVPData(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();

            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(15);
                options.CookieName = ".MyCoreApp";
             });

        }

 

vwSVPRecordController.cs

    public class vwSVPRecordController : BaseController
   {
        // GET: /<controller>/

        private readonly SVPData db;

        public vwSVPRecordController(SVPData context)
       {
            db = context;
        }

    }

 

BaseController.cs

    public class BaseController : Controller
    {
        const string SessionKeyUser = "_User";
        UserAuthorizationDTO user;

         public override void OnActionExecuting(ActionExecutingContext filterContext)
         {
               UserAuthorizationDTO uaDTO = GetUserDTO();

               if (uaDTO == null)
               {
                    string sUserName = System.Environment.UserName;

                    using (SVPData context1 = new SVPData())
                    {

                     }

             }

         }

}

How come before I added the BaseController, it was not having an error reading off the SVPData db in the vwSVPRecordController class?  How can I get and check the user info for the BaseController?

Please note that SVPData is in a different project.  It's app.config is this:

Project: SVPData

app.config
<configuration>
<connectionStrings>
 
<addname="SVPData"connectionString="data source=devserversql001;initial catalog=SVP;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

I appreciate your input!

Thanks,

tinac99

 


Problem with Razor mixed Javascript ...

$
0
0

 Hello everyone, I tried toswitch to ajavascript function server-sideinformation.The problem seems tobe dueto the factthat he can notread the valueof theJavaScriptvariable "filename" (it is notseen in the context)in thefollowing code:

<script>
    var selDiv = "";
    document.addEventListener("DOMContentLoaded", init, false);

    function init() {
        document.querySelector('#files').addEventListener('change', handleFileSelect, false);
        selDiv = document.querySelector("#selectedFiles");
    }

    function handleFileSelect(e) {
        if (!e.target.files) return;

        var html = "<table class=\"table table-striped\"><thead><tr>";
        html += "<th>#</th>";
        html += "<th>File Name</th>";
        html += "<th>Type</th>";
        html += "<th>Size</th>";
        html += "<th>Last Modified Date</th>";
        html += "<th>Note</th>";
        html += "</tr>";
        html += "</thead>";
        html += "<tbody>";

        var files = e.target.files;
        var isCorrectFile = false;
        for (var i = 0; i < files.length; i++) {
            var f = files[i];
            var filename = f.name;
            isCorrectFile = false;
            @foreach (Dictionary< string, object> dicFileName in ViewData["CsvNamesList"] as List<Dictionary<string, object>>) {<text>
                    if (filename == "@dicFileName["ImportFileName"]")
                    {
                        isCorrectFile = true;
                        break;
                    }
                    else
                    { isCorrectFile = false; }</text>
                }
            if (isCorrectFile) {
                html += "<tr>";
                html += "<th scope=\"row\">" + (i + 1) + "</th>"
                html += "<td>" + f.name + "</td>";
                html += "<td>" + f.type + "</td>";
                html += "<td>" + (f.size / 1000).toFixed(2).toString().replace('.', ',') + " KB" + "</td>";
                html += "<td>" + f.lastModifiedDate.toLocaleDateString() + "</td>";
                html += "<td>" + "" + "</td>";
                html += "<tr/>";
            } else {
                html += "<tr class=\"warning\" >";
                html += "<th scope=\"row\">" + (i + 1) + "</th>"
                html += "<td>" + f.name + "</td>";
                html += "<td>" + f.type + "</td>";
                html += "<td>" + (f.size / 1000).toFixed(2).toString().replace('.', ',') + " KB" + "</td>";
                html += "<td>" + f.lastModifiedDate.toLocaleDateString() + "</td>";
                html += "<td>" + "Nome del file non ammesso nel IMPORT" + "</td>";
                html += "<tr/>";
            }
        }
        html += "</tbody>";
        html += "</table>";
        selDiv.innerHTML = html;
    }</script>

Basicallywhen I manage toblock the executionwithbreakpoint I can readthe values of "@dicFileName["ImportFileName"]"and notthose of"filename"and"isCorrectName" variabledoes not goto "true"even if itshould. Paolo

VS2017 Deploying and Starting Minimal Kestrel SCD Application

$
0
0
Hello,

I am trying to create the smallest (only what I need) self-contained deployment possible for Asp.Net Core application using Kestrel that will run on a device like Raspberry Pi. However, I can not figure out how to do that in Visual Studio 2017 or by cmd line.

I am trying to mimick the node.js use case, where I start up an instance of node.js in any random folder with the least amount of modules to do the job. Using "dotnet new console", then adding Kestrel to .csproj (plus few other changes to serve "Hello World"), then calling "dotnet restore", then "dotnet build", creates a small folder (~367k) but depends on "dotnet run" to start. Doing a similar thing in Visual Studio 2017 results in a 17MB deployment folder (which is too big) that depends on VS2017 to start. I am hoping to achieve a size of less than ~2MB minus web application content and source code.

1) How do I deploy only the .Net Core files necessary (not the entire SDK) to the filesystem using Visual Studio 2017 or the cmd line?
a) or Is there a method for manually pruning the resulting deployment package or folder?

2) How do I start an SCD instance (NOT USING "dotnet run") within a folder (NOT USING IIS) from Visual Studio 2017 or the cmd line?

Thank you,

Migration error to Visual Studio 2017

$
0
0

I would like to migrate my ASP.NET Core project to Visual Studio 2017 Community Edition, but I'm getting an error.

E:\xxxxxx\projectName.xproj : error  : The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\DotNet\Microsoft.DotNet.Props" was not found. Also, tried to find "DotNet\Microsoft.DotNet.Props" in the fallback search path(s) for $(VSToolsPath) - "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" . These search paths are defined in "C:\Users\mskur\AppData\Local\Microsoft\VisualStudio\15.0_0cd52d80\devenv.exe.config". Confirm that the path in the <Import> declaration is correct, and that the file exists on disk in one of the search paths.  E:\xxxxxx\projectName.xproj

Do you need something else which can help you to investigate problem?

Thanks in advance.

What is the concept of classes and objects in n tier architecture or 3 tier architecture ?

$
0
0

By this question, I want to elaborate that how are classes made in a BO, BAL and DAL layers ? For example, Registration and login should be treated as methods and have to be made in DAL and needs to be called in BAL layer. But how are classes made in BEL, BAL and DAL layer? Hope you guys, understood my question....Thanks

VS community 2017 and Loading depandances

$
0
0

Hello,

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

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

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

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

thanks

asp.net core 1.0.1 and reporting services report viewer

$
0
0

Has anyone successfully integrated SQL 2016 SSRS reportviewer? If so, can you point me in the direction for a sample?

Modelbinding a List stopped working when moving from .net core 1.0 to .net core 1.1 .cshtml contains a form with a foreach loop

$
0
0

Hi all,

When upgrading to 1.1 my modelbinding from a form stopped working

public class test {

public int id {get;set;}

public string name {get;set;}

}

[HttpGet]

public async Task<IActionResult> doIt()

{

List<test> model = new List<test>();

test atest = new test();

atest.id = 1;

atest.name="First";

model.Add(atest);

atest = new test();

atest.id=2;

atest.name="Second";

model.Add(atest);

return View(model)

}

[HttpPost]

public async Task<IActionResult> doIt(List<test> model)

{

if(ModelState.IsValid)

{

//model.Count() is always Zero after upgrade to 1.1 :-)

}

}

//doIt.cshtml

@model List<test>

<form asp-action="doIt" method="post">

@foreach(test item in Model)

{

<label asp-for="@Model.First().id"></label>

<input type="hidden" asp-for="@item.id" value="@item.id" />

<label asp-for="@Model.First().name"></label>

<input type="hidden" asp-for="@item.name" value="@item.name" />
<button id="btnConfirm" type="submit" class="btn btn-info">Go On</button>

</form>
}

Change the EF Core connection string at runtime from a Controller

$
0
0

Hello,

I am using ASP.NET Core and EF Core for the creation of a Web API. I want to use thesame Web API (same controllers, same functionalities, etc.) formultiple databases. Therefore, what I want to accomplish is giving the connection string as a parameter to a controller and change it at runtime. For example, to use DB1 database, I want to make the following request:http://www.testserver.com/api/controller1/DB1 and change the connection string of the TestDbContext (which is TestDbContext : IdentityDbContext<TestUser>) as @"Server=(localdb)\MSSQLLocalDB;Database=DB1;integrated security=True;". If I want to use the DB2 then I'll make the same request but instead of DB1, I'll place the DB2 parameter. This is how I want my Web API finally to be working.

Is this possible? Can I change the EF Core connection string at runtime from a Controller? If yes, can anyone help me with this? If this is not possible, is there any other solution?

Please, I have tries a lot but I nothing seems to be working so I need your help.

Thanks in advance.

Hosting asp.net core online

$
0
0

Hi I am trying to host asp.net core blog online.This is my first time   hosting website online.Can anybody provide me documentation including step by step process how to host it other than   on azure

Thank You :)

Post Current Page Before Navigating Away

$
0
0

We have a web app that has 5 tabs with a form on each. After completing tab 1 and submitting it it posts the form data and redirects to tab 2.  The problem we are having is that we need navigation for the 5 different tabs.

So if you are on tab 1 and click on tab 3 we need it to first post the form data (check if the ModelState.IsValid) and then redirect to tab 3. What is the right approach for accomplishing this?

trouble with add-migration in VS 2017

$
0
0

Getting following error while trying to add a migration. Any ideas?

PM> add-migration m1
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at RIMS.Models.AppDbContextFactory..ctor() in C:\Users\bnilsen\Source\Repos\rims\RIMS\src\RIMS\Infrastructure\Data\AppDbContextFactory.cs:line 18
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_0.<FindContextTypes>b__3()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.

AspNetCore AzureAppServicesIntegration not compatible with netcoreapp1.1

$
0
0

I have a web.api project targeting netcoreapp1.1, when I try to:

Install-Package Microsoft.AspNetCore.AzureAppServicesIntegration 

I get an the error:

Install-Package : One or more packages are incompatible with .NETCoreApp,Version=v1.1.

Full error here: http://en.pastebin.ca/3779287
Seems like some dependecies:

* Microsoft.Data.Services.Client

What should I do?

 - Add a  second framework target? Defeats the purpose of using netcoreapp.

Any other tools which can be used for logging files into azure? I can add a blob and assign it to the filesystem of the app, but wanted to hear other ideas.

Thanks

ASP.NET Core application not freeing memory

$
0
0

I have an ASP.NET Core application running behind IIS in production that is not freeing memory on its own until the application pool recycles itself.  Every request causes the memory to increase.  

I am able to reproduce this with a fresh ASP.NET core application using Visual Studio 2017 with the ASP.NET Core Web API template.  I created the following method and called it from postman about 100 times:

namespace WebApplication3.Controllers
{
    [Route("")]
    public class ValuesController : Controller
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var message = "test";
            return Enumerable.Repeat(message, 100000);
        }
    }
}

I did a publish build and launched the application from the command line.

The memory usage goes up and is never released:

dotnet memory

Here is my dotnet version

PS C:\Windows\system32> dotnet --version
1.0.0

I expect the memory to go down after the requests are done being served.  Does anybody have any idea what is going on?

The ASPX file is turned into binary file.

$
0
0

Hi!

Recently, my PC got freeze and it shut down unexpectedly without saving my ASPX file. After I turned on again my PC, the ASPX file turned into binary file but the ASPX.CS is still accessible. How can I recover the codes in my ASPX file?

I tried looking on the backup files folder but nothing to see. I turned on my AutoRecovery since I started working.

I don't have admin rights to install recovery software, please help me to recover the file.

Thanks.


VS2017 Scaffolding error Microsoft.VisualStudio.Web.CodeGeneration.Utils

$
0
0

I am trying to just do an controller scaffolding on a ASP.NET Core application I and I get the following error

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.Web.CodeGeneration.Utils, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.Main(String[] args)

I looked on Google but they are not many references about VS2017 yet.

Thanks

What is Micro service in asp.net core

$
0
0

please get me good explanation for what is Micro service ?

when we use Micro service ?

web api or wcf will be used to develop Micro service ?

please guide me in details with easy way with example because the word Micro service is new to me. thanks

Auto migration in EF Core in three tier application

$
0
0

i have three tier application in Asp.net Mvc Core and use EF core, now i want create auto migration ,

i have DAL layer that my context available here

public class AdminContext : DbContext
    {

    public AdminContext(DbContextOptions<AdminContext> options) : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<AdsAdsCategory>()
             .HasKey(bc => new { bc.AdsId, bc.AdsCategoryId });

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Ads)
            .WithMany(b => b.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsId);

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Category)
            .WithMany(c => c.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsCategoryId);
    }

    public DbSet<Ads> Adses { get; set; }
    public DbSet<AdsCategory> AdsCategories { get; set; }
    public DbSet<AdsPosition> AdsPositions { get; set; }
    public DbSet<AdsCustomer> AdsCustomers { get; set; }
}

and in my application startup

i write this code

var context = app.ApplicationServices.GetService<AdminContext>();

       if (!context.Database.EnsureCreated())
            context.Database.Migrate();

when i run application database was created and table generate but __migrationhistory doesn't exist and migration not generate,

when in start up i remove this line code

if (!context.Database.EnsureCreated())

database was created and __migrationhistory table generated,but my model table not generate,

how i can solve this problem ? and run auto migration in EF Core in three tier application?

How to Log last Active Database Connection in ASP.NET Core

$
0
0

Hi, I am new to ASP.NET core and building an application. we got a requirement where we need to log the last active database connection and use it next time to reduce the likelihood of one connection attempt timing out. Please let me know how can I do this with logging the active database connection.

Please let me know if there are some configuration changes can be done to achieve the required output without using log database connection.

Request.CreateResponse() not found - What is the alternative?

$
0
0

I created a new web api project with VS 2017, and am migrating some old code. Several of the methods return HttpResponseMessage objects. The old code calls Request.CreateResponse to create the response object, but that method does not appear to be available from the request object anymore. What is the proper way to do this?

Viewing all 9386 articles
Browse latest View live


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