Learn step by step network programming using C#.Net socket, remoting, WCF and SignalR technology from lots of source code and description. All source code download link available at end of the blog post.
Saturday, October 20, 2012
Send File from Server to Client using C# Socket Programming 3/6
Saturday, February 26, 2011
How to transfer Large File using C# Socket
Source Code
https://drive.google.com/file/d/0Bwd4GP6MNsEgXy1ZZmxFdVFfS0U/view?usp=sharing
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ServerSockets.Synchronous.UsingByteArray
{
/// That server code will run to access multiple client requrest and response. Here will not any
/// Un-zip and Decript technology. Server will save all data in Encripted-Zipped form which will
/// sent by Client.
public class SyncSocketServerMulClient
{
public static bool isServerRunning=false;
public static int receivePort,sendPort, maxClientReceived, bufferSize;
//public static int progress=0 ;
public string outPath ;
public static string status="",presentOperation = "";
public string currentStatus = "";
public SyncSocketServerMulClient(int receivePort,int sendPort,int maxClient, string outPutPath)
{
SyncSocketServerMulClient.receivePort = receivePort;
SyncSocketServerMulClient.sendPort = sendPort;
SyncSocketServerMulClient.bufferSize = 10 * 1024;
SyncSocketServerMulClient.maxClientReceived = maxClient;
outPutPath = outPutPath.Replace("\\", "/");
if (outPutPath.Substring(outPutPath.Length - 1) != "/")
outPutPath += "/";
this.outPath = outPutPath;
SyncSocketServerMulClient.status = "";
//SyncSocketServerMulClient.progress = 0;
SyncSocketServerMulClient.presentOperation = "";
}
/// Default sets Receive Port:8080, Send Port:8081, Buffer Size:10KB, Max Client:100 and Out path: C:\
public SyncSocketServerMulClient()
{
SyncSocketServerMulClient.receivePort = 8080;
SyncSocketServerMulClient.sendPort = 8081;
SyncSocketServerMulClient.bufferSize = 10 * 1024;
SyncSocketServerMulClient.maxClientReceived = 100;
this.outPath = "c:/";
SyncSocketServerMulClient.status = "";
//SyncSocketServerMulClient.progress = 0;
SyncSocketServerMulClient.presentOperation = "";
}
#region SERVER SYNCHRONOUS SOCKET DATA RECEIVE
Thread threadReceiveServer, threadSendServer;
private void StartReceiveServer()
{
SyncSocketServerMulClient.isServerRunning = true;
threadReceiveServer = new Thread(new ThreadStart(this.StartReceiveServerThread));
threadReceiveServer.Start();
}
private void StopReceiveServer()
{
SyncSocketServerMulClient.isServerRunning = false;
//
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], SyncSocketServerMulClient.receivePort);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSock.Connect(ipEnd);
string strData = "END";
byte[] clientData = new byte[30];
clientData = Encoding.ASCII.GetBytes(strData);
clientSock.Send(clientData);
//byte[] serverData = new byte[10];
//int len = clientSock.Receive(serverData);
//Console.WriteLine(Encoding.ASCII.GetString(serverData, 0, len));
clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
//
}
Socket receiveSock,sendSock;
IPEndPoint ipEndReceive, ipEndSend;
private void StartReceiveServerThread()
{
ipEndReceive = new IPEndPoint(IPAddress.Any, SyncSocketServerMulClient.receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
receiveSock.Bind(ipEndReceive);
SyncSocketServerMulClient.isServerRunning = true;
receiveSock.Listen(maxClientReceived);
Console.WriteLine("Waiting for new client connection");
while (SyncSocketServerMulClient.isServerRunning)
{
Socket clientSock;
clientSock = receiveSock.Accept();
SyncSocketServerMulClient serObj = new SyncSocketServerMulClient(SyncSocketServerMulClient.receivePort, SyncSocketServerMulClient.sendPort, SyncSocketServerMulClient.bufferSize, this.outPath);
Thread newClient = new Thread(serObj.ReadDataFromClient);
newClient.Start(clientSock);
}
receiveSock.Close();
}
private void ReadDataFromClient(object clientObject)
{
Socket clientSock = null;
BinaryWriter bWriter=null;
string fileName = "";
try
{
SyncSocketServerMulClient.status = "";
SyncSocketServerMulClient.presentOperation = "";
clientSock = (Socket)clientObject;
bool flag = true;
Console.WriteLine("New connection estublished. Socket {0}", clientSock.GetHashCode());
int totalDataLen, receivedLen, fileNameLen, fileContentStartIndex;
byte[] data = new byte[bufferSize];
//DATA FORMAT: [FILE SIZE LEN INFO[0-3]][FILE NAME LEN INFO[4-7]][FILE NAME DATA][FILE CONTENT]
//GET FILE NAME, SIZE ETC.
currentStatus =presentOperation = "Data Receiving";
int len = clientSock.Receive(data);
if (len == 0)
{
clientSock.Close();
return;
}
if (len == 3)
{
string clientData = Encoding.ASCII.GetString(data);
if (clientData.Substring(0, len) == "END")
return;
}
totalDataLen = BitConverter.ToInt32(data, 0);
fileNameLen = BitConverter.ToInt32(data, 4);
fileName = Encoding.ASCII.GetString(data, 8, fileNameLen);
fileContentStartIndex = 4 + 4 + fileNameLen;
receivedLen = len - fileContentStartIndex;
//READ DATA & STORE OF FIRST PACKET
//DELETE IF FILE ALREADY EXIST
if (File.Exists(outPath + fileName))
File.Delete(outPath + fileName);
bWriter = new BinaryWriter(File.Open(outPath + fileName, FileMode.Append));
bWriter.Write(data, 0, len);
while (true)
{
if (receivedLen < len =" clientSock.Receive(data);" currentstatus ="presentOperation" currentstatus =" presentOperation" clientinfodata =" new" clientinfodata =" Encoding.ASCII.GetBytes(" status = "Access Denied by server end." status = "Address Already In Use." status = "Address Not Available." status = "Connection aborted by server." status = "Connection refused by server." status = "Connection Reset." status = "Destination Address Required." status = "Disconnecting." status = "Target Host is Down." status = "Target Host Not Found." status = "Target Host Unreachable." status = "In Progress." status = "Interrupted." status = "Invalid Argument." status = "Network Down." status = "Network Reset." status = "Network Unreachable." status = "No Buffer Space Available." status = "No Data." status = "Not Connected." status = "Not Initialized." status = "Not Socket." status = "Operation Aborted." status = "Socket already Shutdown." status = "Too Many Open Sockets." status = "Too Many Open Sockets." status = "Have some unknown problem in Socket." isserverrunning =" true;" threadsendserver =" new" ipendsend =" new" sendsock =" new" isserverrunning =" true;" clientsock =" sendSock.Accept();" serobj =" new" newclient =" new" clientsocket="(Socket)clientObject;" filenamewithpath = "" breader =" null;" status = "" clientdata =" new" clientdatalen =" clientSocket.Receive(clientData);" clientdatalen ="=" clientdatalen ="=" clientdatastr =" Encoding.ASCII.GetString(clientData);" clientidlen =" BitConverter.ToInt32(clientData," filenamelen=" BitConverter.ToInt32(clientData," clientid =" Encoding.ASCII.GetString(clientData," filename =" Encoding.ASCII.GetString(clientData," copiedfilename =" clientId" filenamewithpath =" this.outPath;" filenamewithpath =" fileNameWithPath.Replace(" length ="=" currentstatus =" presentOperation" breader =" new" data =" new" sentdatasize =" (int)bReader.BaseStream.Length;" data =" new" sentdatasize =" bufferSize;" totalsentdataslot =" 1;" totaldatasize =" (int)bReader.BaseStream.Length;" progress =" (int)(((float)sentDataSize" progress =" (int)(((float)sentDataSize" enddata =" new" sentdatasize =" (int)bReader.BaseStream.Length;" progress =" (int)(((float)sentDataSize" currentstatus =" presentOperation" strfleerr = "ERROR" tempfleerrarr =" Encoding.ASCII.GetBytes(strFleErr);" currentstatus =" presentOperation" status = "Access Denied by server end." status = "Address Already In Use." status = "Address Not Available." status = "Connection aborted by server." status = "Connection refused by server." status = "Connection Reset." status = "Destination Address Required." status = "Disconnecting." status = "Target Host is Down." status = "Target Host Not Found." status = "Target Host Unreachable." status = "In Progress." status = "Interrupted." status = "Invalid Argument." status = "Network Down." status = "Network Reset." status = "Network Unreachable." status = "No Buffer Space Available." status = "No Data." status = "Not Connected." status = "Not Initialized." status = "Not Socket." status = "Operation Aborted." status = "Socket already Shutdown." status = "Too Many Open Sockets." status = "Too Many Open Sockets." status = "Have some unknown problem in Socket." status =" ex.Message;" isserverrunning =" false;" ipaddress =" Dns.GetHostAddresses(" ipend =" new" clientsock =" new" strdata = "END" clientdata =" new" clientdata =" Encoding.ASCII.GetBytes(strData);" serverdata =" new" len =" clientSock.Receive(serverData);" style="font-weight: bold; color: rgb(51, 51, 255);" size="4">Client Code is here:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace ClientSockets.Synchronous.UsingByteArray // SyncScoketClient_ByteArr_Dll
{
/// Client open a syncronous socket and send file to server, here asynchronous mode becomes by
/// Threading, and here uses Byte Array to transfer data.
public class SynchronusClient_ByteArr
{
public delegate void FileSendCompletedDelegate();
public event FileSendCompletedDelegate FileSendCompleted, FileReceiveCompleted;
public static int progress = 0, portSend, portReceive;
int bufferSize;
public static string status = "", presentOperation = "", ipAddress, outPathDefault = "";
private static string outPathUserSelected = "";
string clientId = "";
string fileNameWithPath;
public static bool isSaveToDefaultPath = false;
static int totalSentDataSlot;
public SynchronusClient_ByteArr(string clientId, string ipAddress, int sendPort, int receivePort, string DefaultPath)
{
this.clientId = clientId;
SynchronusClient_ByteArr.ipAddress = ipAddress;
SynchronusClient_ByteArr.portSend = sendPort;
SynchronusClient_ByteArr.portReceive = receivePort;
SynchronusClient_ByteArr.outPathDefault = DefaultPath;
this.bufferSize = 10 * 1024;
}
/// Conestructor of Client Object
public SynchronusClient_ByteArr(string clientId, string ipAddress, string DefaultPath)
{
this.clientId = clientId;
outPathDefault = DefaultPath;
SynchronusClient_ByteArr.ipAddress = ipAddress;
SynchronusClient_ByteArr.portSend = 8080;
SynchronusClient_ByteArr.portReceive = 8081;
this.bufferSize = 10 * 1024;
}
Thread startFileTransferThread, startFileReceiveThread;
public string SendFileToServer( string senderId, string receiverId)
{
string newFileName, onlyFileName, path;
//Select a File to transfer
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() != DialogResult.OK)
return "Cancelled by user";
string fileNameWithPath = ofd.FileName;
fileNameWithPath = fileNameWithPath.Replace("\\", "/");
onlyFileName = fileNameWithPath;
path = "";
while (onlyFileName.IndexOf("/") != -1)
{
path += onlyFileName.Substring(0, onlyFileName.IndexOf("/")) + "/";
onlyFileName = onlyFileName.Substring(onlyFileName.IndexOf("/") + 1);
}
newFileName = senderId + "#" + onlyFileName;
//File.Copy(fileNameWithPath, path + "/" + newFileName,true);
//File.SetAttributes(path + "/" + newFileName, FileAttributes.Hidden);
string bothName = fileNameWithPath + "?" + path + "/" + newFileName;
startFileTransferThread = new Thread(this.SendFileToServerByThread);
startFileTransferThread.Start(bothName);
//NEW FILE NAME IS NOW IN IT'S OWN EXTENSION NEED TO CHANGE .sjb FORM
//Only file name
int k = newFileName.Length - 1;
while (newFileName.Substring(k, 1) != ".")
{
k--;
}
newFileName = newFileName.Substring(0, k);
newFileName = newFileName + ".sjb";
return newFileName;
}
private void SendFileToServerByThread(object fileNameWithPathObj)
{
Socket server = null;
BinaryReader bReader = null;
string newFileName = "";
try
{
//BUILD A COPY OF SENDING FILE
string oldFileName, bothFileName;
bothFileName = fileNameWithPathObj.ToString();
oldFileName = bothFileName.Substring(0, bothFileName.IndexOf("?"));
newFileName = bothFileName.Substring(bothFileName.IndexOf("?") + 1);
string filePath = "", tempFileName = oldFileName;
while (tempFileName.IndexOf("/") != -1)
{
filePath += tempFileName.Substring(0, tempFileName.IndexOf("/") + 1);
tempFileName = tempFileName.Substring(tempFileName.IndexOf("/") + 1);
}
if (File.Exists(newFileName))
File.Delete(newFileName);
File.Copy(oldFileName, newFileName, true);
File.SetAttributes(newFileName, FileAttributes.Hidden);
status = "";
this.fileNameWithPath = newFileName;
//presentOperation = "Data Compressing";
//this.fileNameWithPath = ZipUnzip.LZO_Algorithm.LZO.Compress(this.fileNameWithPath);
//File.SetAttributes(filePath + this.fileNameWithPath, FileAttributes.Hidden);
if (this.fileNameWithPath.Length == 0)
return;
this.fileNameWithPath = filePath + tempFileName;// this.fileNameWithPath;
presentOperation = "Data Sending";
IPAddress[] serverIp = Dns.GetHostAddresses(SynchronusClient_ByteArr.ipAddress);
IPEndPoint ipEnd = new IPEndPoint(serverIp[0], SynchronusClient_ByteArr.portSend);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
server.Connect(ipEnd);
int sentDataSize;
byte[] data;// = new byte[bufferSize];
bReader = new BinaryReader(File.Open(fileNameWithPath, FileMode.Open));
if (bReader.BaseStream.Length <= bufferSize) { data = new byte[bReader.BaseStream.Length]; bReader.Read(data, 0, (int)bReader.BaseStream.Length); sentDataSize = (int)bReader.BaseStream.Length; } else { data = new byte[bufferSize]; bReader.Read(data, 0, bufferSize); sentDataSize = bufferSize; } string onlyFileName; fileNameWithPath = fileNameWithPath.Replace("\\", "/"); onlyFileName = fileNameWithPath; while (onlyFileName.IndexOf("/") != -1) onlyFileName = onlyFileName.Substring(onlyFileName.IndexOf("/") + 1); //DATA FORMAT: [FILE SIZE LEN INFO[0-3]][FILE NAME LEN INFO[4-7]][FILE NAME DATA][FILE CONTENT] byte[] dataLenBytes = BitConverter.GetBytes((int)bReader.BaseStream.Length); byte[] fileNameLenBytes = BitConverter.GetBytes(onlyFileName.Length); byte[] fileNameBytes = Encoding.ASCII.GetBytes(onlyFileName); byte[] allData = new byte[8 + fileNameBytes.Length + data.Length]; //MAKE FIRST PACKET TO SERVER WITH FILE SIZE & FILE NAME dataLenBytes.CopyTo(allData, 0); fileNameLenBytes.CopyTo(allData, 4); fileNameBytes.CopyTo(allData, 8); data.CopyTo(allData, 8 + fileNameBytes.Length); //SEND FIRST PACKET TO SERVER server.Send(allData); totalSentDataSlot = 1; int totalDataSize = (int)bReader.BaseStream.Length; progress = (int)(((float)sentDataSize / totalDataSize) * 100); while (sentDataSize < progress =" (int)(((float)sentDataSize" enddata =" new" sentdatasize =" (int)bReader.BaseStream.Length;" progress =" (int)(((float)sentDataSize" receivedata =" new" recvlen =" server.Receive(receiveData);" presentoperation = "Data Sending Completed" status = "Access Denied by server end." status = "Address Already In Use." status = "Address Not Available." status = "Connection aborted by server." status = "Connection refused by server." status = "Connection Reset." status = "Destination Address Required." status = "Disconnecting." status = "Target Host is Down." status = "Target Host Not Found." status = "Target Host Unreachable." status = "In Progress." status = "Interrupted." status = "Invalid Argument." status = "Network Down." status = "Network Reset." status = "Network Unreachable." status = "No Buffer Space Available." status = "No Data." status = "Not Connected." status = "Not Initialized." status = "Not Socket." status = "Operation Aborted." status = "Socket already Shutdown." status = "Too Many Open Sockets." status = "Too Many Open Sockets." status = "Have some unknown problem in Socket." status =" ex.Message;" fbd =" new" outpathuserselected =" fbd.SelectedPath;" startfilereceivethread =" new" outpathuserselected =" ReceivePath;" startfilereceivethread =" new" server =" null;" bwriter =" null;" rcvfilename = "" filename = "" status = "" onlyfilename =" onlyFileNameObj.ToString();" presentoperation = "Data Compressing" length ="=" clientid =" DateTime.Now.Ticks.ToString();" clientidlenbytes =" BitConverter.GetBytes(clientId.Length);" clientidbytes =" Encoding.ASCII.GetBytes(clientId);" filenamelenbytes =" BitConverter.GetBytes(onlyFileName.Length);" filenamebytes =" Encoding.ASCII.GetBytes(onlyFileName);" alldata =" new" presentoperation = "Data Sending" serverip =" Dns.GetHostAddresses(SynchronusClient_ByteArr.ipAddress);" ipend =" new" server =" new" status = "" progress =" 0;" presentoperation = "" server =" (Socket)clientObject;" flag =" true;" data =" new" presentoperation = "Data Receiving" len =" server.Receive(data);" len ="=" strtemp =" Encoding.ASCII.GetString(data," strtemp ="=" status = "File yet not sent by Sender" presentoperation = "Data Receiving Not Started" progress =" 0;" totaldatalen =" BitConverter.ToInt32(data," filenamelen =" BitConverter.ToInt32(data," filename =" Encoding.ASCII.GetString(data," filecontentstartindex =" 4" receivedlen =" len;//" outpathdefault =" outPathDefault.Replace(" outpathuserselected =" outPathUserSelected.Replace(" fbd =" new" bwriter =" new" bwriter =" new" bwriter =" new" progress =" (int)(((float)receivedLen" len =" server.Receive(data);" val =" (float)receivedLen" progress =" (int)(((float)receivedLen" presentoperation = "Data Decompressing" rcvfilename =" ZipUnzip.LZO_Algorithm.LZO.Decompress(outPathDefault" rcvfilename =" ZipUnzip.LZO_Algorithm.LZO.Decompress(outPathUserSelected" orgfilename =" rcvFileName=" orgfilename =" orgFileName.Substring(orgFileName.IndexOf(" isserverrunning =" false;" presentoperation = "Data Receiving Completed" progress =" 100;" status = "Access Denied by server end." status = "Address Already In Use." status = "Address Not Available." status = "Connection aborted by server." status = "Connection refused by server." status = "Connection Reset." status = "Destination Address Required." status = "Disconnecting." status = "Target Host is Down." status = "Target Host Not Found." status = "Target Host Unreachable." status = "In Progress." status = "Interrupted." status = "Invalid Argument." status = "Network Down." status = "Network Reset." status = "Network Unreachable." status = "No Buffer Space Available." status = "No Data." status = "Not Connected." status = "Not Initialized." status = "Not Socket." status = "Operation Aborted." status = "Socket already Shutdown." status = "Too Many Open Sockets." status = "Too Many Open Sockets." status = "Have some unknown problem in Socket." status =" ex.Message;" style="">
Friday, April 11, 2008
Run any Stored Procedure from .Net - version 2
Please change "(less than)" with it's sign.
In my last article I found some limitation and this code also quite large so I’ve write it’s modified code to run stored procedure. It’s more powerful and comparatively very low code and use is also very easy.
When you run a stored procedure by that code you need to call one function to run specific stored procedure and for every argument need to call just a function. Also here I’ve handle arraylist internally which was need to use externally by you. Also you can use ADO.Net ’s enum to provide table’s field data type and parameter direction also you can use ado.net enum.
Hove ever I’m giving one sample code which you need to write. It’s very easy, just create an object of that class, then invoke these functions. Codes are below:
Create object.
ExecSpClass objSp = new ExecSpClass("Connection string write here");
Pass arguments:
objSp.AddArgument("@nextName", "Suman Biswas", SqlDbType.VarChar, ParameterDirection.Input);
objSp.AddArgument("@id", "2",SqlDbType.Int,ParameterDirection.Input);
Now execute stored procedure:
objSp.ExecSpNonQuery("spProjectCategoryAdd");
Code is complete from your side to run a stored procedure.
I’m giving my code below which is doing the actual work, to learn it you can read it, I think it’s quite easy to understand.
public class ExecSpClass
{
internal class SPArgBuild
{
internal string parameterName = "";
internal string parameterValue = "";
internal SqlDbType pramValueType;
internal ParameterDirection parmDirection;
internal SPArgBuild(string pramName, string pramValue, SqlDbType pramValueType, ParameterDirection parmDirection )
{
this.parameterName = pramName;
this.parameterValue = pramValue;
this.pramValueType = pramValueType;
this.parmDirection = parmDirection;
}
}
SqlConnection conn;
SqlCommand cmd;
SqlDataAdapter adap;
ArrayList spPramArrList = new ArrayList();
public ExecSpClass(string dbConnStr)
{
conn = new SqlConnection(dbConnStr);
}
private void OpenConection()
{
cmd = new SqlCommand();
adap = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
if (conn.State == ConnectionState.Closed ||
conn.State == ConnectionState.Broken ||
conn.State == ConnectionState.Connecting ||
conn.State != ConnectionState.Executing ||
conn.State != ConnectionState.Fetching ||
conn.State != ConnectionState.Open)
{
conn.Open();
}
}
private void CloseConnection()
{
if (conn.State != ConnectionState.Closed ||
conn.State == ConnectionState.Broken ||
conn.State == ConnectionState.Connecting ||
conn.State != ConnectionState.Executing ||
conn.State != ConnectionState.Fetching ||
conn.State == ConnectionState.Open)
{
conn.Close();
cmd.Dispose();
adap.Dispose();
}
}
public void AddArgument(string spParmName, string spParmValue, SqlDbType spPramValueType, ParameterDirection parmDirection)
{
SPArgBuild spArgBuiltObj = new SPArgBuild(spParmName, spParmValue, spPramValueType,parmDirection);
spPramArrList.Add(spArgBuiltObj);
}
public DataTable ExecSpGetDataTable(string spName)
{
string spPramName = "";
string spPramValue = "";
SqlDbType spPramDataType;
DataSet ds=new DataSet();
OpenConection();
cmd.CommandText = spName;
for (int i = 0; i (less than) spPramArrList.Count; i++)
{
spPramName = ((SPArgBuild)spPramArrList[i]).parameterName;
spPramValue = ((SPArgBuild)spPramArrList[i]).parameterValue;
spPramDataType = ((SPArgBuild)spPramArrList[i]).pramValueType;
SqlParameter pram = null;
pram = cmd.Parameters.Add(spPramName, spPramDataType);
pram.Value = spPramValue;
pram.Direction = ((SPArgBuild)spPramArrList[i]).parmDirection;
}
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(ds);
CloseConnection();
return ds.Tables[0];
}
public string ExecSpScalar(string spName)
{
string spPramName = "";
string spPramValue = "";
OpenConection();
cmd.CommandText = spName;
SqlDbType spPramDataType;
for (int i = 0; i (less than) spPramArrList.Count; i++)
{
spPramName = ((SPArgBuild)spPramArrList[i]).parameterName;
spPramValue = ((SPArgBuild)spPramArrList[i]).parameterValue;
spPramDataType = ((SPArgBuild)spPramArrList[i]).pramValueType;
SqlParameter pram = null;
pram = cmd.Parameters.Add(spPramName, spPramDataType);
pram.Value = spPramValue;
pram.Direction = ((SPArgBuild)spPramArrList[i]).parmDirection;
}
string noRowEfect = cmd.ExecuteScalar().ToString();
CloseConnection();
return noRowEfect;
}
public int ExecSpNonQuery(string spName)
{
string spPramName = "";
string spPramValue = "";
OpenConection();
cmd.CommandText = spName;
SqlDbType spPramDataType ;
for (int i = 0; i (less than) spPramArrList.Count; i++)
{
spPramName = ((SPArgBuild)spPramArrList[i]).parameterName;
spPramValue = ((SPArgBuild)spPramArrList[i]).parameterValue;
spPramDataType = ((SPArgBuild)spPramArrList[i]).pramValueType;
SqlParameter pram = null;
pram = cmd.Parameters.Add(spPramName, spPramDataType);
pram.Value = spPramValue;
pram.Direction = ((SPArgBuild)spPramArrList[i]).parmDirection;
}
int noRowEfect= cmd.ExecuteNonQuery();
CloseConnection();
return noRowEfect;
}
}
If you get any problem to run that code or understand please contact with me.
Saturday, February 23, 2008
Run any Stored Procedure from .Net
Hi, Now I’m far from socket now Im giving some code with .Net and SQL Server related code, that code will help any one to run stored procedure, very easyly with little code. Now follow these code.
Create a table to test the stored procedure, I’m giving one example:
CREATE TABLE client(
id int IDENTITY(1,1) NOT NULL,
Name varchar(64) NULL,
jdate datetime NULL
)
Then insert some data into that table.
INSERT INTO client(Name,jdate)VALUES ('Taniya',getdate())
INSERT INTO client(Name,jdate)VALUES ('Jhuma',getdate())
INSERT INTO client(Name,jdate)VALUES ('Ganesh',getdate())
Then create a stored procedure to test my class, here I’m creating a stored procedure (sp) to update some data based on client id. Here store procedure’s parameters are @nextName and @id. Code is giving here:
create procedure UpdateName ( @nextName varchar(256), @id int )
as
update client set name=@nextName where id=@id
Now sql server data base related job is done. Now will to c# related code.
First giving the code by that my class will be accessed to run that stored procedure. Just note that code, only that code will be required to run any stored procedure.
public class RunSP
{
/// *summary$
/// Run Store Procedure.
/// */summary$
/// *param name="cnnStr"$Connection String of SQL server*/param$
public static void RunSP(string cnnStr)
{
//Create a array list to store parameter(s) with
//parameter name, value & data type.
ArrayList arLst = new ArrayList();
//Now send array list name, value & varchar, persingle
//call of that function will create one stored parameter.
SP.spArgumentsCollection(arLst, "@nextName", "Suman Biswas", "varchar");
SP.spArgumentsCollection(arLst, "@id", "2", "int");
//Now run stored procedure.
SP.RunStoredProcedure(cnnStr, "UpdateName", arLst);
}
}
Here the actual class to run stored procedure, you can make all dll file by that code and then easily use this. Codes are below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
//That code has written by Suman Biswas, that code is running fine at my testing,
//if any one get any problem please inform me. My email is sumanbiswas@aol.in
namespace StoredProcedureLib
{
/// *summary$
/// This class helps to built SP argument. It can use directly to any SP. Created by Suman Biswas on 23rd Frb 2007.
/// */summary$
public class SP
{
internal class SPArgBuild
{
internal string parameterName = "";
internal string parameterValue = "";
/// *summary$
/// Write full data type, such as SqlDBType.VarChar.
/// */summary$
internal string pramValueType = "";
/// *summary$
/// Use to create SP Argument Build conestruction.
/// */summary$
/// *param name="pramName"$SP Argument Parameter Name.*/param$
/// *param name="pramValue"$SP Argument Parameter Value.*/param$
internal SPArgBuild(string pramName, string pramValue, string pramValueType)
{
this.parameterName = pramName;
this.parameterValue = pramValue;
this.pramValueType = pramValueType;
}
}
/// *summary$
/// This function built an Array List, which is collection of some SP parameter's Name, Value and Data type.
/// */summary$
/// *param name="arrLst"$Array List which will store all argument.*/param$
/// *param name="spParmName"$SP Argument Parameter Name.*/param$
/// *param name="spParmValue"$SP Argument Parameter Value.*/param$
/// *param name="spPramValueType"$Parameter value type EXACTLY same as SqlDBType. E.g. 'SqlDbType.BigInt' will 'BigInt'. */param$
/// *returns$*/returns$
public static ArrayList spArgumentsCollection(ArrayList arrLst, string spParmName, string spParmValue, string spPramValueType)
{
SPArgBuild spArgBuiltObj = new SPArgBuild(spParmName, spParmValue, spPramValueType);
arrLst.Add(spArgBuiltObj);
return arrLst;
}
/// *summary$
/// Run a stored procedure of Select SQL type.
/// */summary$
/// *param name="dbConnStr"$Connection String to connect Sql Server*/param$
/// *param name="ds"$DataSet which will return after filling Data*/param$
/// *param name="spName"$Stored Procedure Name*/param$
/// *param name="spPramArrList"$Parameters in ArrayList*/param$
/// *returns$Return DataSet after filing data by SQL.*/returns$
public static DataSet RunStoredProcedure(string dbConnStr, DataSet ds, string spName, ArrayList spPramArrList)
{
SqlConnection conn = new SqlConnection(dbConnStr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = spName;
string spPramName = "";
string spPramValue = "";
string spPramDataType = "";
for (int i = 0; i * spPramArrList.Count; i++)
{
spPramName = ((SPArgBuild)spPramArrListi).parameterName;
spPramValue = ((SPArgBuild)spPramArrListi).parameterValue;
spPramDataType = ((SPArgBuild)spPramArrListi).pramValueType;
SqlParameter pram = null;
#region SQL DB TYPE AND VALUE ASSIGNMENT
switch (spPramDataType.ToUpper())
{
case "BIGINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.BigInt);
pram.Value = spPramValue;
break;
case "BINARY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Binary);
pram.Value = spPramValue;
break;
case "BIT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Bit);
pram.Value = spPramValue;
break;
case "CHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Char);
pram.Value = spPramValue;
break;
case "DATETIME":
pram = cmd.Parameters.Add(spPramName, SqlDbType.DateTime);
pram.Value = spPramValue;
break;
case "DECIMAL":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Decimal);
pram.Value = spPramValue;
break;
case "FLOAT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Float);
pram.Value = spPramValue;
break;
case "IMAGE":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Image);
pram.Value = spPramValue;
break;
case "INT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Int);
pram.Value = spPramValue;
break;
case "MONEY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Money);
pram.Value = spPramValue;
break;
case "NCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NChar);
pram.Value = spPramValue;
break;
case "NTEXT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NText);
pram.Value = spPramValue;
break;
case "NVARCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NVarChar);
pram.Value = spPramValue;
break;
case "REAL":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Real);
pram.Value = spPramValue;
break;
case "SMALLDATETIME":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallDateTime);
pram.Value = spPramValue;
break;
case "SMALLINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallInt);
pram.Value = spPramValue;
break;
case "SMALLMONEY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallMoney);
pram.Value = spPramValue;
break;
case "TEXT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Text);
pram.Value = spPramValue;
break;
case "TIMESTAMP":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Timestamp);
pram.Value = spPramValue;
break;
case "TINYINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.TinyInt);
pram.Value = spPramValue;
break;
case "UDT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Udt);
pram.Value = spPramValue;
break;
case "UMIQUEIDENTIFIER":
pram = cmd.Parameters.Add(spPramName, SqlDbType.UniqueIdentifier);
pram.Value = spPramValue;
break;
case "VARBINARY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.VarBinary);
pram.Value = spPramValue;
break;
case "VARCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.VarChar);
pram.Value = spPramValue;
break;
case "VARIANT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Variant);
pram.Value = spPramValue;
break;
case "XML":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Xml);
pram.Value = spPramValue;
break;
}
#endregion
pram.Direction = ParameterDirection.Input;
}
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(ds);
return ds;
}
/// *summary$
/// Run a stored procedure which will execure some nonquery SQL.
/// */summary$
/// *param name="dbConnStr"$Connection String to connect Sql Server*/param$
/// *param name="spName"$Stored Procedure Name*/param$
/// *param name="spPramArrList"$Parameters in a ArrayList*/param$
public static void RunStoredProcedure(string dbConnStr, string spName, ArrayList spPramArrList)
{
SqlConnection conn = new SqlConnection(dbConnStr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = spName;
string spPramName = "";
string spPramValue = "";
string spPramDataType = "";
for (int i = 0; i * spPramArrList.Count; i++)
{
spPramName = ((SPArgBuild)spPramArrListi).parameterName;
spPramValue = ((SPArgBuild)spPramArrListi).parameterValue;
spPramDataType = ((SPArgBuild)spPramArrListi).pramValueType;
SqlParameter pram = null;
#region SQL DB TYPE AND VALUE ASSIGNMENT
switch (spPramDataType.ToUpper())
{
case "BIGINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.BigInt);
pram.Value = spPramValue;
break;
case "BINARY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Binary);
pram.Value = spPramValue;
break;
case "BIT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Bit);
pram.Value = spPramValue;
break;
case "CHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Char);
pram.Value = spPramValue;
break;
case "DATETIME":
pram = cmd.Parameters.Add(spPramName, SqlDbType.DateTime);
pram.Value = spPramValue;
break;
case "DECIMAL":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Decimal);
pram.Value = spPramValue;
break;
case "FLOAT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Float);
pram.Value = spPramValue;
break;
case "IMAGE":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Image);
pram.Value = spPramValue;
break;
case "INT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Int);
pram.Value = spPramValue;
break;
case "MONEY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Money);
pram.Value = spPramValue;
break;
case "NCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NChar);
pram.Value = spPramValue;
break;
case "NTEXT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NText);
pram.Value = spPramValue;
break;
case "NVARCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.NVarChar);
pram.Value = spPramValue;
break;
case "REAL":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Real);
pram.Value = spPramValue;
break;
case "SMALLDATETIME":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallDateTime);
pram.Value = spPramValue;
break;
case "SMALLINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallInt);
pram.Value = spPramValue;
break;
case "SMALLMONEY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.SmallMoney);
pram.Value = spPramValue;
break;
case "TEXT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Text);
pram.Value = spPramValue;
break;
case "TIMESTAMP":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Timestamp);
pram.Value = spPramValue;
break;
case "TINYINT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.TinyInt);
pram.Value = spPramValue;
break;
case "UDT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Udt);
pram.Value = spPramValue;
break;
case "UMIQUEIDENTIFIER":
pram = cmd.Parameters.Add(spPramName, SqlDbType.UniqueIdentifier);
pram.Value = spPramValue;
break;
case "VARBINARY":
pram = cmd.Parameters.Add(spPramName, SqlDbType.VarBinary);
pram.Value = spPramValue;
break;
case "VARCHAR":
pram = cmd.Parameters.Add(spPramName, SqlDbType.VarChar);
pram.Value = spPramValue;
break;
case "VARIANT":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Variant);
pram.Value = spPramValue;
break;
case "XML":
pram = cmd.Parameters.Add(spPramName, SqlDbType.Xml);
pram.Value = spPramValue;
break;
}
#endregion
pram.Direction = ParameterDirection.Input;
}
cmd.ExecuteNonQuery();
}
}
}