MVC Mini Profiler with Entity Framework: How to Get Connection - mvc-mini-profiler

I would like to use MVC Mini Profiler for Entity Framework Connection. The way I did it is like this:
public static XXXXX.DAL.BO.XXXXXEntities GetEntityConnection()
{
var conn = ProfiledDbConnection.Get(new EntityConnection(ConfigurationManager.ConnectionStrings["XXXXXEntities"].ConnectionString));
return ObjectContextUtils.CreateObjectContext<XXXXX.DAL.BO.XXXXXEntities>(conn);
}
So the following line is to get the Context for the rest of the code:
XXXXX.DAL.BO.XXXXXEntities ctx = GetEntityConnection();
When I attempted to view this site on a browser, however, the WebDev.WebServer40.exe crashed.
Does anyone have any idea why?
Thanks heaps.
P.S.
Previously it was
XXXXX.DAL.BO.XXXXXEntities ctx = new XXXXX.DAL.BO.XXXXXEntities();
and it worked fine.

If you are able to use the v3.0.10 nuget for EF6, then all you need to do to hook up Entity Framework is
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
}
Using EF 5 or earlier (with the corresponding nuget package) would require you to generate an EFProfiledDbConnection as Anirudh wrote in his answer:
var conn = new EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
return ObjectContextUtils.CreateObjectContext<MyModel>(conn);

try initialising your connection to :
connection = new EFProfiledDbConnection( new EntityConnection(ConfigurationManager.ConnectionStrings["XXXXXEntities"].ConnectionString),
MiniProfiler.Current);
works for me.

Related

Oracle connection strings in blazor app with ef code

I have a Blazor server project with Oracle Database. When I try to use the connection
"ConnectionStrings": {
"GTravelDbConnection": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=XE)));User Id=GTRAVEL; Password=cteam;"
in appsettings.json and use in program.cs the following code
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("GTravelDbConnection");
builder.Services.AddDbContext<GTravelDbContext>(
options => options.UseOracle(connectionString)
);
I get the error
No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The same connection string if used from dbcontext class
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseOracle("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=XE)));User Id=GTRAVEL; Password=cteam;");
}
}
works with no problem.
I would be obliged if someone could help me.
The problem was that I was trying to use a scoped service without creating a scope. When I used the following code in program.cs
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("GTravelDbConnection");
builder.Services.AddDbContext<GTravelDbContext>(
options => options.UseOracle(connectionString)
);
builder.Services.AddScoped<ICustomerService, CustomerService>();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var customerService = services.GetRequiredService<ICustomerService>();
}
it all worked perfectly.
Thank you

Problem with ConfigurationStoreOptions while upgrading to Duende IdentityServer 6.0

I have some integration tests that use a real database targetting a ConfigurationDbContext. When upgrading to Duende IdentityServer 6.0, the constructor for ConfigurationDbContext breaks (only accepts 1 arg instead of 2) because of the DbContext connection pooling feature that was added.
This code breaks:
public static ConfigurationDbContext GetConfigurationDbContext()
{
var connectionString = Configuration.GetConnectionString("ConfigurationDbContext");
var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
builder.UseSqlServer(connectionString);
var options = new ConfigurationStoreOptions
{
DefaultSchema = Schema.IdSrv
};
return new ConfigurationDbContext(builder.Options, options);
}
So I changed it to:
return new ConfigurationDbContext(builder.Options);
Now I can build, but my tests fail with this error:
Unable to resolve service for type 'Duende.IdentityServer.EntityFramework.Options.ConfigurationStoreOptions'
How am I supposed to pass the ConfigurationStoreOptions in? Looking at the code in Github, it looks like it relies on dependency injection. (Getting the options from services collection).
OK, I figured out my own problem, but I had to hunt and peck around. It is not listed as a breaking change in the upgrade documentation:
https://docs.duendesoftware.com/identityserver/v6/upgrades/v5.2_to_v6.0/
The solution is to upgrade your project to 6.1
<PackageReference Include="Duende.IdentityServer.EntityFramework.Storage" Version="6.1.5" />
Then you can use this code instead (StoreOptions has been made a public set property)
public static ConfigurationDbContext GetConfigurationDbContext()
{
var connectionString = Configuration.GetConnectionString("MyIdentity");
var builder = new DbContextOptionsBuilder<ConfigurationDbContext>();
builder.UseSqlServer(connectionString);
var options = new ConfigurationStoreOptions
{
DefaultSchema = Schema.IdSrv
};
var dbContext = new ConfigurationDbContext(builder.Options);
dbContext.StoreOptions = options;
return dbContext;
}
This will work for ConfigurationDbContext and PersistedGrantDbContext.

CMS Open Payments Data Limitation

I've finally got around to getting the code needed to import web API into my SQL environment. However, when I ran the SSIS Script Component package (Script Language: Visual Studio C# 2017) I was only able to retrieve 1000 records out of of millions. A consultant mentioned that I may have to incorporate the App Token into my code in order to access additional records.
Would someone be able to confirm that this true? And if so, how should it be coded?
Here is the code prior to my "ForEach" loop code:
public override void CreateNewOutputRows()
{
//Set Webservice URL
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string wUrl = "https://openpaymentsdata.cms.gov/resource/bqf5-h6wd.json";
string appt = "MyAppToken";
try
{
//Call getWebServiceResult to return our Article attributes
List<Payment> outPutResponse = GetWebServiceResult(wUrl);
If there's an alternative method to using the app token (like in the HTTP Connection for example) please let me know.
Figured it out...
https://openpaymentsdata.cms.gov/resource/bqf5-h6wd.json?$limit=10000&$$app_token="MyAppToken"

CosmosDB Project Layout

Asking for advice and references.
Using Visual Studio, I have an Azure Web Apps project in my solution. Now, I'm programming my Stored Procedures for CosmosDB. Using the CosmosDB Emulator, I can simply insert the Stored Procedure code directly into the browser editor window. All good and fine, and everything is working beautifully.
I also have a NodeJS project sitting alongside my Web App project. This allows me to store the Stored Procedures as files. The associated Console App is able to connect and modify the CosmosDB Emulator as expected.
My question is, using Visual Studio, what is the best way to lay out my project, so that it's not done on napkins and prayers?
I'm wondering how I should be structuring my project layout and assets to align with current "best practices". Is there any information, articles or posts that you guys/gals have found that talk about this specifically? Would I be running all of these procedures against CosmosDB manually, or are there automated procedures people have devised? I would like to be able to test these stored procedures first, against the Emulator, and with little-to-no source code change, update staging.
Thanks!
I have just recently asked myself the same question regarding stored procedure migrations.. I am currently running a basic Migrate Method that will get stored procedure content from a js file and replace/create the stored procedure, this runs on startup (in startup.cs)
The main gist of the code below, you will need to create the very basic internal methods (comments welcome):
using System;
using System.IO;
using System.Threading.Tasks;
using App.Data.Access;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Azure.Documents;
namespace App.Data.StoredProcedures
{
public class Migrations : IMigrations
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IDocumentDbContext _documentDbContext;
public Migrations(IHostingEnvironment hostingEnvironment,IDocumentDbContext documentDbContext)
{
_hostingEnvironment = hostingEnvironment;
_documentDbContext = documentDbContext;
}
public async Task<bool> Migrate()
{
try
{
await AddUpdateBulkDeleteStoredProcedure();
return true;
}
catch (Exception exception)
{
throw new Exception("Error running CosmosDb stored procedure migrations,error" + exception.Message);
}
}
public string GetStoredProcedureScript(string filename)
{
var script = Path.Combine(_hostingEnvironment.WebRootPath, "App_Data", "CosmosDbStoredProcedures", filename);
return IO.File.ToString(script);
}
public async Task<bool> AddUpdateBulkDeleteStoredProcedure()
{
const string storedProcedureId = "BulkDeleteStoredProcedure";
var function = GetStoredProcedureScript($"{storedProcedureId}.js");
if (string.IsNullOrWhiteSpace(function))
{
throw new Exception($"Error running DocumentDb Stored procedure migrations, {storedProcedureId} content is empty");
}
try
{
await _documentDbContext.Client.ReplaceStoredProcedureAsync(_documentDbContext.GetStoredProcedureUri(storedProcedureId), new StoredProcedure {Id = storedProcedureId, Body = function});
return true;
}
catch
{
// ignore
}
await _documentDbContext.Client.CreateStoredProcedureAsync(_documentDbContext.DocumentCollectionUri, new StoredProcedure {Id = storedProcedureId, Body = function});
return true;
}
}
}

ASP.NET BoilerPlate: .Net core template - app service error

I am in the process of moving my app code from the .Net5 MVC/JQuery ASPNETZERO template to the new .Net core 1.1 MVC/JQuery template.
So far I have copied over my first few custom entities. Created a EF migration and applied the changes to my DB.
I then started building the first app service for one of my entities. I am copying over the code from my existing MVC template that is working without any issues.
public async Task<PagedResultDto<ListValuesListDto>> GetListValues(GetListValuesInput input)
{
var query = from lv in _listvaluesRepository2.GetAll()
select new ListValuesListDto
{
Id = lv.Id,
ListName = lv.ListName,
ListText = lv.ListText
};
query = query.WhereIf(!input.Filter.IsNullOrWhiteSpace(), lv => lv.ListName.Contains(input.Filter) || lv.ListText.Contains(input.Filter));
var resultCount = await query.CountAsync();
var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
return new PagedResultDto<ListValuesListDto>(resultCount, results);
}
The method above is from my MVC template. When I place this into the .Net core solution, I keep getting the following build error.
CS0411 The type arguments for method 'Enumerable.OrderBy(IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly
The error is pointing to the "OrderBy" on this line of code:
var results = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
I am still very much learning the ABP template and EF. I cannot for the life of me figure out why the same code in the .Net core template does not work?
Any help that anyone can provide would be much appreciated!
I just solved my own issue. I had to add the using statement for System.Linq.Dynamic.Core
Hope it helps someone else! :-)

Resources