Prash's Blog

Compress and Uncompress in C# using .Net APIs December 3, 2012

Filed under: C# — prazjain @ 4:02 pm
Tags: , ,

Code snippet below for uncompressing a zip file to text file and compressing a text file back to zip file.
It is really minimal and I was able to uncompress 3+ gb text files using this, and as it just deals with stream you do not need to store the contents of the file in memory!
Here you go

        internal void UncompressZipFile(string fullPath, string zipPath)
        {
            //uncompress it
            Log.InfoFormat("Uncompressing XML zip file : Start");
            using (GZipStream gzs = new GZipStream(new FileStream(zipPath, FileMode.Open), CompressionMode.Decompress))
            {
                using (FileStream xmlFile = File.Create(fullPath))
                {
                    gzs.CopyTo(xmlFile);
                }
            }
            Log.InfoFormat("Uncompressing XML zip file : Finish");
        }

        internal void CompressCSVFile(string fullPath, string zipPath)
        {
            //Compress it
            Log.Info("Compressing CSV file : Start");
            using (FileStream csvFile = new FileStream(fullPath, FileMode.Open))
            {
                using (GZipStream gzs = new GZipStream(new FileStream(zipPath, FileMode.Create), CompressionMode.Compress))
                {
                    csvFile.CopyTo(gzs);
                }
            }
            Log.Info("Compressing CSV file : Finish");
        }

 

Restore of database failed : Operating System returned error Access denied March 5, 2012

Filed under: C# — prazjain @ 12:13 pm
Tags: ,

I was restoring a database backup in sql server after a long time, and hit upon this error. Well how difficult can restoring a db backup be in sql server express.
Hmm, not that difficult, here is what happened.

Error Message:

System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\MDS.mdf'. (Microsoft.SqlServer.SmoExtended)

The backup creator had MSSql version 10 installed, so when he took the backup it also stores the original file path (to be able to restore it in same location), but I had version 11, so it could not find the destination directory.

So I changed the output file directory to C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\, and it was able to restore the database successfully.

 

Entity Framework 4.0 supports POCO May 13, 2010

Filed under: C#,Entity Framework — prazjain @ 8:49 pm
Tags: , ,

POCO – Plain Old CLR Object

In Entity Framework 3.5 an Entity Class had to extend EntityObject class which in turn implemented IEntityWithKey, IEntityWithChangeTracker, IEntityWithRelationships. All of this meant more persistence logic into a domain object, a place where it does not belong. It also made testing of these domain object a bit more complicated.

Entity Framework 4.0 now supports POCO, so simple implementation like below could be used with EF 4.0 (database used with this example is the Microsoft AutoLot database).


public class Customers {

public int CustID {   get;   set;   }

public string FirstName {   get;   set;   }

public string LastName {   get;   set;   }

}

This also makes the code easier to test, and it extracts the persistence logic out of domain objects.

 

New C# Language Features in .Net 4.0 May 7, 2010

Filed under: C# — prazjain @ 11:31 pm
Tags: , , , ,

.Net 4.0 has added couple of new language features in C#

Dynamic Lookup

C# has added a new static type named ‘dynamic’. It supports late binding, so any calls to methods, properties, fields are not resolved at compile time. Thus an error arising due to its use is also detected at runtime.


dynamic person = GetPerson();

// A runtime error would be generated if the object returned by GetPerson() method does not has Name property

person.Name="Prashant";

‘dynamic’ type provides a lot of help to programmers dealing with COM objects in C#

Optional Parameters

C# now provides the ability to assign default values to method parameters incase the caller does not intend to pass value for a parameter.


void Print(string car="Mini Cooper", int price=15000)

{      Console.Writeln(string.format("Car : {0}, Price : {1}",car, price));  }

void M1()

{   Print("VW Golf");  }

Upon invoking M1(), it would print : “Car : VW Golf, Price : 15000″

This shows the parameter ‘price’ assumed the default value.

Named Parameter

Method parameters can now be assigned names, so its no longer necessary that method arguments are passed in the same order as method parameters.


void Print(string car="Mini Cooper", int price=15000)

{      Console.Writeln(string.format("Car : {0}, Price : {1}",car, price));  }

void M1()

{   Print(price: 16000, car: "VW Golf");  }

Upon invoking M1(), it would print : “Car : VW Golf, Price : 16000″

Covariance

Covariance means that an object can be treated as less derived. This features is used to return values from methods that are more abstract.


class Vehicle { ... }

class Car : Vehicle { ... }

class Test {

static void Main(string[] args)

{

...

IEnumerable<Car> cars = GetCars();

// this is now possible in .Net 4.0

IEnumerable<Vehicle> vehicles = cars;

// prior to .Net 4.0 it would have required going through 'cars' collection and add every object into a new collection vehicles

}

}

To allow Covariance the IEnumerable type is defined with an ‘out’ keyword


IEnumerable<out T> { ... }

‘out’ keyword says that its fine to take values out from the collection, adding values is not allowed.

Contravariance

Contravariance allows a more derived type argument to be passed into a less derived type method parameter.


class Vehicle { ... }

class Car : Vehicle { ... }

class Test

{

// Contravariance is enabled by using 'in' keyword

delegate void MyHandler<in T> (T a);

static void Main(string[] args)

{

MyHandler<Vehicle> handler = (veh) => { Console.Writeln(veh); }

// below line is now allowed in .Net 4.0

MyHandler<Car> carHandler = handler;

}

}

All that it means is contravariance allows a Car (subtype) to be passed into a method that requires Vehicle (base type), which could do not harm to the execution of method. But this is only allowed when the delegate generic definition uses ‘in’ keyword, without ‘in’ it would fail in .Net 4.0 too!

Events

Events in C# look like fields / properties. Operators += and -= are overloaded to map to add and remove accessor methods.

Prior to C# 4.0, these generated accessors were synchronized across threads using ‘lock(this)’ as the auto generated code decorated accessors with MethodImpl(MethodImpl.Synchronized) attribute, that meant instead of synchronizing access on that invoke ‘add’ & ‘remove’ method, it would synchronized access across any thread that capture lock on ‘this’ object.

To get across this problem, C# 4.0 changes the way the code is generated for these accessors, it generates code to test for race conditions and updates delegate list accordingly.

This should be a non-breaking changes unless your code is dependent on the way synchronization was implemented earlier.

 

Using Anonymous types in .Net 3.0 September 28, 2009

Filed under: C# — prazjain @ 2:20 am
Tags: ,

Using Anonymous types in C# .Net 3.0

Anonymous types should as simple containers for storing temporary data. These types as they do not have a name associated with them, cannot be passed to a method or returned back. Generally these are supposed to be used inside a method while performing some processing, where you would not like to work on the entire data structure and just a part of it.

How to create an anonymous type

</p>
<p>var anonTypeVar = new { X = 100, Y = 200 };</p>
<p>

This statement causes compiler to generate an internal sealed class, with readonly properties for X and Y. The constructor for this class takes two parameters for each property, in the sequence they are defined. The type of the properties is determined by their values.
eg. : This is approximately what compiler generates behind the scenes.

</p>
<p>internal sealed AnonTypeClass {<br />
private readonly int x;<br />
public int X { get { return x; } }</p>
<p>private readonly int y;<br />
public int Y { get { return y; } }</p>
<p>public AnonTypeClass(int xParam, int yParam) { x = xParam ; y = yParam; }</p>
<p>}</p>
<p>

The compiler generates this boiler plate code for you when you create an anonymous type var.

In case you noticed by now, using object initializers with immutable types is only possible when its an anonymous type, as compiler adds some features into the auto-gen code to allow that.

You might be tempted to think that the compiler create a new type everytime it sees that expression. No, it reuses the same type as long as their are same number of properties, they are of same type, same name, and in the same sequence.
So these expressions would generate different types :

</p>
<p>var a1 = new { X = &quot;a&quot;, Y = &quot;b&quot; };<br />
var a2 = new { Y = 100, X = 200 };<br />
var a3 = new { X = 100, Y = 200, Z = 300 };</p>
<p>

Overuse of anonymous types could make the code unreadable, but if used judiciously they could prevent creation of lots of classes that are used to create only temporary objects  in intermediate processing.

 

Extension Methods : What When How

Filed under: C# — prazjain @ 1:24 am
Tags: ,

What are Extension Methods

Interfaces have allowed us to attach only declaration of methods with them.
Extension methods provide a way to add behavior to an interface. This makes it more interesting as your interface definition and the implementing class can remain constant, but the new capabilities can be added to the interface (through extension methods).

When to use Extension methods

A general rule of thumb that goes while determining which methods should be part of interface and which ones should be extension methods :

Any methods that is part of generic implementation should be part of interface, whereas any specific implementation of that method should be an extension method.

Example:
Suppose there is a holiday planning service out there, then using extension how could it be designed :


public interface IHolidayPlanner
{
IList<Holiday> GetHolidays(int minPrice, int maxPrice, int duration);
}

public class HolidayPlanner : IHolidayPlanner
{
IList<Holiday> GetHolidays(int minPrice, int maxPrice, int duration)
{
return null // get the logic working here
}
}

// Now we could define extension methods around the generic implementation of IHolidayPlanner interface, for example searching for budget holidays and luxury holidays

public static class HolidayPlannerEx
{
public static IList<Holiday> GetBudgetHolidays<T>(this T planner,int duration) where T: IHolidayPlanner<T>
{
return planner.GetHolidays(0,1000,duration);
}

public static IList<Holiday> GetLuxuryHolidays<T>(this T planner,int duration) where T: IHolidayPlanner<T>
{
return planner.GetHolidays(1001,100000,duration);
}
}

In this way any specific implementation that could be built upon a generic implementation of a method in the interface could be declared as an extension method.

This example might not be the best way to design a holiday planning app, but I hope it get the message across about how Extension methods can be used.

 

 
Follow

Get every new post delivered to your Inbox.