Wednesday, June 27, 2012

Sending big size (>2MB) file over WCF (bulking)

If you trying to send big file over WCF you need config  file on server and client, depends on direction.

But there is another way to do this - divide your file (pfd, txt, word and etc.) to packages  (bulks)

Following example in C# with WCF:

Client Sending file to server:


 var bulkSize = 2000000; //in kb
 var stillSize = originalPdf.Length; //original file size
 var globalCounter = 0;
 while (stillSize > 0)
 {                
    var newActualBulkSize = stillSize > bulkSize ? bulkSize : stillSize;
    var bulkArray = new byte[newActualBulkSize];
    for (var i = 0; i < (newActualBulkSize); i++)
    {
       bulkArray[i] = originalPdf[globalCounter++]; //creating small bulks of file
    }
                
     //sending to server small parts
     clientReference.TransferDocToServer(new DataTransferObject() 
                                              { DocBase64Array = bulkArray }, 
                                    stillSize > bulkSize ? false : true, originalPdf.Length);
 
     
stillSize -= bulkSize;
     
 }                        


Server Side Code:

private static readonly Dictionary<intbyte[]> Bulks = new Dictionary<intbyte[]>();
private static int _key; 

public void TransferDocToServer(DataTransferObject dataTransferObject, bool finishTransfer, int originalSize)
{            
    Bulks.Add(_key++, dataTransferObject.DocBase64Array);
    if (finishTransfer)
    {
       var originalPdf = CreatePdfAgain(originalSize);
       CreatePdfOnFileSystem(originalPdf);
       ClearObjects();               
    }                       
}
 
private static void ClearObjects()
{
    Bulks.Clear();
    _key = 0;
}
 
private static void CreatePdfOnFileSystem(byte[] originalPdf)
{
   using (Stream stream = new FileStream("c:/newFile.pdf"FileMode.Create))
   {
       stream.Write(originalPdf, 0, originalPdf.Length);
   }     
}

private byte[] CreatePdfAgain(int originalSize)
{
   var resultIndex = -1;
   var resultArrayForPdf = new byte[originalSize];
   foreach (var bytesBulk in Bulks)
   {
       foreach (byte t in bytesBulk.Value)
       {
           resultArrayForPdf[++resultIndex] = t;
       }
   }
 
   return resultArrayForPdf;
}

No comments:

Post a Comment