TopMenu

Thursday, 5 December 2013

Dictionaries in CSharp are datastructure which represents hash maps. You can store key value based data easily also it prevents to insert duplicate keys. But sometime it comes as requirement where you have a list of items which you want to use as a key in dictionary. The following wouldn’t be so common and only occur rare but it’s a possibility that you would also face the same situation so I came to share the same with you guys.

Problem: Now here the trouble starts. If you use generic list as key the default equality comparer checks for default has and simple object reference equality in Dictionary for keys. Now for two similar lists with similar underlying items would result in getting those two lists as different items. Which means you can add the two lists with similar items in Dictionary as a key with no objection. But what is benefit of using Dictionary then?

Solution: There’s an overload of constructor of Dictionary which accepts the custom Equality comparer for keys. So I’ve created custom equality comparer and it was also tricky to write that custom comparer.

So implementation of the custom equality comparer would look something like:

Now why I have to write so much custom code in the Equals and GetHashCode method. If I use simple and direct solution then these list will always be different. So I have to XOR the hashcode of underlying items in both lists to get the hashcode based on the items rather than list reference. I found dealing with Hashcode from John Skeet’s post on stackoverlflow.

For equals method, I need to compare the values of the public properties of the list items as the reference would be different so again we felt into the same situation. But after comparing the values and hashcode individually for each item of list we can ensure if we’re not adding similar stuff again and again in the dictionary.

Thursday, 3 October 2013

I’ve been using the Micromax Canvas4 from few months. There was an update from Gmail app and I downloaded and installed it. Then It asked me to “AutoSyncOption” to set to “ON” and I clicked “OK”. Later the device was in a restart loop after every 3-4 second. It’s like a mess for me as I bought it recently. Later I had to hard reset the device to factory setting and wiped all the data. Then It worked like a charm. I’ll share the steps but do it at you own risk but it worked for me.

How to Hard Reset the Canvas 4 Android device:

1. Switch off the device and then Boot it with holding volume up + volume down + unlock key together.

2. Now it will start booting when I vibrates first time release the key and It’ll start in the boot mode.

3. Now select the RecoveryMode. You can navigate through the option via volume up & down key and select the option by “Option/Menu” button.

4. It’ll further go to another option menu. Now navigate to select the Wipe user data/Factory Reset option and select ok by Menu key.

5. Now this will start restoring to it’s factory setting*(state of the device when you purchased it).

6. When the reset will finish it’ll go back to the menu again. Now navigate to the Restart the device by selecting Restart option and click ok.

Now your device will be restarted and will be running again.

Warning/Disclaimer: Do this at your own risk. It worked perfectly for me.

The EF5 has been released with .Net framework 4.5 and now it’s supporting the user defined table valued types as parameter in stored procedure. In earlier versions of Entity framework it was not supported. For e.g. EF4 is widely being used with .net framework 4.0. And these types are not supported in that version. Even some people raise a User voice ticket for the same but none action has been taken and ticket was closed since this feature is shipped with .net 4.5.

For those who can not migrate to 4.5 and are looking for a work around how to work with these kinda stored procedures. I’ve created a work around solution for that. Let’s take some database test objects.

Now if you try to generate the model from database this StoredProcedure will not be listed even if you use FunctionImport to call the stored procedure. Now to workaround I’ve created a custom class that executes this stored procedure as a Sql statement from DBContext object.

Tuesday, 1 October 2013

Flags enumerations are used for masking bit fields and doing bitwise comparisons. They are the correct design to use when multiple enumeration values can be specified at the same time. This was quite an official definition and if you are confused then let’s take an example.

For example, theFileShare enumeration contains the ReadWrite value to specify that a shared file can be opened for reading or writing. This shows developers that they can open a shared file for reading or writing, and eliminates the need for them to learn how to specify a combination of enumeration values as a single value.

Let’s take you to the world of Enums where you are allowed to use multiple values rather than using only single value for comparison/storing. To create an Flagged Enumeration you need an attribute [Flags] to be specified on the Enum.

Here are few guidelines while declaring an Enum as flagged.

Do apply the System.FlagsAttribute to flags enumerations. Do not apply this attribute to simple enumerations.

Do use powers of two for a flags enumeration's values so they can be freely combined using the bitwise OR operation.

Note: If you do not use powers of two or combinations of powers of two, bitwise operations will not work as expected.

for e.g. Let’s take an example of Identity cards type allowed to fill an application form before applying for a position. So we’ll create an Flagged Enum.

Likewise, after you've set your property AllowedIDs to Passport, DrivingLicense and UId (which values where OR'ed by the pipe |), AllowedIDs looks like this

AllowedIDs: 00001110

So when you retreive the value you are actually bitwise AND'ing the values

myProperties.AllowedIDs: 00001110 IdentityProofType.DrivingLicense: 00000010 ----------------------- 00000010 // this is the same as IdentityProofType.DrivingLicense!

Different forms of Flagged Enums

There are different ways you can define a Flagged Enumeration. Since you know that it only allow values to the power of 2. So you can do something like this with your flagged enumeration in case you don’t want to count for the huge collection of Enum.

Note: If you have notices than there’s a new name introduced in these called None having value 0. It is not allowed to have value starting with 0 in these enum types. But as per the MSDN:

Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

Wednesday, 25 September 2013

I’ve been a big fan of JSON.Net since past few years. Always helping me with less code and high performance conversion of JSON to C# objects. Thanks to James who made it possible as a fastest framework for manipulating JSON with a great documentation. In this post we will talk about a json format where a list of json objects presents with no root elements. This would be easy if you have root element you can use JObject of json.net. But in case you don’t then this would throw an exception.

You can use simple Jsonconvert.Deserialize<yourType>(jsonString) to get the typed object from a JSON. But his can throw an error if the items in Json have field with incorrect value. Let’s an int field have some alphabetic character. The exception will thrown for parsing and you’ll have very little details on error.

Now if you need to parse it as list and let’s say you want to find elements who have fields which are not of correct type as it should be then we can filter them out and log them somewhere. And so you will get a complete list of correct items and corrupted data.

We’ll use a JArray class from namespace Newtonsoft.Json.Linq to parse the data as list of array of object and then we’ll convert one by one each item to typed object and add it to list. Here’s the sample generic deserializer that can parse Json and get the valid and invalid elements.

Wednesday, 18 September 2013

There were new features introduced in .Net 4.0 and one of the awesome feature was addition of System.Dynamic in framework library. With this dynamic objects C# can provide dynamic language features like Python.

A short brief of Dynamic objects is, Dynamic objects expose members such as properties and methods at run time, instead of in at compile time. This enables you to create objects to work with structures that do not match a static type or format. For example, you can use a dynamic object to reference the HTML Document Object Model (DOM), which can contain any combination of valid HTML markup elements and attributes.

People still gets confused with Dynamic vs Anonymous types. Just to clarify Anonymous types cause the compile time errors. While Dynamic types work upon run time late binding for object properties. Let’s take an example:

var anonymousObject = new { Name=”Anonymous”, Value=”Foo” } ;

if you use anonymouseObject.Index then It’ll throw an compile time exception because it only know the Name and Value as it’s property. But using Dynamic you can use object.UnknownProperty will not cause compile time error.Let suppose you have requirement to create a object with properties which could be in any no. and of any type you don’t know. So how will you do this operation? I’ll introduce you with an exciting type of class called ExpandoObject with in System.Dynamic.

This will automatically append these properties to the object. Now if you ask for runTimeObject.OtherUnknownProperty then it’ll not give any error during compilation but this will be check when you run the program. So you can also check if the object have this kind of property before using any runtime property. Behind the scene it’s storing these property as a Dictionary. So you can cast the runTimeObject to IDictionary<string,object> to get the list of late bound properties on the object.

Isn’t is cool? Yes it is. But beware before using it in your ordinary scenario can cost you some CPU time. These are runtime late binding operations which requires its own time to resolve the symbols and so are less optimized than normal early binding cases.

So choose wisely with your scenario. In some cases this is really an awesome feature provided in recent version of CSharp. I would say that CSharp is not just a Object Oriented language but it’s adapting features of Functional, Dynamic language. That’s why it’ll will long last than any language in the programming world.

If you enjoyed reading this then please leave a comment or suggestions.

Friday, 6 September 2013

This post is about a question that people often asks when writing Unit tests and What troubles a developer is:

When should I stop writing Unit tests of something(Let say a simple Function)?

Lets talk about something known as Code coverage feature in visual studio(Premium/Ultimate editions). Most of the people don’t even know how it can help identifying unused code. Code coverage actually do the instrumenting of the assembly with special symbols putting over each statement and then analyse if that is being called when the code was getting executed. In visual studio this feature is added with Test manager. So you can run your unit tests via coverage tool and analyse the report how much production code is being covered by your unit tests.

Lets see how to run tests with coverage in simple steps:

1. In visual studio 2012 (Premium/Ultimate) you’ll find the option Test –> Analyze code coverage. Now there’s an option to run a single test coverage or all tests coverage.

Note: This option will be enabled only when your solution have UnitTests available. For unit tests written with Nunit you will need an Nuget package for Nunit Test Adapter. If you want then you can also download the Nunit VS Extension by searching into the VS Extension online.

2. Now select Run All Tests option and the magic will start. The coverage tool will be automatically launched and will run all Unit tests.

3. Once all the unit tests are done with running. You’ll see a coverage report in Code coverage Results window which will give you coverage in %.

In this report you’ll see in the Covered column the percentage of every function. And if this report says 100% then

Writing Unit tests at the moment.

Though as a standard testing strategy you can stop when coverage is >95%.

Monday, 24 June 2013

There are several ways to implement the Global Exception handling in WCF for e.g. using a IErrorHandler (The best way to handle the uncaught exceptions) or creating your own Façade for calling all service methods. In this article we’ll discuss about an Interceptor IOperationInvoker that can be used before and after activity when a service actually calls it’s operations. There are several things you can perform at this stage like Logging, Tracing or Handling the Exception(specially Unhandled Exceptions).

First we’ll start to look at high level of the picture where the Operation invoker actually stands when a client make a service method call. Below diagram is showing a picture of the same.

So lets create a WCF service project. (Learn how to create and consume WCF service). After adding the project, we need to add some operation in the service so for e.g. our service operation is GetParseData(). So it can look something like this(as generated from Project template).

To get some exceptions we’ll a custom logic in the Implementation of GetParseData(). So it can look something like this.

publicstring GetParseData(stringvalue){// check if value is alphabets/Numericif (string.IsNullOrEmpty(value)) {thrownew ArgumentException("Method parameter value can not be null or empty"); }

// split the value if it contains spaces and return first two words var stringArray = value.Split(' ');

// This will/may cause an Unhandled exception for OutOfIndex in case of single word is passed.returnstring.Format("{0}_{1}_{2} ..", stringArray[0], stringArray[1], stringArray[2]);}

Here in this method we have introduced some known and unhandled exception. To demonstrate the logging and Global exception handling we’ll now create a class that will Implement the IOperationInvoker interface.

In this implementation of IOperationInvoker we will only focus on the Invoke() method to log the request begin and request end also a Try Catch block is placed on the invoke statement so that we can capture any unhandled exception and log it in the first place with all details. And we’re not sending the complete exception to the client but a custom FaultException with less details or a message.

Now the invoker is ready but how to attached this Invoker/Dispatcher to our service. For this we’ll implement the IOperationBehavior first to attach the invoker with default operation behaviors.

But here we’ll create our Custom Attribute class and will use it in the code directly as an Attribute on service class. To create an Attribute for service behavior we need to inherit the Attribute class in our CustomAttribute implmenetation with IServiceBehavior .

Here we are actually applying the behavior to the end points. which in turn doing the same as we do apply behavior via the configuration file with each EndPoint. So our Attribute class is ready, we're going to tell the Service calls that you have a custom behavior to handle the global exception.

// split the value if it contains spaces and return first two words var stringArray = value.Split(' ');

// This will/may cause an Unhandled exception for OutOfIndex in case of single word is passed.returnstring.Format("{0}_{1}_{2} ..", stringArray[0], stringArray[1], stringArray[2]); }}

Now we’ll create a client and call the service method. To create a client simple host the service in IIS express and find the service reference via service reference dialog box. We’ll simply use the Console application as a client.