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        

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        

I was recently working with a sidekick thing where I was using MySQL as my backend database. This was accessed from the application with hostname - localhost and username dev. I had created one view and was using it in the thing I was working on. It was originally scripted like this: CREATE DEFINER = 'dev'@'localhost' VIEW somedatabase.somerandomviewname AS SELECT `sd`.`somerandomcolumnone` as `ColOne`, `sd`.`somerandomcolumntwo` as `ColTwo` FROM `someshitytable` `sd` WHERE sd.blahblah IS NOT NULL; One day I realized that my workstation is going crazy over few tools I use everyday. I could have repaired or fixed or reinstalled them but then I choosed to do a full cleanup and start fresh (for no particular reason). So I used MySQL dump backup feature from maintanance and created backup scripts for that database, which also contains the creation script for this view obviously. Once my machine was ready » 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 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        

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        

Application speaks your business. The application works fine – check, it does not crash while you pop some popcorns – check, it does show correct results and data – check, it cannot get anymore faster than this – check, does not keep showing “loading, please wait” message for next 100 years – check. Phew, finally your application is all good to go. But are we not forgetting something? Presentation or the visuals plays an equally important role in success of any business solution / application. Condition – it is not some high end, supa dupa background processing application. This presentation part can be different for each and every solutions coded out there. They may have glassy sprites and rich menus, some might be theme based. Some impress well using javascript or animation and so on. One of the Titanic times solution for desktop application to improve presentation quality is start-up splash screen. Application splash screen can be » Read more

 Jsinh        

Lately Microsoft have been using some of the well known design patterns to ease and furnish work of a programmer who choose to bang keyboards using .NET. One good example is WPF commands. Microsoft at MSDN on Commanding: Commanding is an input mechanism in Windows Presentation Foundation (WPF) which provides input handling at a more semantic level than device input. It resembles and is inspired by the famous Command Design Pattern with Microsoft flavors added to it. This Routed command system as named by Microsoft is a modified version of the original command design pattern with routing capabilities. It is used to send command and / or behavioral notifications from UI controls. They are analogous to the Routed event system in WPF. The routed command system in WPF has two types of commands: Routed Commands Routed UI Commands It becomes clear from the name itself that the first is used to » Read more

 Jsinh        

Microsoft Message Queue is message based protocol technology that provides a way to communicate asynchronously in a distributed environment. Microsoft Message Queue is also known as MSMQ for short, code name “Falcon”. MSMQ is one of the best proven ways to engineer for developing distributed enterprise business solutions. It provides asynchronous and disconnected pattern of communication between different components of an enterprise application. Different application can work in isolation and can communicate or pass information to other application using this message protocol. MSMQ is service which manages queues. These queue stores message used for communication or to pass information. MSMQ is part of Microsoft OS from time of Windows NT 4 and Windows 95. It was introduced in late 1997 and become a part of Microsoft Embedded platforms from 1999. MSMQ is also called Message – Oriented Middleware (MOM). MSMQ Versions First Version 1.0 of MSMQ was released in May » Read more

 Jsinh        

I would start this.life and connect with the world by explaining three important C# keywords – ref, out and params also known as “Method parameter keywords”. These keywords are called method parameter keywords because they are used to change the behaviour of parameters passed into any method. C# Keyword - params This parameter keyword can be used to specify method parameter that takes variable number of arguments. When the number of values required are not fixed and the internal mechanism can handle variable number of arguments processing, in that situation we can use params keyword for a method parameter. This method parameter can either accept comma-separated list of arguments of specified type, array of arguments of specified type or no arguments. public void DemonstrateParams(params int[] inputParamList) { if (inputParamList.Length >= 1) { for (int counter = 0; counter > inputParamList.Length; counter++) { Console.WriteLine("Parameter No:" + counter + " = " + inputParamList[counter]); } } else { Console. » Read more

 Jsinh