Monday, November 23, 2015

Passing By Value Vs By Ref C#

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable. If you want the called method to change the value of the parameter, you must pass it by reference, using the ref or out keyword. For simplicity, the following examples use ref.

Bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

Class, delegate, dynamic, interface, object, string

C# Example
private void button1_Click(object sender, EventArgs e)
     int i = 100;

     PassByVal(i);   // Don't change original value
     button1.Text = i.ToString(); // OutPut is : 100

     PassByRef(ref i);   // Change original value
     button1.Text = i.ToString(); // OutPut is : 110

private void PassByRef(ref int i) { i += 10; }

private void PassByVal(int i) { i += 10; }

More Difference

Value Type
Reference Type
They are stored on stack
They are stored on heap
Contains actual value
Contains reference to a value
Cannot contain null values. However this can be achieved by nullable types
Can contain null values.
Value type is popped on its own from stack when they go out of scope.
Required garbage collector to free memory.
Memory is allocated at compile time
 Memory is allocated at run time

Wednesday, September 23, 2015

.NET Logging Tools, plugins, open source

There are multiple tools and plugins available for .net application logging, based on its license, easy to use, easy pluggable, least impact on performance and best fit into .net environment, below are the tools listed on priority wise.  
ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. 
The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. Log4net is a port of the excellent Apache log4j framework to the Microsoft.NET run time. 
Microsoft Enterprise Library
Logging Application Block. Developers can use this application block to include logging functionality for a wide range of logging targets in their applications. This release adds asynchronous logging capabilities.
Smart Inspect
Rich Logging & Tracing Track messages, errors, objects, database results & more. Logging support to any .NET desktop application, ASP.NET server project or multi-tier database solution.

Saturday, May 09, 2015

Convert Byte Array to Memory Stream and vice versa

Convert byte Array to Memory Stream
Stream stream = new MemoryStream(byteArray);

Convert Memory Stream to Byte Array
Byte[] byteArraystream.ToArray();

Convert String to byte Array
static byte[] GetBytes(string str)
{   byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;

Convert Byte Array to String
static string GetString(byte[] bytes)
{   char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);

Write Byte Array into File
File.WriteAllBytes(string path, byte[] bytes)

Add double quotes in the string:
string str = "\"Add double quotes\"";

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