Missing assembly reference for SqlConnection - dapper

I'm still new to MVC and dapper ORM.
Suppose I use dapper for MVC and and when I try to build solution, it showing message:
'SqlConnection does not contain a definition for'Query' and no extension method 'Query' accepting a first argument of type 'SqlConnection'.
here is the code:
using System.Collections.Generic;
using System.Data.SqlClient;
public string Connectionstring = #"Data Source = KL - PT - 049\sqlexpress;Initial Catalog = Record; Integrated Security = True";
public IEnumerable<Customer> GetCustomers()
{
using (SqlConnection conn = new SqlConnection(Connectionstring))
{
conn.Open();
var customer = conn.**Query**<Customer>("Select * from Customer");
return customer;
}
my question is: does the Query above should be fine if I use that way? since I already use data.sqlClient reference?

Add
using Dapper;
at the top of the file.
Note: in recent versions of Visual Studio you can also just press ctrl+. on the unresolved extension method and it will offer to fix it for you:

Related

Failure to get a list of avaliable SQL Server instances using SqlDataSourceEnumerator

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
static void Main()
{
string conn = #"Data Source=(local)\SQLEXPRESS; Integrated Security=true;";
using (SqlConnection sqlConn = new SqlConnection(conn))
{
sqlConn.Open();
Console.WriteLine("State: {0}", sqlConn.State);
}
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
System.Data.DataRow[] rows = table.Select();
foreach (System.Data.DataRow row in rows)
{
Console.WriteLine(row["ServerName"]);
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
I have a single SQL Server Express instance running.
When I launch this program, it says "Status: Open" but fails to show the name of the server. Why might that be? I know for sure that there is one server up and running.
I picked (and adapted a little) the second half of the code from the MSDN page "SqlDataSourceEnumerator.Instance Property"
When I use a breakpoint to peek into the contents of rows[], I see that they are empty.
The program does not throw any errors, it just does not show the name of the server.

SQL Exception not handled in user code

The following error is occurring when i run my code below. I am running a user registration page with details such as first name, last name, user name, password ect. "ID" is my primary key. Error: "An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication_Assignment
{
public partial class User_Registration_WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_SubmitUserReg_Click(object sender, EventArgs e)
{
//Response.Write("Your registration is successful");
string sql = "SELECT * from User_Table where User_Name = #username";
using (SqlConnection connection = new SqlConnection("ConnectionString"))
using (SqlCommand command = new SqlCommand(sql, connection))
{
var userParam = new SqlParameter("username", SqlDbType.VarChar);
userParam.Value = TextBox_UserName.Text;
command.Parameters.Add(userParam);
var results = command.ExecuteReader();
}
Because you are not using parameters, you have a surname (lastname) that is almost certainly "O'Sullivan" See that single quote; it is causing the TSQL statement to be improperly formed.
If you concatenate strings you run into problems like this and open yourself up to SQL Injection attacks. Always use parameters.
Here's a simple example:
string sql = "SELECT * from employee where username = #username";
using (SqlConnection connection = new SqlConnection("connection string")
using (SqlCommand command = new SqlCommand(sql, connection))
{
var userParam = new SqlParameter("username", SqlDbType.VarChar);
userParam.Value = txtUsername.Text;
command.Parameters.Add(userParam);
var results = command.ExecuteReader();
}
There are numerous references to SQL Injections attacks on SO. Here's one example:
Why do we always prefer using parameters in SQL statements?

Change Connection String in App.config at runtime

The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)

How can I get SQL Server database properties from C# code?

I've a C# 4.0 console application and a SQL Server 2008 database up and running on database server.
Does somebody know if there is a way to get the database properties (like "Database Read-Only" ) from the C# code?
My guess is it should be, but I was not able to find out the accurate solution.
Thanks in advance
There are at least two ways to do it. One is to use the Database Metadata tables the other to use SQL Management objects in both cases there's lot of data there so you really need to know what you want. For example this is how you would get the "Database Read-Only" property you mentioned.
Using a SqlCommand against the MetaData
using (SqlConnection cnn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;"))
{
SqlCommand cmd = new SqlCommand("SELECT is_read_only FROM sys.filegroups",cnn);
cnn.Open();
var isReadOnly = cmd.ExecuteScalar();
Console.WriteLine(isReadOnly );
}
Using SMO
using System;
using Microsoft.SqlServer.Management.Smo;
namespace SMO_Test
{
class Program
{
static void Main(string[] args)
{
Server srv = new Server(); //Connection to the local SQL Server
Database db = srv.Databases["master"];
foreach (FileGroup fg in db.FileGroups)
{
Console.WriteLine(fg.ReadOnly);
}
}
}
}

Can we connect Sharepoint to SQL Server 6.5?

Not able to import application definition file!! Error: The metadata object with Name 'XYZ' and of Type 'LobSystemInstance' has a Property with Name 'DatabaseAccessProvider' that has either an invalid value or Type. Error was encountered at or just before Line: '10' and Position: '10'.
line 10 in ADF:
<"Property Name="DatabaseAccessProvider" Type="System.String">SqlOledb<"/Property>
Please give me ideas on how to display data from SQL Server 6.5 in Sharepoint?
The value of the node is invalid. You need to use SqlServer or OleDb. Check out this page for more information:
http://msdn.microsoft.com/en-us/library/ms550725(office.12).aspx
Im just starting on a similar task (so I found your unanswered question). I am trying to copy our documentation library in Sharepoint to an SQL db. Its not opening your file directly from SQL its using some c# code to setup a job which opens the sharepoint which may be what you are wanting.
There are two methods I have found so far:
One is to copy your data from sharepoint to a linked list in Access and then use the OLEDB methods in to open it.
Found here: C# Sync MS Access database to sql server
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
string connectionString = #"C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb";
using (DataTable dt = new DataTable())
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb;Jet OLEDB:Database Password=password";
//using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbConnection conn = new OleDbConnection(ConnStr))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
using (SqlConnection conn2 = new SqlConnection(connectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
The other is to use the Microsoft.Sharepoint libraries and open your sharepoint directly from the c# then copy it into your SQL.
Found here: http://www.dotnetspark.com/kb/3573-fetching-lists-from-sharepoint-2010-site.aspx
using (SharePointclientObj.ClientContext ctx = new SharePointclientObj.ClientContext(clientContext))
{
//Get the site
SharePointclientObj.Web site = ctx.Web;
ctx.Load(site);
//Get Lists
ctx.Load(site.Lists);
//Query
ctx.ExecuteQuery();
//Fill List
foreach (SharePointclientObj.List list in site.Lists)
{
Console.WriteLine(list.Title);
}
}

Resources