Showing posts with label socket programming. Show all posts
Showing posts with label socket programming. Show all posts

Saturday, October 20, 2012

Send File from Server to Client using C# Socket Programming 6/6



Server codes are here...



Server code:


using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace beginSocketServer
{
//FILE TRANSFER USING C#.NET SOCKET - SERVER
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("That program can transfer small file. I've test up to 850kb file");
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
//clientSock is the socket object of client, so we can use it now to transfer data to client
Socket clientSock = sock.Accept();


string fileName = "test.txt";// "Your File Name";
string filePath = @"C:\FT\";//Your File Path;
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);

byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);


clientSock.Send(clientData);
Console.WriteLine("File:{0} has been sent.", fileName);


clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("File Receiving fail." + ex.Message);
}
}
}
}

Send File from Server to Client using C# Socket Programming 4/6



6) Client Action: This section of code is retrieving file name length and by using this file name which was sent by server at the starting of file data. This will require retrieving file name.


int fileNameLen = BitConverter.ToInt32(clientData, 0);

string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);


7) Client Action: Now received data is saving at client side by using below lines of code with the help of binary stream writer.


BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append));

bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);


Here file data is starting to retrieve after file size and file name bytes. This has managed in 2nd line.


By that way one small file can be sent from server to client.


8) Client and Server Action: Now server and client both will do same activity; that is to release server and client socket by using close method of socket. Client needs to close binary stream writer as well.


So by following these steps a file can be sent from server to client. Same way we can send large file from server to client. TCP buffer can not handle large data size at a time. So if you try to send large file it will throw overflow error. To avoid this error you need to slice big file in small pieces (same thing has applied in 2GB file transfer article) and need to send one by one slice. So there will be loop to send file from server to client that means step 5 to step 7 will repeat.


Also server can send some particular file based on client request. But for that client need to send file name at the time of server request. So server can search file based on this information, so can read and send particular file to client.


By handling multiple clients objects one server can send file to multiple clients simultaneously but for that you need to create multithread application and need to keep track client socket object array with data file. So programming must be more complex. I am planning to write codes up to multiple client to client large file transfer with the help of one server application step by step. So keep watching my blog to learn new things.


Download this project from below link:

https://rapidshare.com/files/691859425/Client and Server - Send Small File from Server to Client.zip  



Send File from Server to Client using C# Socket Programming 3/6



4) Server Action: These codes are not directly related with socket programming. This is using to read and send file to client.


string fileName = "test.txt";// "Your File Name";

string filePath = @"C:\FT\";//Your File Path;

byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);


byte[] fileData = File.ReadAllBytes(filePath + fileName);

byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];

byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);


fileNameLen.CopyTo(clientData, 0);

fileNameByte.CopyTo(clientData, 4);

fileData.CopyTo(clientData, 4 + fileNameByte.Length);


These lines of code reading some particular file from local drive and string its data in byte array “clientData”. File data need to store in array with raw byte format to send these to client. With data file name size string at initial of file data. This is predefined between client and server and it needs to do, otherwise client will not get file name which is sending by server.


For my case I am using first four byte to represent file name length and form 5th byte file name is storing. So all file data will store after file name.


5) Server Action: Now file data is in byte array and it needs to send to client. The same thing is happening by using below code with the help of client socket (clientSock) object, which was created during client request acceptance.


clientSock.Send(clientData);


Basically server application task ends here for small file transfer. Remaining code has used for some decoration and socket closing related things.


5) Client Action: Now again turn comes to client and it will perform below tasks:


byte[] clientData = new byte[1024 * 5000];

string receivedPath = "C:/";


int receivedBytesLen = clientSock.Receive(clientData);


Here first two lines are just creating byte array to store server data and path is used to decide where data to be save. In my code, I am saving data in C: drive.


Last line is start receiving data from server. Whenever client socket starts receiving server data then it returns length of data which has captured in a integer variable.



Send File from Server to Client using C# Socket Programming 2/6



2) Client Action: Now turn is coming to client to request server.


IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");

IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);


clientSock.Connect(ipEnd);


These codes are from client application, here first two lines are using to get Localhost IP address and by using this creating new IPEnd point. Be sure there IP address and port number must be same as server address. I am running my applications in same machine so using localhost.


Next two lines of code is creating a socket object and trying to connect by using IPEnd point. So this socket object will try to connect server socket which was in listen mode.


3) Server Action: Again turn comes to server about to response on client’s request and this is doing by below line of code in server application:


Socket clientSock = sock.Accept();


This “sock” is server socket object which was created previously and it was in listen mode. This sock object will accept client request and generate a new socket object with name “clientSock”. Rest all work in server side will be performed by “clientSock” object to handle this particular client request.



Saturday, February 26, 2011

How to transfer Large File using C# Socket

-->
Now I will discuss about, how we can transfer a large file (file size in GB) using Microsoft dot net socket programming using C# (C sharp) language. This code has written in Visual Studio 2005 (dot net 2).

Source Code
https://drive.google.com/file/d/0Bwd4GP6MNsEgXy1ZZmxFdVFfS0U/view?usp=sharing


Basic Knowledge
To cover this article you need to read my few articles, these are –
1. Asynchronous Socket Server Programming for Beginner
2. Asynchronous Socket Client Programming for Beginner
3. File Transfer using C# Socket Programming
4. Split and Assemble large file (around 2GB) in C# dot net Programming

Steps
The basic code has covered in these article and that article basically comes by assembled these four. To transfer a large file from Client to Server I’ve followed these basic steps-
1) First read the file (slice wise) and store a slice data in a buffer (byte array). How a file can read slice wise, it has covered in my 4th article (Split and Assemble large file (around 2GB) in C#) in file split section. It’s required because TCP buffer is limited so if we try to send a large data then we will get TCP buffer overflow error.
2) Send these buffered data to server using TCP socket object. How it can be done, has covered in 3rd article (File Transfer using C# Socket programming). And for basic idea you can read article 1 & 2.
3) In server side when we starts to receive sliced data from client then we write these data in a file. How this can be done has covered in article 4 (Split and Assemble large file (around 2GB) in C#.net ), in file assemble section.

To receive file from Server to Client same process is applicable, just then server sends data by sliced and receive by Client in same way.

How to use DLL
In my code I have made these two functionality (server and client) in two separate class library (DLL file). By calling these two libraries (DLL file) any one can transfer data very easily. To do it need to follow these steps -
Step 1: Create Object
To use these dll to transfer data you need to create one client and one server object.
For client object -
SynchronusClient_ByteArr objClient = new SynchronusClient_ByteArr ("","localhost", @"C:\Documents and Settings\Administrator\UserData");
First argument for client id, if you keep it blank string then also ok, but when you use dll for multiple client (sender) to transfer multiple file to multiple client (receiver) then it’s mandatory. Otherwise file may goes to all user or different user. Next argument for server IP, and next for a temporary back up path, it’s require at file receive time from server.
Here and one more constructor with more argument there you can assign port no etc. Here default port is 8000 and 8001.
For Server object –
SyncSocketServerMulClient servObj = new SyncSocketServerMulClient();
If you use this code then server will load it’s default configuration, like port 8000 and 8001 and it’s default path to C: Other wise you can call overloaded method.

Step 2: Method & Properties
For server and client has some method which you need to call.
Client methods and properties are –
Picture 1 Picture 2
Picture 1 for Method and events of client object and Picture 2 for method and property of client class.
Hope from pic 1 you can understand everything very easily and from pic 2 also clear from it’s name. For ‘status’, it holds current status of client like, slicing data, sending data, receiving data etc and ‘progress’ it holds current % of data transfer currently done.
Server methods and properties are –
Picture 3 Picture 4
For pic 3 hope everything clear to you. But my comments here is, when you call start server then server starts and stays active as long as you call stop server. After call start server you can’t call it again before stop server call.
From pic 4 ‘bufferSize’ is for declare byte array length, you can define it as your self, ‘maxClientReceived’ for how many client can send or receive data at a time.
By using this code I’ve developed few large application, like text chat with smiles, file transfer, picture transfer, online drawing etc. Hope you will get a great experience by that code.
Download link
You can download source code from these two links-
http://alap.me/blog/All_Source_Codes.rar


Server Code is here :

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="">

Wednesday, November 26, 2008

Split and Assemble large file (around 2GB) in C# dot net Programming


Hi friends after a long time I’m back again. Now with a quite different coding flavor in different area. I will express about some operation with File. I will give some code to split and assemble large file. These codes can split up to 2 GB (approximately) file to any number of small file (minimum 1 MB) and also can assemble these small files to get the original file. Be sure that in assembling all small files need to keep in a folder otherwise it will fail to make original file and throw an error.

To do this in C# dot net , I’ve taken help of System.IO namespace and BinaryReader and BinaryWriter class. To learn about these classes please see msdn site. Here I’ve follow very simple algorithm.

For slice a file steps are:
(i) Open a large file in read mode by binary reader stream.
(ii) Execute step iii and step v, until file read reach at end of file.
(iii) Read from that stream and set these bytes in byte array
(iv) Make a new file name from original file name with slice number, for last file slice add ‘E’ after slice number.
(v) Save these bytes from array to a new file with ‘File’ class’s ‘WriteAllBytes’ method.
(vi) close the dot net binary stream.

Download source code from here:
http://alap.me/blog/All_Source_Codes.rar

These code as follows –

(i) BinaryReader br=new BinaryReader(File.Open(filename, FileMode.Open));

(ii) while (br.BaseStream.Length > sliceLen * counter)

(iii) br.BaseStream.Read(buffer, 0, sliceLen);
(iv) curFileName = filename + "." + counter.ToString();
curFileName = filename + "." + counter.ToString() + ".E";
(v) File.WriteAllBytes(curFileName, buffer);
(vi) br.Close();

For assemble these files need to follow these steps –

(i) Create a binary writer stream and open a binary file in append mode.
(ii) Execute from step iii to v
(iii) Generate file name in runtime depends on pervious file name.
(iv) Check for last file slice, last file slice name ends with last character ‘E’. If present file is the last slice then exit from that loop.
(v) Read all bytes from file and set in a byte array then write these byte data by binary writer.
(vi) Close the binary writer.

These code as follows-

(i) BinaryWriter bw = new BinaryWriter(File.Open(orgFile, FileMode.Append))
(ii) while(true)
(iii) nextFileName = orgFile + "." + counter.ToString();
(iv) if (File.Exists(nextFileName + ".E"))

(v) buffer = File.ReadAllBytes(nextFileName + ".E");
bw.Write(buffer);
(vii) bw.Close();

I’ve not covered everything in algorithm but I believe that you will understand these easily.

The complete codes are given below:

// File cutter assembler in microsoft c# dot net
//This code has written by Suman Biswas in 2008.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileCutter
{
//This class is used to call the actual file operation class.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "File cutter & assembler (upto 1.96 GB) by Suman Biswas";
}
FileHandling obj = new FileHandling();
private void btnSelectFile_Click(object sender, EventArgs e)
{

obj.SplitUp(SelectFile(),int.Parse(textBox1.Text));


}

private void button1_Click(object sender, EventArgs e)
{
obj.MargeUp(SelectFile());
}
private string SelectFile()
{
OpenFileDialog fbd = new OpenFileDialog();
if (fbd.ShowDialog() != DialogResult.OK)
{
MessageBox.Show("No file selected");
return "";
}
else
return fbd.FileName;
}
}

//Main file operation is done here.
class FileHandling
{
int sliceLen = 1024 * 1024;
int counter = 0;

public void SplitUp(string filename,int fileSizeInMB)
{
if (fileSizeInMB < slicelen =" 1024" counter =" 0;" buffer="new" br="new" slicelen =" (int)br.BaseStream.Length;"> sliceLen * counter)
{
if (br.BaseStream.Length > sliceLen * (counter + 1))
{
br.BaseStream.Read(buffer, 0, sliceLen);
curFileName = filename + "." + counter.ToString();
}
else
{
int remainLen = (int)br.BaseStream.Length - sliceLen * counter;
buffer = new byte[remainLen];
br.BaseStream.Read(buffer, 0, remainLen);
curFileName = filename + "." + counter.ToString() + ".E";
}

if (File.Exists(curFileName))
File.Delete(curFileName);

File.WriteAllBytes(curFileName, buffer);
counter++;
}
br.Close();
MessageBox.Show("File spilitted successfully");
}

public void MargeUp(string firstFileName)
{
if (firstFileName.Length < 1)
return;

string endPart = firstFileName;
string orgFile = "";

orgFile = endPart.Substring(0, endPart.LastIndexOf("."));
endPart = endPart.Substring(endPart.LastIndexOf(".") + 1);

if (endPart == "E")//If only one slice is there
{
orgFile = orgFile.Substring(0, orgFile.LastIndexOf("."));
endPart = "0";
}

if (File.Exists(orgFile))
{
if (MessageBox.Show(orgFile + " already exists, do you want to delete it", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
File.Delete(orgFile);
else
{
MessageBox.Show("File not assembled. Operation cancelled by user.");
return;
}
}

//Assembling starts from here
BinaryWriter bw = new BinaryWriter(File.Open(orgFile, FileMode.Append));
string nextFileName = "";
byte []buffer=new byte [bw.BaseStream.Length];


int counter=int.Parse(endPart);
while(true)
{
nextFileName = orgFile + "." + counter.ToString();
if (File.Exists(nextFileName + ".E"))
{
//Last slice
buffer = File.ReadAllBytes(nextFileName + ".E");
bw.Write(buffer);
break;
}
else
{
buffer = File.ReadAllBytes(nextFileName);
bw.Write(buffer);
}
counter++;
}
bw.Close();
MessageBox.Show("File assebled successfully");
}

}

}

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.