While I was working on some code today and found that some NuGet packages where out of date. So I went to update tab in Manage NuGet packages window and updated all of them. MySql.Data package (not important which package, just an example) was also updated in that from version 6.7.8 to current / latest (6.9.6). I tried to run the application to test the updates made in referring packages. I encountered following error: TypeInitializationException was unhandled An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module. Additional information: The type initializer for '[Application Name]' threw an exception. Looking at this exception, it doesn't seems to be obvious what is going wrong here. There isn't even option for "View details". Many of you may get stuck on this and spent hours before you figure out that the AssemblyBinding.dependentAssembly.bindingRedirect are creating this » Read more

 Jsinh        

Microsoft OS (XP or later) and .NET provides finest way to secure your data for storage and in-memory. This can be accomplished using following classes from Data Protectection API ProtectedData ProtectedMemory Above mentioned classes can be found in System.Security.Cryptography namespace. Also known as part of DPAPI, they are available since .NET 2.0 ProtectedData ProtectedData can encrypt and decrypt your data symmetrically. To encrypt data following code is used: ProtectedData.Protect(byteArrayOfOriginalData, additionalEntropyOrSalt, DataProtectionScopeValue); To decrypt data following code is used: ProtectedData.Unprotect(byteArrayOfEncryptedData, additionalEntropyOrSalt, DataProtectionScopeValue); In above code snippets additionalEntropyOrSalt can be some custom key / salt value / entropy data that you can add to the encryption / decryption process to increase security strength. DataProtectionScope in above code snippets can have any of the two values: CurrentUser - Allows decryption of encrypted data in current user context only. LocalMachine - Allows decryption of encrypted data in current machine context » Read more

 Jsinh        

WPF Application developers would be experiencing or would have observed that after updating MVVMLight Toolkit package to Version 5.0.0 or 5.0.1, RelayCommand - CanExecute() mechanism is not working anymore. This issue is been already reported by MVVMLight user on codeplex as Issue# 7659. As explained by Laurent: WPF is the only XAML framework that uses the CommandManager to automagically raise the CanExecuteChanged event on ICommands. Unfortunately, there is no CommandManager in PCL (portable class library). CanExecute() is an input parameter of type action, it can be a method that returns bool based on which binding updates to allow or block command execution. This is to be passed when instantiating RelayCommand property that will bind with your control's Command property and fire the default event based on user action. A hot fix is released for above mentioned issue as Version 5.0.2 and now available on » Read more

 Jsinh        

Drag and drop and one of the UI interaction every user loves to have. I gave it a whip in something I was playing with at home. There might be better ways to bring Drag N' Drop interaction in WPF application but I choose to use GongSolution for WPF Drag Drop One reason for using this library for drag and drop interaction is that the library supports MVVM way to do it and does not require much integration to get started. You can add Gong WPF DragDrop library from Nuget into your MVVM enabled WPF application. Add enable a UI element for drag - drop support add following properties to it: DragDrop.IsDropTarget="True" and DragDrop.DropHandler="{Binding}" Here is how my sample XAML file looks like after adding above mentioned properties. <Window x:Class="GongDragAndDropSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http: » Read more

 Jsinh        

So someday you might need to create shortcut of or in your application programatically. Here is how you can do it: A shortcut is basically a LINK to the original file / executable that will be called when the link / shortcut is clicked. To create shortcut pro-grammatically, first you need add reference to Windows Script Host Object Model COM library in your project. Next add this using to your class - using IWshRuntimeLibrary; Next code snippet to create shortcut: var startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var shell = new WshShell(); var shortCutLinkFilePath = Path.Combine(startupFolderPath, @"\CreateShortcutSample.lnk"); var windowsApplicationShortcut = (IWshShortcut)shell.CreateShortcut(shortCutLinkFilePath); windowsApplicationShortcut.Description = "How to create short for application example"; windowsApplicationShortcut.WorkingDirectory = Application.StartupPath; windowsApplicationShortcut.TargetPath = Application.ExecutablePath; windowsApplicationShortcut.Save(); Using above code, I create shortcut on my user's desktop. First line gives me the path to the desktop of my user - using Environment.SpecialFolder.Desktop. Next I » Read more

 Jsinh        

One thing a developer does all the time is debugging code, very obvious. At times the value of property or output of a method you are interested in might be deep inside a class. While debugging you would frequently add them to quick watch window or pin (bookmark) them to reach out quickly. One productivity tip is that you can use DebuggerDisplay on entities to make it quickly accessible while debugging. Let's take a simple class as example: namespace DebuggerDisplaySample { using System; using System.Diagnostics; using System.Globalization; public class Program { public static void Main(string[] args) { var programInstance = new Program(); programInstance.LastSavedDateTime = DateTime.ParseExact( "21-05-1985 12:12 PM", "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None); Console.ReadLine(); } public DateTime LastSavedDateTime { get; set; } } } Here when you debug and hover on the programInstance or pin it (bookmark) it will show you the full name of the class as DebuggerDisplaySample.Program. » Read more

 Jsinh        

For all those important methods of your application where you would like to / have check an input parameter or output result for null / empty check. In case you don't want those checks while you release and only want them to be break into debug or pause while debugging - Debug.Assert is your friend. Let say we have a method that takes string as input: private void SomeMethodAbc(string someInput) { //// TODO: Doing something in here !! } What you want is to validate that someInput is not null, empty or whitespace. But you know your input well and sure that it won't be null, empty or whitespace in production. So in that case you just require this check for debug or development purpose. You can use Debug class from System.Diagnostics and its method Assert to achieve that. When you add a Debug.Assert and the provided condition evaluate to false - » Read more

 Jsinh        

One interesting feature of delegates in C# is that it provide ways to attach / detach more than one methods that has method signature similar to the delegate declared and combine them together. This combining or attaching / detaching of methods to a delegate is called Multicasting. Behind the scenes: This multicasting is possible because delegates inherit from System.MulticastDelegate which in turn inherits from System.Delegate, which inherits from Object class. How to multicast: Multicasting can be done using += and / or -= operator. Here is an example that demonstrate use of += and -= to multicast delegates. private delegate void Greetings(); static void Main(string[] args) { SayHello(); Console.ReadLine(); } public static void SayHelloToScott() { Console.WriteLine("Hi Mr. Delegate, from Scott"); } public static void SayHelloToAlex() { Console.WriteLine("How about a coffee? from Alex"); } public static void SayHelloToJasmine() { Console.WriteLine("Hi delegates, from Jasmine"); } public static void SayHelloToJsinh() { Console.WriteLine("Delegates aahaa, from Jsinh" » Read more

 Jsinh        

I had a weird experience before few days, I definitely knew how to solve the problem and I am sure it is the right way to do it. Thinking it would not be any different to map a datatable to POCO class(es) using Automapper. But it didn't turned out to be completely true. I have been playing with Automapper for couple of years now in my day-to-day work, but I stumbled a bit this time. Situationally, I was not able to conclude the problem with a working solution at that moment, thus I would take this opportunity and write about it so anyone out there who is facing same or similar problem can find their answers. Problem Data filled into a datatable was expected to be converted to Json object. If the datatable contains more than one row the resultant Json should have list of Json objects for each » Read more

 Jsinh        

There will be lot of situations when you have introduced boolean expressions in your code and in good times you might have also combined more than one boolean expressions to control your program flow. Boolean Expression Any expression that can produce a boolean result can be considered as boolean expression. The end result will be boolean, i.e true or false. For example: x == y You can use Greater than >, Smaller than <, Greater than or equal to >=, Smaller than or equal to <=, equal to ==, Not equal to != equality operators to create a boolean expression. Combining Boolean Expression You can combine more than one boolean expressions using OR - ||, AND - && and EXCLUSIVE OR - ^ boolean operators. Short-circuiting - OR (||) boolean operator The OR - || boolean operator when applied returns true when any one of the two operand (or boolean expression) or both operand evaluates » Read more

 Jsinh        

One interesting feature that was introduced since .NET 4.0 was AppDomain.FirstChanceException FirstChanceException MSDN: Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain. This means that whenever an exception occurs in your managed code, all subscribers of above mentioned event will be notified with exception details. It is called first chance because this event is notified to the debugger or subscribers even before the actual program gets it. Event before Try/Catch block (if any) are executed. It serves as "first chance" to take a note of the exception thrown. All exceptions except Stackoverflow and access violation exceptions will be notified to this event. This is subscribed by your Visual Studo debugger, you can verify that by running an sample and throw an exception from your program. You will see following or similar output » Read more

 Jsinh        

These days Redis sparkle in my eyes, for lots of reason but the basic and most important reason is that it is deaam fast. Now we all know this can bring up an never ending debate but I am not going to be part of it because its fast and here I am not referencing it with comparison to other data-stores available. Redis is an open source, advance key-value store. This key thingy can be strings, hashes, lists, sets and / or sorted sets. Quite a list :) Note: This post was tested and written for Redis Version 2.8.3. This may or may not work for other or latest version of Redis Server. I was impressed when I queried who is using Redis and the long list of clients libraries for most of the language available to work with Redis as your Key-Value store. It is made to run on » Read more

 Jsinh        

In .NET, version information for an assembly follows following format - [*.*.*.*]. This version format consist of four values: Major Version Minor Version Build Number Revision Above four value can be used to indicate different things depending on how you want them to be understood. When we compile or build our code in .NET (using Visual studio), it outputs assemblies and this assembly can be tagged with three different types of versions, which are as follows: Assembly Version Assembly File Version Assembly Informational Version Now let’s take a minute to understand what are these and how or in which context are they used. What is Assembly Version? I call this version as the pure .NET version, but to be specific it is important in your runtime scope. When any application or other assembly references this assembly, this is the version number they will try to find and remember the referenced » Read more

 Jsinh        

In case you are serializing your models to generate XML content, you will often encounter empty nodes and elements in the XML which appears when the entity property is not filled or the list is empty. Lets take an example of Employee model class as below: using System.Collections.Generic; using System.Xml.Serialization; public class Employee { public Employee() { this.Skills = new List&lt;string&gt;(); } [XmlElement("FirstName")] public string FirstName { get; set; } [XmlElement("LastName")] public string LastName { get; set; } [XmlArray("Skills")] [XmlArrayItem("Skill")] public List<string> Skills { get; set; } } When you generate XML for the above model by assigning FirstName and LastName only keeping Skills empty: var employeeDetail = new Employee() { FirstName = "Mister", LastName = "XYZ" }; var employeeDetailXml = SerializeXml(employeeDetail); you will get XML content something like this: <?xml version="1.0" encoding="utf-16"?> <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: » Read more

 Jsinh        

AppDomain.CurrentDomain.SetupInformation property provides some general information about the currently executing assembly. This can provide more information about the assembly binding information for current instance of AppDomain used. Above property results instance of type AppDomainSetup class. Few properties you may find interesting about the currently executing assembly are as follows: ApplicationBase - ives the path to the directory that contains the application. ApplicationName - Gives name of the application (with extension). ConfigurationFile - Gives path to the configuration file of the application domain. TargetFrameworkName - Give a string that specifies the target version of .NET framework for   the application domain this string follows format defined for FrameworkName.FrameworkName property. Happy Coding !! » Read more

 Jsinh        

All .NET string is in Unicode (UTF-16) encoding format. So when you are using StringWriter to create your XML it will use UTF-16 encoding. Example when creating XML : var serializer = new XmlSerializer(yourModel.GetType(), string.Empty); var stringBuilder = new StringBuilder(); using (var stringWriter = new StringWriter()) { serializer.Serialize(stringWriter, yourModel); stringBuilder.Append(stringWriter); } var resultString = stringBuilder.ToString(); But you want your XML to use UTF-8 encoding. One good way of doing this is to derive the StringWriter class and override the encoding. using System.IO; using System.Text; public sealed class ExtentedStringWriter : StringWriter { private readonly Encoding stringWriterEncoding; public ExtentedStringWriter(StringBuilder builder, Encoding desiredEncoding) : base(builder) { this.stringWriterEncoding = desiredEncoding; } public override Encoding Encoding { get { return this.stringWriterEncoding; } } } Then you can use ExtendedStringWriter instead of StringWriter in the above example. » Read more

 Jsinh