Monday, April 27, 2015

Update memory stream contains Zip file using .NET 4.5 and above OR Unzip memory stream using Zip Archive .NET 4.5.

I am showing one example below where I have to update my zip file in the WCF service and return back with modified zip file to end user.  Microsoft .NET 4.5 frame work, IO compression library can be used to Zip and Unzip files.


I have one zip file contains 5 or more images, I have to use  those images and generate one HTML file, add into same zip file and return back zip file with one extra file.

Workflow to understand steps

C# Client Code


using System.IO;


//Input file contain 5 image file
const string inputFile = @"C:\TEMP\";

//Output file will contain 5 image and 1 Html file
const string outputFile = @"C:\TEMP\";

Button event Code

private void button1_Click(object sender, EventArgs e)
   //create date object to count time taken in second
   DateTime dt1 = DateTime.Now;

   //Convert file into byte array
   byte[] docOutPut = File.ReadAllBytes(inputFile);

   //create WCF service instance
   var client = new ServiceReference1.Service1Client();

   //Call WCF service method and get byte array
   byte[] returnModifiedZipFile = client.UpdateZipFile(docOutPut);

   //convert byte array into memory stream
   Stream stream = new MemoryStream(returnModifiedZipFile);
   //Create new zip file and write memory stream into it
   using (var fileStream = new FileStream(outputFile, FileMode.Create))
      stream.Seek(0, SeekOrigin.Begin);

      lblHTML.Text = (DateTime.Now - dt1).Seconds + " Seconds";

WCF Service method code


using System.IO;
using System.IO.Compression;

Add Reference to your WCF project


WCF Method Code

public byte[] UpdateZipFile(byte[] ZipFileInputFile)
   //open Memory Stream
   using (var memoryStream = new MemoryStream())

//Write byte array into memory stream to avoid “Memory Stream exception–Memory //stream is not expandable” error

      memoryStream.Write(ZipFileInputFile, 0, ZipFileInputFile.Length);
      //use Zip Archive and open memory stream in update mpde
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Update, true))
          //create new file
          var outPutFile = archive.CreateEntry("NewFile.html");
          //open new file to write
          using (var entryStream = outPutFile.Open())                   
          //create stream writer and write content into new file
          using (var streamWriter = new StreamWriter(entryStream))
             // read files how many files present into the zip file
             for (int entry = 0; entry < archive.Entries.Count - 1; entry++)
                //use file name present into the zip file
streamWriter.Write(string.Format("<img src= \"{0}\" width=\"100%\" />", archive.Entries[entry].FullName));
           //convert memory stream into array and retun
           return memoryStream.ToArray();

To configure config file please see below article


To know more about Zip Archive and other IO Compression utility see below

Error:Cannot write configuration file, Visual Studio 2013

Friday, April 17, 2015

Understand Dependency Injection with C# code example

Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. It can be implemented by constructor injection, setter injection or method injection.
To understand DI you need to understand how and why DI pattern introduced. Following terms are the main factor for complete understanding of DI.  
  • Dependency
  • Dependency Inversion Principle
  • Inversion of Control (IoC)
Below diagram will depicts the differences between these terms, it's pros and cons and complete journey. code will help to understand this patterns easily.

Main advantages of using DI patterns
  • Create loosely couple class, reduces class coupling
  • Improves application testing, Classes can be tested individually, Class can be mock easily.,  
  • Increases code re-usability
  • Improves code maintainability
  • Increase application scalability
Dependency injection can be done in three ways.
  • Constructor injection
  • Method injection
  • Property injection
In below diagram I have described the Constructor injection, other example can be seen in below links
Microsoft provide better framework called unity 3.0 (latest )to develop DI pattern, this can be downloaded by below link
Dependency Injection using unity framework, C# code example can be seen in below link
There are reasons for not using it in your application, some of which are summarized in this section.

  • Dependency injection can be overkill an application, introducing additional complexity and requirements that are not appropriate or useful. this has to be used properly after good analysis of all aspects.