Dapper with MVCMiniProfiler - mvc-mini-profiler

I am wanting to use the MVCMiniProfiler with Dapper. Is this possible beyond wrapping the "Query" call from dapper in "Using Profiler.Step" block?
I have this basic Dapper call:
Dim comments As List(Of Comment)
Using conn = New SqlConnection(ConnectionString)
conn.Open()
comments = conn.Query(Of Comment)("SELECT * from comments where userid = #userid", New With {.userid= 1})
End Using
The MiniProfiler examples show this
Private Shared _sqlConnection As SqlConnection
Public Shared Function GetOpenConnection() As DbConnection
If _sqlConnection Is Nothing Then
_sqlConnection = New SqlConnection("connection string")
End If
' wrap the connection with a profiling connection that tracks timings
Return MvcMiniProfiler.Data.ProfiledDbConnection.[Get](_sqlConnection, MiniProfiler.Current)
End Function
Where I am stuck is in the implementation of the "Get" on the ProfiledDbConnection. Is it possible to use ProfiledDbConnection while using Dapper?

Good catch, the documentation is out of date, just updated it:
Use something like:
return MiniProfiler.Current != null ?
new MvcMiniProfiler.Data.ProfiledDbConnection(cnn, MiniProfiler.Current) :
cnn;
I killed the factory cause I wanted people to be able to inherit off ProfiledDbConnection and statics can not be virtualized.

Related

CRM 2016 OrganizationServiceProxy.EnableProxyTypes seems to hang

We're currently changing the architecture of our back end systems and we've discovered that we need to enable proxy types for use in CodeActivities for Workflows, using the OrganizationServiceProxy.EnableProxyTypes method.
However, whenever I include this method call it makes the Workflow run extremely slow before eventually failing.
Here is the code we use to call the method:
var service = serviceFactory.CreateOrganizationService(context.UserId);
if (service is OrganizationService)
{
tracingService.Trace("Enabling proxy types");
((OrganizationServiceProxy)((OrganizationService)service).InnerService).EnableProxyTypes(assembly);
tracingService.Trace("Proxy types enabled");
}
Any ideas?
Thanks
I've never had to pass an assembly in as a parameter to EnableProxyTypes. Did you try it without passing the assembly?
Also, there's another way to enable proxy types by adding to the Behaviors collection. Here's an example:
public static IOrganizationService GetOrganizationService(Guid userId)
{
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
Uri homeRealmUri = null;
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(new Uri(GetOrganizationUri()),
homeRealmUri, credentials, null))
{
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_serviceProxy.CallerId = userId;
IOrganizationService _service = (IOrganizationService)_serviceProxy;
return _service;
}
}

Create Pervasive Database using Distributed Tuning Objects (DTO)

I am writing an application in C# (.NET 4.0) which has to integrate with another, much older application. Part of the requirement is to integrate with a much older program that uses Pervasive PSQL Version 9. I asked this question about accessing the database without having to install an ODBC DSN. Part of the answer (thanks very much) is that I need to create a database using DTO.
I've used COM interop to access the dto2.dll COM library, and have read the samples, but I am having problems creating the database. Here is a summary of the code I'm using.
var session = new DtoSession();
var result = session.Connect("localhost", "", "");
Assert.AreEqual(dtoResult.Dto_Success, result);
testDB = new DtoDatabase {
Session = session,
Name = "Test1",
Ddfpath = #"C:\TEMP\DATA\DDF",
DataPath = #"C:\TEMP\DATA",
};
result = session.Databases.Add(testDB);
Assert.AreEqual(dtoResult.Dto_Success, result);
No matter what values I use for the Name and paths, that final Assert always fails. The error code is Dto_errDuplicateName. If I do not include the Session property I get a different error code (7039).
Has anyone done this successfully? What am I doing wrong?
I believe you are missing the Flags property of the DtoDatabase object. I had the following code in my archive as an example of adding a database with DTO. This code was probably written when DTO was first released but it works and the only difference I can see is the Flags property.
DtoSession session = new DtoSession();
dtoResult result;
result = session.Connect("localhost", "","");
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error connecting. Error code: " + result.ToString());
return;
}
DtoDatabase testDB = new DtoDatabase();
testDB.Name = "Test1";
testDB.DataPath = #"C:\DATA";
testDB.DdfPath = #"C:\DATA";
testDB.Flags = dtoDbFlags.dtoDbFlagNotApplicable;
result = session.Databases.Add(testDB);
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error Adding. Error code: " + result.ToString());
return;
}
Console.WriteLine("DB Added.");

SqlDependency not working with Entity Framework

I have an issue when trying to start the SqlDependency.
The error informs me: Keyword not supported: 'metadata'.
The connectionstring is the following when retrieved from the immediate window right before it crashes.
?objectContext.Connection.ConnectionString
"metadata=res://*/YeagerTech.csdl|res://*/YeagerTech.ssdl|res://*/YeagerTech.msl;provider=System.Data.SqlClient;provider connection string=\"data source=Bill-PC;initial catalog=YeagerTech;integrated security=True;multipleactiveresultsets=True;App=EntityFramework\""
Here is the code. It crashes on the Start method. Apparently, it doesn't think the EF connectionstring is valid. Any idea of how I can correctly use this?
YeagerTechEntities dbContext = new YeagerTechEntities();
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
SqlDependency.Start(objectContext.Connection.ConnectionString);
Because EF connection string is not valid for SqlDependency. It works only with EntityConnection but SqlDependency uses SqlConnection. So you must either use direct connection string in your dbContext or extract database connection string from entity connection.
Either:
var connectionString = dbContext.Database.Connection.ConnectionString;
Or
var connectionString = ((EnityConnection)objectContext.Connection).StoreConnection.ConnectionString;
Anyway EF doesn't play very well with SqlDependency. SqlDependency expects that you write SQL queries yourselves and have them under your control.
Actually, the code snippet that I got it to work is the following:
YeagerTechEntities dbContext = new YeagerTechEntities();
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
Application["dbContext"] = dbContext;
objectContext.Connection.ConnectionString =
ConfigurationManager.ConnectionStrings["YeagerTechEntities"].ConnectionString;
SqlDependency.Start(((System.Data.EntityClient.EntityConnection)objectContext.Connection)
.StoreConnection.ConnectionString);
YeagerTechEntities is the EF connectionstring.

How to execute a custom sql statement in LLBLGen 3.1 (self servicing)?

Using LLBLGen 3.1 (Self Servicing) on SQL Server, how would one execute custom SQL, such as:
delete from UserPreference
select * from UserPreference (into a datatable, for example)
Just noticed this question hadn't been answered. With Self Servicing, you'll probably use the TypedListDAO class.
See: Generated code - Fetching DataReaders and projections, SelfServicing
The TypedListDAO class has what you need to do SQL against your database, and it can automatically do projections onto custom classes for you if you need that (see the article).
But basically, (from memory, so might need some slight adjustments), here's what your code might look like:
// inside the DaoClasses namespace of your generated project
TypedListDAO dao = new TypedListDAO();
// do it yourself, and use your project's connection string
string connectionString = CommonDaoBase.ActualConnectionString;
using (var conn = new SqlConnection(connectionString)) { }
// use a DbConnection directly
DbConnection connection = dao.CreateConnection();
// or
connection = dao.DetermineConnectionToUse(null);
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM UserPreferences";
cmd.CommandType = CommandType.Text;
var reader = cmd.ExecuteReader(CommandBehavior.Default);
while (reader.Read()){}
reader.Close();
// use a datareader
IRetrievalQuery query = new RetrievalQuery(
new SqlCommand("SELECT * FROM UserPreferences"));
// or new RetrievalQuery(cmd);
// where you create the cmd using the dao connection
IDataReader reader = dao.GetAsDataReader(null, query,
CommandBehavior.CloseConnection);
while (reader.Read()){}
reader.Close();
// use a datatable - try something like this
// (BUT honestly, you might want to look at the custom projection
// into custom classes capability, or the data reader, instead of this)
DataTable dt = new DataTable();
dao.GetMultiAsDataTable(new EntityFields(0) /* can't be null, i don't think */,
dt, query, null);
// other methods
dao.ExecuteScalarQuery(query, null);
ActionQuery actionQuery = new ActionQuery(new SqlCommand("INSERT ..."));
dao.ExecuteActionQuery(actionQuery, null);
OR, use a micro-orm to do your sql, and just use the connection from the TypedListDAO class above
Some Light-weight micro-orms, like: Dapper (1 cs file), PetaPoco, Massive, etc...
While it is true that you can access the low level data readers, etc.. I think it kind of defeats the purpose of using the ORM. If you just want to fill a datatable from a collection (with or without filtering), you can use the static method GetMultiAsDataTable (which you can pass a predicate expression to if you want to do filtering). If you want to replace more complex SQL (very useful for reporting), check out the dynamic lists capabilities:
http://www.llblgen.com/documentation/4.0/LLBLGen%20Pro%20RTF/hh_start.htm
The QuerySpec is an even nicer way to specify a dynamic query and project it:
http://www.llblgen.com/documentation/4.0/LLBLGen%20Pro%20RTF/hh_start.htm

MVC Mini Profiler with Entity Framework: How to Get Connection

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.

Resources