CLR Stored Procedure - clr

I wish to use the Cryptography API in CLR stored procedure.
I have created a CLR stored procedure and written a select statement
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Context Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = #"select * from Employee";
SqlDataReader rdr = cmd.ExecuteReader();
Now I wish to filter the results using the employee Number which is stored in encrypted form in database for which I am going to use the Cryptography methods.
Now I am stuck with how to go about filtering the records from the SqlDataReader.
I want the return format as SqlDataReader, as to return multiple records from CLR stored procedure there is one method SqlContext.Pipe.Send() and this method accepts only SqlDataReader objects.
Please guide me.

I'm looking at a similar problem where I want to do some manipulation before returning the results.
The only way I can see at the moment is to use:
// Note you need to pass an array of SqlMetaData objects to represent your columns
// to the constructor of SqlDataRecord
SqlDataRecord record = new SqlDataRecord();
// Use the Set methods on record to supply the values for the first row of data
SqlContext.Pipe.SendResultsStart(record);
// for each record you want to return
// use set methods on record to populate this row of data
SqlContext.Pipe.SendResultsRow(record);
Then call SqlContext.Pipe.SendResultsEnd when you're done.
If theres a better way I'd like to know too!

Related

Stored procedure returning dynamic columns in Entity Framework

I have a function calling a SQL Server stored procedure using Entity Framework 6.2.
The stored procedure returns a result set which has different number of columns on each call, and column names may vary on each call.
Function getListOfDocs() As JsonResult
Try
Using entities As PromatEntities = New PromatEntities()
Dim param(1) As SqlParameter
param(0) = New SqlParameter("#ProjID", SqlDbType.Int)
param(0).Value = vProjectId
Dim query = entities.Database.SqlQuery(Of "help required here")("sp_EIP_IPSSDocMaster_Get", param) // cannot handle this case as entity framework needs type
Dim lstDocs = query.ToList
End Using
Return Json(New With {lstDocs}, JsonRequestBehavior.AllowGet)
Catch ex As Exception
ClsCommon.ExceptionManager(ex)
Return Nothing
End Try
End Function
But Entity Framework doesn't allow anonymous types in database.SqlQuery. Can anyone suggest a way to solve the issue and get the anonymous type data to view?

How to check whether stored procedure executed successfully

If you have a stored procedure that executing multiple queries, doesn't return values and doesn't have error-handling in it, how can you ascertain whether the stored procedure ended successfully when calling from VB code?
For example, if the stored procedure is something like:
create stored procedure some_procedure
Insert into ...
delete ...
update ...
end
... and the VB code is like this:
Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Set rs = Cmd.Execute
Debug.Print rs(0)
... then how can I get a return value that is 0 for success or 1 for failure?
I believe passing the optional RecordsAffected parameter with the Execute statement will work for you. Since you're so scarce on the details you'll have to try it, but this has worked for me with SQL, and FoxPro OLEDB providers. Also, why no error handling? IMHO not having an error handler in code that has a good possibility of producing an error is asking for trouble.
...
Dim lngRecsAffctd As Long
Cmd.ActiveConnection = cn
Cmd.CommandText = "some_procedure"
Cmd.CommandType = adCmdStoredProc
Cmd.Execute lngRecsAffctd, ,adCmdStoredProc 'why set to a recordset when the sproc doesn't return anything?
Debug.Print lngRecsAffctd
...
The complete details of the Execute command and the RecordsAffected parameter can be found at msdn.microsoft.com/en-us/library/ms681559%28v=vs.85%29.aspx

Using Stored procedures in ASP.net MVC?

Guys I am trying to learn MVC and I want to use stored procedures to perform all CRUD operations in MVC framework. I have googled for tutorials and everything, but all the tutorials are using that "Code-First" approach and using Entity Framework to handle all the data.
I would really appreciate if someone could help me regarding how to use SP in MVC and could provide some links to tutorials or something like that.
Before you learn Entity Framework, before you learn LINQ to SQL, take the time to learn ADO.NET which is all you need if you want to call a stored procedure. The previously mentioned technologies are in fact built on top of ADO.NET so it's good to know what they are doing. Check out lesson 7 of this tutorial which shows you exactly how to call a stored procedure from any .NET application (including MVC).
You can always use code first from your db
Code First to an Existing Database
Using this simple method, I was able to call stored procedures in MVC application
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, SqlParameter[] commandParameters)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandTimeout = 0;
command.CommandType = commandType;
command.CommandText = commandText;
if (commandParameters != null && commandParameters.Length > 0)
command.Parameters.AddRange(commandParameters);
return FillData(command, connection);
}
}
}

Stub Update an Entity in Entity Framework

I want update an entity property(Count) in Entity Framework 6 with stub update manner, indeed i want plus one Count property value Without query database. How i can do this?
//...
var stub = new entity {Id = id};
_articles.Attach(stub);
stub.Count++; // Count always is 1! How i can do this without fetch/query database?
context.SaveChanges();
//...
The only way I'm aware of is to use a stored procedure.
create proc sp_UpdateCount #Id int
as
update [dbo].[EntityTable] set [Count] = [Count] + 1
where [Id] = #Id
and then run it in the code
SqlParameter paramId = new SqlParameter("#Id", id);
context.Database.ExecuteSqlCommand("sp_UpdateCount #Id", paramId);
Please note this will run the procedure immediately and you don't have to call SaveChanges for it. If you want to execute the procedure in a transaction with other changes make sure you create one explicitly with TransactionScope.
Hope it helps!

Entity Framework CTP5 - Reading Multiple Record Sets From a Stored Procedure

In EF4, this was not easily possible. You either had to degrade to classic ADO.NET (DataReader), use ObjectContext.Translate or use the EFExtensions project.
Has this been implemented off the shelf in EF CTP5?
If not, what is the recommended way of doing this?
Do we have to cast the DbContext<T> as an IObjectContextAdapter and access the underlying ObjectContext in order to get to this method?
Can someone point me to a good article on doing this with EF CTP5?
So i got this working, here's what i have:
internal SomeInternalPOCOWrapper FindXXX(string xxx)
{
Condition.Requires(xxx).IsNotNullOrEmpty();
var someInternalPokey = new SomeInternalPOCOWrapper();
var ctx = (this as IObjectContextAdapter).ObjectContext;
var con = new SqlConnection("xxxxx");
{
con.Open();
DbCommand cmd = con.CreateCommand();
cmd.CommandText = "exec dbo.usp_XXX #xxxx";
cmd.Parameters.Add(new SqlParameter("xxxx", xxx));
using (var rdr = cmd.ExecuteReader())
{
// -- RESULT SET #1
someInternalPokey.Prop1 = ctx.Translate<InternalPoco1>(rdr);
// -- RESULT SET #2
rdr.NextResult();
someInternalPokey.Prop2 = ctx.Translate<InternalPoco2>(rdr);
// -- RESULT SET #3
rdr.NextResult();
someInternalPokey.Prop3 = ctx.Translate<InternalPoco3>(rdr);
// RESULT SET #4
rdr.NextResult();
someInternalPokey.Prop4 = ctx.Translate<InternalPoco4>(rdr);
}
con.Close();
}
return someInternalPokey;
}
Essentially, it's basically like classic ADO.NET. You read the DbReader, advance to the next result set, etc.
But at least we have the Translate method which seemingly does a left-to-right between the result set fields and the supplied entity.
Note the method is internal.
My Repository calls this method, then hydrates the DTO into my domain objects.
I'm not 100% happy with it for 3 reasons:
We have to cast the DbContext as IObjectContextAdapter. The method Translate should be on DbContext<T> class IMO.
We have to use classic ADO.NET Objects. Why? Stored Procedures are a must have for any ORM. My main gripe with EF is the lack of the stored procedure support and this seems to not have been rectified with EF CTP5.
You have to open a new SqlConnection. Why can't it use the same connection as the one opened by the EF Context?
Hope this both helps someone and sends out a message to the EF team. We need multiple result support for SPROCS off the shelf. You can map a stored proc to a complex type, so why can't we map a stored proc to multiple complex types?

Resources