I am tyring to develop a sample project in mvc. In this, i tried to get the userlist from database (mysql). i am using enterprise library dll to set the database connectivity.
public IEnumerable<UserViewModel> GetUserList()
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("MySqlConnection");
DbCommand dbc = db.GetStoredProcCommand("uspGetUserList");
dbc.CommandType = CommandType.StoredProcedure;
return db.ExecuteDataSet(dbc);
}
i know the executedataset is to execute only dataset type... i want the command that execute IEnumerable type.....
thank you
If you want to return an IEnumerable type without manually constructing it (either from a DataSet or an IDataReader) then you can use accessors.
In your case your could would look like this:
public IEnumerable<UserViewModel> GetUserList()
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create("MySqlConnection");
IEnumerable<UserViewModel> results = db.ExecuteSprocAccessor<UserViewModel>("uspGetUserList");
return results;
}
This assumes that the UserViewModel can be mapped from the stored procedure result set (e.g. column names are the same name as the property names). If not, then you would need to create a custom mapper. See Retrieving Data as Objects from the Developer's Guide for more information about accessors.
Related
I have a grails service that calls stored procedures using Groovy SQL.
I am using dataSource for initializing the connection.
My question is: Do I need to manually close the connection or will it be handled by Groovy or GORM (since I am using def dataSource)?
Here is how my service is structured.
class MyService {
static transactional = Boolean.FALSE
private static final String STATEMENT_ONE_SQL = "{ call sp_One(?) }"
private static final String STATEMENT_TWO_SQL = "{ call sp_Two(?,?) }"
def dataSource
Sql sql
#PostConstruct
def initSql() {
sql = new Sql(dataSource)
}
List<GroovyRowResult> callSpOne(Integer id) {
List<GroovyRowResult> results = sql.rows(STATEMENT_ONE_SQL, [id])
return results
}
List<GroovyRowResult> callSpTwo(Integer id, String name) {
List<GroovyRowResult> results = sql.rows(STATEMENT_TWO_SQL, [id, name])
return results
}
Basing on official docs
Finally, we should clean up:
sql.close()
If we are using a DataSource and we haven't enabled statement caching, then strictly speaking the final close() method isn't required - as all connection handling is performed transparently on our behalf; however, it doesn't hurt to have it there as it will return silently in that case.
If instead of newInstance you use withInstance, then close() will be called automatically for you.
I have a 'Execute SQL task' which product a row count. see screen 1.
I am trying to print 'ContactRowCount' in ssis 'Script task'. See screen 2.
But Dts.Variables["User::ContactRowCount"] is null. I can retrieve it.
Anyone knows how to retrieve variable value from 'Execute SQL task' in script task
Screen - 1
Screen - 2
Do read documentation, all of this has been covered.
Variables
I have two variables. One is for my SQL, called Quqery, which is optional. The other is an Int32 called RowCount.
Execute SQL Task
I have an Execute SQL task that uses an OLE DB Connection Manager. I have specified that it as a ResultSet of Single Row. I use my Query variable as the source.
The value is
SELECT COUNT(1) AS ContactRowCount FROM sys.columns AS SC;
In the Result Set tab, I map the 0 ResultSet to my variable User::RowCount.
If you are using a different Connection Manager provider (ADO.NET or ODBC), then these semantics all change. But it's documented.
Script Task
I ensure that I am passing in my variable as a read only object
Within my script, I need to access that variable. This is case sensitive. Furthermore, I want the .Value property. Your code, were it to work, would be casting the SSIS Variable to a string. This results in the default of the object emitting its name Microsoft.SqlServer.Dts.Runtime.Variable
Instead, we will want to access the .Value property which is returned as an object. If you were trying to do something mathematical with this value, then you'd need to convert it to an integer value but since we're going to string, that's easy.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_454527867e9d448aad6a7f03563175b2.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
string strMessage = Dts.Variables["User::RowCount"].Value.ToString();
MessageBox.Show(strMessage);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
use variable name in the script task and not the result set name.
Just check the variable values during runtime debug.
I've been searching for a solution for days now and I still cant seem to find one. I have a problem acquiring a connection in my Script component. I need to query my database to retrieve an Id to be used before I insert it in the
public override void AcquireConnections(object Transaction)
{
connMgr = base.Connections.Connection;
conn = (SqlConnection)connMgr.AcquireConnection(null);
}
I get an exception here.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Any solutions?
For those that want to be able to do this in a Script Component:
Double Click the Script component to open the "Script Transformation Editor"
Click the "Connection Managers" list item.
Add a new Connection Manager. Select an existing ADO.NET connection manager.
Click on the "Script" list item and then the "Edit Script..." button.
You can do something like this inside your script:
using (SqlConnection connection = this.Connections.Connection.AcquireConnection(null) as SqlConnection)
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT [Value] FROM dbo.MyTable";
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ProfanityWords.Add(reader.GetValue(0).ToString());
}
}
}
this.Connections.Connection.ReleaseConnection(connection);
}
ADO.NET connection manger should be created and refer into the code to type cast to the SqlConnection. If you dont have the ADO.NET connection in your SSIS pakcage you will get the TypeCast exception. Following steps should be used if you want to use the SqlConnection.
Create the ADO.NET connection.
Use the following line in your code.
var connObj = Dts.Connections["ADO.NETConnectionName"].AcquireConnection(null);
var sqlConn = (SqlConnection)connObj;
Once you done with your SQL connection. Use the following code to Close/ Release your connection.
Dts.Connections["ADO.NETConnectionName"].ReleaseConnection(connObj);
Hope this helps.
I am developing an ASP.Net MVC 3 application using Entity Framework 4.1. For one of queries I am taking advantage of the SqlQuery method on the DbSet class which enables me to execute a raw SQL query that returns an entity list.
I have a method within my Service class, see below, where I write the raw sql and pass in two parameters, shiftID and shiftDateID.
public IList<User> GetAvailableLocums(int shiftID, int shiftDateID)
{
var query = #"set language 'British'
SELECT *
FROM [Shift]
WHERE shiftID = #p0
AND shiftDateID = #p1";
return _UoW.User.GetWithRawSql(query, shiftID, shiftDateID).ToList();
}
I then call the following method in my Repository class, see below,
public IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
I am worried that this might be open to a SQL Injection attack. If so, does anyone know how I can parametrize my two parameters?
Thanks for your help.
Have you seen this http://msdn.microsoft.com/en-us/library/bb738521.aspx? Second code block..
I've got a system which basically has to do a query like this:
SELECT * FROM MyTable WHERE #parameter.STIntersects(MyGeometryColumn)
This is quite simple to do when using vanilla SQL parameters, you just have to create your parameter in a non-typical way (where the builder variable is a SqlGeometryBuilder which I use to create a rectangle):
command.Parameters.Add(new SqlParameter
{
UdtTypeName = "geometry",
Value = builder.ConstructedGeometry,
ParameterName = "#paremeter"
});
Now, When I try to do this using dapper, I get an error that it can't figure out how to use this as a parameter. Anyone who has got this working, or any pointers on how to enable this? I do have a workaround, but that involves using the string representation and converting that to a geometry type in my SQL query. I really don't want that.
To answer the comment, the error I'm getting is 'The member Parameter of type Microsoft.SqlServer.Types.SqlGeometry cannot be used as a parameter value'. In other words, dapper doesn't know how to deal with a SqlGeometry object as a parameter.
The key to implementing weird and wonderful DB specific params all boils down to SqlMapper.IDynamicParameters
This simple interface has a single endpoint:
public interface IDynamicParameters
{
void AddParameters(IDbCommand command);
}
Dapper already has a DB generic implementation of this interface called: DynamicParameters which allows you to handle output and return values.
To emulate this spatial stuff I would try something like:
public class SpatialParam : SqlMapper.IDynamicParameters
{
string name;
object val;
public SpatialParam(string name, object val)
{
this.name = name;
this.val = val;
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
var sqlCommand = (SqlCommand)command;
sqlCommand.Parameters.Add(new SqlParameter
{
UdtTypeName = "geometry",
Value = val,
ParameterName = name
});
}
}
Usage:
cnn.Query("SELECT * FROM MyTable WHERE #parameter.STIntersects(MyGeometryColumn)",
new SpatialParam("#parameter", builder.ConstructedGeometry));
This simple implementation of the interface handles only a single param, but it can easily be extended to handle multiple params, either by passing in from the constructor or adding a helper AddParameter method.
If you don't mind modifying Dapper at its core then you can use what I've done... https://gist.github.com/brendanmckenzie/4961483
I modified Dapper to accept Microsoft.SqlServer.Types.SqlGeography parameters.
Dapper.EntityFramework 1.26 has support for DbGeography
Dapper 1.32 has inbuilt support for SqlGeography
Dapper 1.33 has inbuilt support for SqlGeometry
Dapper.EntityFramework 1.33 has inbuilt support for DbGeometry
Dapper 1.34 has inbuilt support for SqlHierarchyId
So with the latest libraries; it should simply work.