How to easily create self hosted signalr windows service using TopShelf framework

Recently i got the chance to work with windows service. As a web developer i have never created windows service in my carrier. Generally i used to refer MSDN and hence i was trying to understand the flow of windows service from MSDN. But for more complex example i did some googling in detail and found out “TopShelf” library.

Topshelf is an opensource windows service framework written in c#. Using TopShelf creating windows service is as easy as creating a console application. This framework will literally convert your console application into windows service. What!.. yes, you heard it correct. You can easily convert your typical console application into windows service and easily debug it and install it in “Service control manager” by using few lines of Topshelf’s configuration fluent API. It’s available on GitHub. Okay, in this blog post we’ll step-by-step create self hosted signalr server in windows service and consume it in another console application.

So before we go ahead, let’s understand what signalr is in brief. Well, SignalR is a library for a developer which allows real time bi-directional communication between server and client. Means using SignalR, server can broadcast its message instantly to the connected specific / all clients.

Now its time to do some code. First let’s create a blank solution project in visual studio. Now add one console application in that solution and name it – “SignalRServerUsingTopShelf“. Now add “TopShelf” dll from nuget as shown in below image.

NugetForTopShelf

Also Install Log4Net from nuget which is an open source library that allows application to log statements to a variety of targets

Note: Before you install TopShelf, your console application’s target .net framework must be 4.5.2 or greater.

Now let’s add “StartUp.cs” class to configure signalr middleware. This class contain “Configure()” method. In this method we call “MapSignalR()” method which defines the root that client will use to connect our Hub. To allow cross domain request we set CORS middleware.


public class StartUp
{
	public void Configuration(IAppBuilder app)
	{
		app.UseCors(CorsOptions.AllowAll);
		var hubConfiguration = new HubConfiguration
		{
			EnableDetailedErrors = true
		};

		app.MapSignalR(hubConfiguration);
	}
}

Let’s create signalr hub class. This class contain methods which allows real time communication between server and client. You can think of this class as a mediator between server and client.


public class MyMessageHub : Hub
{
	//public static Dictionary<string, string> subscribedClients =
       //                 new Dictionary<string, string>();

	public void BroadcastMessage(string message)
	{
		Clients.All.BroadcastMessage(message);
	}
}

Now let’s add one new class named it – “SignalServer.cs” in which we write our core windows service related function and will later configure this class using TopShelf’s configurable API in program.cs file’s Main() method. Generally typical windows service class contains method like OnStart, OnStop, OnPause etc. which determine what happens when the state of your service is changed. So in our case the “Start” method contains the defining and hosting of signalR server when my service will start and in “Stop” method i want to dispose the require resources which i have created on start method.


public class SignalRServer
{
	private ILog logger;

	IDisposable SignalR { get; set; }

	public SignalRServer(ILog logger)
	{
	     this.logger = logger;
	}

	public bool StartService()
	{
		logger.Info("Starting service...");
		var option = new StartOptions();
		//option.Urls.Add("http://localhost:18275");
		// You can either get dynamic ip OR set in app.config
		// But for demo purpose i have set it static
		option.Urls.Add("http://192.168.151.87:18275");
		SignalR = WebApp.Start(option);
		logger.Info("SignalR server started..");
		logger.Info("Service Started.");
		return true;
	}

	public bool StopService()
	{
		SignalR.Dispose();
		logger.Info("Service Stopped.");
		System.Threading.Thread.Sleep(1500);
		return true;
	}

	public bool PauseService()
	{
		logger.Info("I'm in Pause method");
		return true;
	}
}

Now its time to configure our “SignalServer.cs” class using TopShelf’s fluent API in program.cs.


class Program
{
	private static readonly ILog logger =
		LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

	static void Main(string[] args)
	{
		logger.Info("Programe launched");
		HostFactory.Run(config =>
		{
			config.Service(instance =>
			{
				instance.ConstructUsing(() =>
					new SignalRServer(logger));

				instance.WhenStarted(server => server.StartService());

				instance.WhenStopped(server => server.StopService());
			});

			config.SetServiceName("Signal_server");
			config.SetDisplayName("Signal server");
			config.SetDescription("Self hosted signal server using TopShelf");
			config.StartAutomatically();

			config.BeforeInstall(() =>
			{
				logger.Info("Service before install");
			});

			config.AfterInstall(() =>
			{
				logger.Info("Service after install");
			});

		});
		//Console.ReadLine();
	}
}

I guess no need to explain the above code as you can see in the above code, Just like normal windows service i have configured the start and stop method and set the service name etc. using TopShelf’s API. Now its time to run the code. Just press “F5” in vs and you can run it as normal console application. When you run the application, it’ll open this type of console window.
Output

Before we go ahead please take one note here – in SingalR when you specify ip address in url (refer SignalRServer class – StartService method) and while running the application sometimes it throws an exception of – “TargetInvocationException“. To get rid of that exception we need to register that url using “Netsh” command. Open command prompt in admin mode and type

— To Register url
netsh http add urlacl url=http://192.168.151.87:18275/ user=EveryOne

— To deregister url
netsh http delete urlacl url=http://192.168.151.87:18275/

netsh_addUrl

Now let’s install our service in “Service control manager” using topshelf command line utility. Go to bin/debug folder and copy the path. Now open command prompt in admin mode and paste the copied path and press enter. Then after enter below command –

“YourServiceName” install start

Topshelf will install the service and showing the following output which means your normal console application now works as a windows service.

Service_Install

You can verify it by opening service manager window.

HostedService

Uninstalling of the service is also easy. Just type following command in command prompt.

“YourServiceName” uninstall

UnInstall_Service

This demo application source code is available for download on GitHub where i have added two more console app from which one works as message sender and another one works as message receiver. That’s it for now. Hope you like this post.

How to dynamically bind and configure column’s metadata in kendo grid for your MVC application

As a blogger you always strive for some interesting topic to write for your blog. Recently in one of our MVC application i got the chance to work with kendo grid control, but with some interesting requirement. Although i have already used kendo ui controls in other mvc application, but in this application i have had got very interesting requirement and somewhat challenging also.

Now let me explain you the requirement. Normally you will bind your kendo grid with some predefined columns. But in this case i need to bind the kendo grid where column type and number of columns to bind will decide at run-time. Let me add further one more point in this requirement – each column’s metadata will also decide at run-time. Well, column’s metadata mean column’s caption, datatype, width, format, header alignment and text alignment etc. will decide based on the type of column. Don’t worry, if you don’t get this point. Let’s see this practically.

For demo purpose, i have made two new classes. One class for actual data to bind in kendo grid. Name of that class is let say – RowValue. Another class is for column’s metadata. Name of that class is – ColumnMetaDataInfo
Here is the code of our both the classes.


public class RowValue
{
	public string PatientName { get; set; }

	public decimal OrderAmount { get; set; }

	public int PatientAge { get; set; }

	public DateTime OrderDate { get; set; }
}

public class ColumnMetaDataInfo
{
	public string FieldName { get; set; }

	public int Width { get; set; }

	public string Caption { get; set; }

	public string Format { get; set; }

	public string Align { get; set; }

	public bool Display { get; set; }

	public Type DataType { get; set; }
}

Well, for demo purpose i have defined the two classes, In real scenario i have two separate tables in the database – one for actual data and another for column metadata. Now let’s use both of these classes in Model which we’ll pass it in our index.cshtml View.


public class GridViewModel
{
       public List<ColumnMetaDataInfo> Columns { get; set; }

       public List<RowValue> RowValues { get; set; }
}

Now its time to initialize the above viewModel class and fill the defined property with required data in “Home” controller’s action method.


public class HomeController : Controller
{

	public ActionResult Index()
	{
		var gridViewModel = new GridViewModel()
		{
			Columns = new List<ColumnMetaDataInfo>()
			{
				new ColumnMetaDataInfo
					{
						Caption = "Patient Name",
						FieldName = nameof(ColumnInfo.PatientName),
						Width = 50,
						Display = true,
						Format = "",
						Align = "left",
						DataType = typeof(string)
					},
				new ColumnMetaDataInfo
					{
						Caption = "Order Amount",
						FieldName = nameof(ColumnInfo.OrderAmount),
						Width = 15,
						Display = true,
						Format = "{0:C2}",
						Align = "right",
						DataType = typeof(decimal)
					},
				new ColumnMetaDataInfo
					{
						Caption = "Patient Age",
						FieldName = nameof(ColumnInfo.PatientAge),
						Width = 15,
						Display = false,
						Format = "{0:N2}",
						Align = "right",
						DataType = typeof(int)
					},
				new ColumnMetaDataInfo
					{
						Caption = "Order Date",
						FieldName = nameof(ColumnInfo.OrderDate),
						Width = 20,
						Display = true,
						Format = "{0:MM/dd/yyyy}",
						Align = "center",
						DataType = Type.GetType("System.DateTime")
					}
			},
			// Actual value to bind for each row
			RowValues = new List<ColumnInfo>()
			{
				new ColumnInfo { PatientName = "Krishnraj Rana", OrderAmount = 100.1M, PatientAge = 25, OrderDate = new DateTime(2016, 11, 25) },
				new ColumnInfo { PatientName = "Vishal Vagadia", OrderAmount = 200.1M, PatientAge = 35, OrderDate = new DateTime(2016, 11, 29) },
				new ColumnInfo { PatientName = "Birju Patel", OrderAmount = 300, PatientAge = 45, OrderDate = new DateTime(2016, 11, 28) }
			}
		};

		return View(gridViewModel);
	}
}

Now its time to bind the model with kendo grid and here is the code of Index.cshtml view in which we pass the above ViewModel class.


@model KendoGridDynamicColumn.Models.GridViewModel

@{
    ViewBag.Title = "Home Page";
}
	<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
	<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="~/Scripts/jquery-1.12.3.min.js"></script>
<script src="~/Scripts/kendo.all.min.js"></script>
<script src="~/Scripts/kendo.aspnetmvc.min.js"></script>


<div class="jumbotron">

<h2>Dynamic Kendo Grid</h2>


<h4>POC - V.1.0.0</h4>

</div>



<div class="row">

<div class="kendolist">
        @(Html.Kendo().Grid(Model.RowValues)
            .Name("grdDynamicCol")
            .Columns(columns =>
            {
                foreach (var column in Model.Columns)
                {
                    columns.Bound(column.FieldName).Title(column.Caption)
                        //.Visible(column.Display)
                        .Format(column.Format)
                        .Width($"{column.Width}%")
                        .HtmlAttributes(new { @style = $"text-align:{column.Align.ToLower()}" })
                        .HeaderHtmlAttributes(new { @style = $"text-align:{column.Align.ToLower()}" });
                }
            })
            .Pageable()
            .Sortable()
            .Resizable(resize => resize.Columns(true))
            .DataSource(dataSource => dataSource
                .Ajax()
                .Model(model =>
                {
                    foreach (var column in Model.Columns)
                    {
                        model.Field(column.FieldName, column.DataType);
                    }
                })
            )
        //.ColumnMenu()
        //.HtmlAttributes(new { @class = "gridview" })
        )
</div>

</div>

<script>
    $(document).ready(function () {

        HideGridColumn();
    });

    function HideGridColumn() {
        var grid = $("#grdDynamicCol").data("kendoGrid");
        @foreach (var column in Model.Columns.Where(col => col.Display == false))
        {
            <text>grid.hideColumn('@column.FieldName');</text>
        }
    }

    function gvchange(e) {
        var grid = $("#grdDynamicCol").data("kendoGrid");
        if (e.checked) {
            grid.showColumn(e.id);
        } else {
            grid.hideColumn(e.id);
        }
    }
</script>

and when grid binds, this is how it look in the browser.

result

That’s it. For any query or doubt, write in the comment section. Hope you enjoyed this post.

Tip of the day: Get the first element from the xml using LINQ to XML

Today, one of my colleague in my office asked me a question that how to get the first element from the XML string. In my previous organization, i had worked with XML but using old methodology. So i thought this is good opportunity to learn and explore LINQ to XML. After some googling i told him that using XElement class of LINQ to XML you can full fill your requirement.

So what exactly the requirement is? Well, In one of my application module, we have save some configuration information in XML format in the database. We need to display the first element of the XML in one label in another web page. So let’s see the XElement class of LINQ to XML in action.

What is XElement?

XElement is one of the fundamental class of LINQ to XML. You can use this class to parse the XML string, create the new element, change the content of the element etc. In this post we’ll use this class to parse the XML string. Well, by not going into much detail let’s see this practically.

Consider i have XML in below format.


<ApplicationName>
  <ModuleConfig AccountNo="Test123" Type="M56X35" Source="XML" PNKNumber="12345" Final="False" />
  <LibraryList>
    <Library1 FolderName="Vendor" />
    <Library12 FolderName="Dealer" />
    <Library123 FolderName="Dealer" />
  </LibraryList>
</ApplicationName>

Now his requirement is –
1). Read the first element from the “LibraryList” tag which is “Library1”.
2). Read the value of attribute “PNKNumber” from “ModuleConfig” tag.

Let’s create the new console application in visual studio.

Here is the solution for the first requirement.


using System.Linq;
using System.Xml.Linq;
using static System.Console;

class Program
{
	static void Main(string[] args)
	{
		string xml = @"<ApplicationName>
						  <ModuleConfig AccountNo=""Test123"" Type=""M56X35"" Source=""XML"" PNKNumber=""12345"" Final=""False"" />
						  <LibraryList>
							<Library1 FolderName=""Vendor"" />
							<Library12 FolderName=""Dealer"" />
						  </LibraryList>
					  </ApplicationName>";

		// First let us parse the xml string using XElement
		var parsedXML = XElement.Parse(xml);

		// Now get the first element from the <LibraryList>  tag.
		string firstElement = parsedXML.Element("LibraryList").Descendants()
                                     .FirstOrDefault().Name.LocalName;
		WriteLine("First Element is - {0}", firstElement);
		ReadLine();
	}
}

Output

First Element is – Library1

Same way to get the 2nd or upto nth tag, you can use the ElementAtOrDefault() method by passing tag index like this –


string elementAt = parsedXML.Element("LibraryList").Descendants()
                  .ElementAtOrDefault(1).Name.LocalName;
WriteLine("Element at Index 1 - {0}", elementAt);
// Output 
// Element at Index 1 - Library12
		
elementAt = parsedXML.Element("LibraryList").Descendants()
            .ElementAtOrDefault(2).Name.LocalName;
WriteLine("Element at Index 2 - {0}", elementAt);
// Output 
// Element at Index 1 - Library123

Here is the solution for the second requirement – Read the value of attribut “PNKNumber” from “ModuleConfig” tag.


using System.Linq;
using System.Xml.Linq;
using static System.Console;

class Program
{
	static void Main(string[] args)
	{
		string xml = @"<ApplicationName>
						  <ModuleConfig AccountNo=""Test123"" Type=""M56X35"" Source=""XML"" PNKNumber=""12345"" Final=""False"" />
						  <LibraryList>
							<Library1 FolderName=""Vendor"" />
							<Library12 FolderName=""Dealer"" />
                            <Library123 FolderName=""Vendor"" />
						  </LibraryList>
					  </ApplicationName>";

		// First let us parse the xml string using XElement
		var parsedXML = XElement.Parse(xml);

		// Read the value of attribute "LNKNumber" from "ModuleConfig" tag.
		// First we check whether "LNKNumber" attribute exists within this "ModuleConfig" tag or not.
		if (parsedXML.Element("ModuleConfig").Attributes().Any(x => x.Name == "PNKNumber"))
		{
			// Now we read the value of attribute "LNKNumber"
			var attrValue = parsedXML.Element("ModuleConfig").Attribute("PNKNumber").Value;
			WriteLine("Attribute value is - {0}", attrValue);
		}
		else
			WriteLine("Attribute PNKNumber does not exists in the xml.");
		
		ReadLine();
	}
}

Output

Attribute value is – 12345

Same way you can check for other attribute also. LINQ to XML really reduce the number of lines of code in your application for complex requirement. My above example is simple, so you can not find some major difference. Any ways that’s it for now. Hope you like this post.

Tip of the day: Replace your switch case statement with generic Dictionary in c#

As i said in my previous post that i got the chance to work in one legacy application where i also optimized some of the code. Today’s post is inspired from one of the situation that i found in that application.

Now let me explain you the requirement. We have used “Dev Express” as reporting tool for our application and we have developed more than 20 reports. Each report binds to one view model / custom class i.e. you can say its a data source to that report. To fill our view model / custom class, we have used one third party dll which will return one class object but in their own format. So we developed individual method to bind our view model / custom class from their object. Before you think let me tell you one thing, We cannot develop common method here to bind model as each report contain different property and have their own logic. In this scenario any one can think of switch case or if else condition. So as expected i found that type of code in this application. Alright now no more detail and let’s jump into the situation and showing you some code.

First let’s create the required view model / custom class to bind report. Here assume that we wants to develop two reports, so we require two view model class as shown below.


class FranchiseeSalesEmployeeViewModel
{
	public int EmployeeID { get; set; }

	public string EmployeeName { get; set; }

	public int ExpectedTargetAmount { get; set; }

	public int AchievedAmount { get; set; }
}

class HREmployeeViewModel
{
	public int EmployeeID { get; set; }

	public string EmployeeName { get; set; }

	public int NoOfInterviweTaken { get; set; }

	public int NoOfRejectedCandidate { get; set; }
}

Now let’s create the source object which we’ll get from other third party dll.


class SourceThirdPartyObject
{
	public int EmployeeID { get; set; }

	public string EmployeeName { get; set; }

	public string DepartmentName { get; set; }

	// -- Other dependent sub class for HR activity

	// -- Other dependent sub class for Sales activity

	// -- and many more...
}

First let’s see the code in which we’ll use switch case statement.


static void Main(string[] args)
{
	// First bind the third party object
	// In real scenario we'll get the data from the third party dll
	SourceThirdPartyObject sourceObj = new SourceThirdPartyObject() {
		EmployeeID = 1,
		EmployeeName = "Bill Gates",
		DepartmentName = "Admin"
	};

	var modelObj = BindReportModel("Report_Name1", sourceObj);

	// same way for other report like this
	// var modelObj = BindReportModel("Report_Name2", sourceObj);
	// Now bind this model class to your report
}

private static object BindReportModel(string reportName, SourceThirdPartyObject sourceObj)
{
	object modelObj = null;

	switch (reportName)
	{
		case "Report_Name1":
			return BindModelForReportName1(sourceObj);

		case "Report_Name2":
			return BindModelForReportName2(sourceObj);

		// Same way for report3, report4 etc...

		//case "Report_Name3":
		//    return BindModelForReportName1(sourceObj);

		// Case so on...
	};

	return modelObj;
}

private static HREmployeeViewModel BindModelForReportName1(SourceThirdPartyObject sourceObj)
{
	// This method contain some complex logic to bind this model
	HREmployeeViewModel hrEmpModel = new HREmployeeViewModel()
	{
		EmployeeID = sourceObj.EmployeeID,
		EmployeeName = sourceObj.EmployeeName,
		NoOfInterviweTaken = 10,
		NoOfRejectedCandidate = 4
	};

	return hrEmpModel;
}

private static FranchiseeHREmployeeViewModel BindModelForReportName2(SourceThirdPartyObject sourceObj)
{
	FranchiseeHREmployeeViewModel franchiseeModel = new FranchiseeHREmployeeViewModel()
	{
		EmployeeID = sourceObj.EmployeeID,
		EmployeeName = sourceObj.EmployeeName,
		ExpectedTargetAmount = 50000,
		AchievedAmount = 45000
	};

	return franchiseeModel;
}

Now let’s see the same code, but this time we’ll replace the switch case statement with pre-initialize generic dictionary.


private static Dictionary<string, Func<SourceThirdPartyObject, object>> 
	methodDictionary = new Dictionary<string, Func<SourceThirdPartyObject, object>>
{
	{"Report_Name1", (sourceObj) => BindModelForReportName1(sourceObj) },
	{"Report_Name2", (sourceObj) => BindModelForReportName2(sourceObj) }
	// Same way for report3, report4 etc...
};

static void Main(string[] args)
{
	// First bind the third party object
	// In real scenario we'll get the data from the third party dll
	SourceThirdPartyObject sourceObj = new SourceThirdPartyObject() {
		EmployeeID = 1,
		EmployeeName = "Bill Gates",
		DepartmentName = "Admin"
	};

	var modelObj = methodDictionary["Report_Name1"](sourceObj);
    //var modelObj = BindReportModel("Report_Name1", sourceObj);
}

As you can see in the above code that we have completely replace our BindReportModel() method with Dictionary. So here we have already initialize our dictionary object with report name as key and its related bind method as value using Func delegate.

Reference

That’s it guys. Hope you enjoyed this post. Thanks for reading this post.

Implement multiple interfaces with same function name and parameters in a class

Few days ago, I got the consultancy work for one of my friend’s firm. In their project i have had faced one interesting issue where there were two interfaces which contain same function name with same parameters and i needed to implement it in one class.

Rather than go into much theory let’s create this situation and see how we can get rid of this situation.

But first we see that what happen if we implement those interfaces in one class. So let’s create the required interfaces and class. So here we have our first interface named – “IStudent

public interface IStudent
{
	///<summary>
	/// Get list of student who have birthday today
	/// </summary>
	/// <returns></returns>
	DataTable GetTodaysBirthdayList(string date = "");
}

And here we have second interface.

public interface IStaff
{
	///<summary>
	/// Get list of staff member who have birthday today
	/// </summary>
	/// <returns></returns>
	DataTable GetTodaysBirthdayList(string date = "");
}

Now let’s try to implement these two interfaces in class.

public class School : IStudent, IStaff
{
	#region IStudent Members

	public DataTable GetTodaysBirthdayList(string date = "")
	{
		var dtList = new DataTable();
		// Business logic to get list of student who have birthday today
		return dtList;
	}

	#endregion

	#region IStaff Members

	public DataTable GetTodaysBirthdayList(string date = "")
	{
		var dtList = new DataTable();
		// Business logic to get list of staff who have birthday today
		return dtList;
	}

	#endregion
}

Alright let’s rebuild the application and see what happen. Whoaa… we get the error!

InterfaceError

Error: Type “School” already defines a member “GetTodaysBirthdayList”

I think no need to explain the error message. Now let’s remove any of the method from the class and rebuild the application. Error is gone now, But the problem is how can you know that which interface method you wanna call!

So to overcome to this situation we need to explicitly implement those interfaces. How ? Let’s see this practically.

public class School : IStudent, IStaff
{

	#region IStudent Members

	DataTable IStudent.GetTodaysBirthdayList(string date)
	{
		var dtList = new DataTable();
		// Business logic to get list of studnet who have birthday today
		Console.WriteLine("=> From IStudent interface.");
		return dtList;
	}

	#endregion

	#region IStaff Members

	DataTable IStaff.GetTodaysBirthdayList(string date)
	{
		var dtList = new DataTable();
		// Business logic to get list of staff who have birthday today
		Console.WriteLine("=> From IStaff interface.");
		return dtList;
	}

	#endregion

	// You cannot directly access explicitly implemented interface method
	// So we need two public method to call above interface method

	public DataTable GetTodaysBirthdayListOfStudent(string date = "")
	{
		IStudent objStudent = (IStudent)this;
		return objStudent.GetTodaysBirthdayList();
	}

	public DataTable GetTodaysBirthdayListOfStaff(string date = "")
	{
		IStaff objStaff = (IStaff)this;
		return objStaff.GetTodaysBirthdayList();
	}
}

By creating an instance of the above class you cannot directly access explicitly implemented interface method. For that we need two public method to call implemented interface method as shown in above class.

And now its time to call the above class method, like this –

static void Main(string[] args)
{
    var school = new School();
            
    var staffList = school.GetTodaysBirthdayListOfStaff();
    var studnetList = school.GetTodaysBirthdayListOfStudent();
}

And we are done. Well after seeing above code you might think that instead of following the above stuff i can make one common interface with common method and inherit that interface in IStaff and IStudent interface. Well Ofcouse you can do that, But consider a situation where you are using any third party DLL or in your existing application you cannot alter or made any changes due to any architectural restriction.

Alright, Hope you enjoyed this post. Thanks for reading this post.

How to achieve UNION ALL and UNION in LINQ

In one of my application, I came to a situation where I had to use UNION ALL like functionality for two enumerable list by using LINQ. So in today’s post we’ll learn about how we can achieve UNION and UNION ALL like functionality using LINQ. You can do a UNION operation using the Union method in LINQ and UNION ALL operation using the Concat method.

Let’s see this practically –

First we will learn about Union method.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionList = productsFromMicrosoft.Union(productsFromGoogle).ToList();

	Console.WriteLine(unionList);
}

UnionList

So as expected, UNION method excludes duplicates from the return set.

Now we will see Concat operator.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionAllList = productsFromMicrosoft.Concat(productsFromGoogle).ToList();

	foreach (var product in unionAllList)
	{
		Console.WriteLine(product);
	}
}

UnionAllList

The Concat method differs from the Union method because the Concat() method returns all the original elements in the input sequences. The Union method returns only unique elements.

Reference Link:

That’s it folks. Hope you like this post.

Resolve same namespace collision between two assembly

One of my friend worked in his freelancing project. In his project there were more than 4 class library projects used within his application. But by mistake he had created the same namespace with same class name within the two class library project. After adding the references of that class library in his main project, when he tried to create an instance of that class, he got the following error.


Error 1
The type ‘Lib1.PatientDataContext’ exists in both ‘d:\TFS\Lib1\bin\Debug\Lib1.dll’ and ‘d:\TFS\Lib2\bin\Debug\Lib2.dll’

It means the C# compiler gets confused that which assembly it has to use for creating an instance of the class. That’s why it throws an above error.

So he asked me to resolve his issue. well, i have never faced this type of error before. So i did some googling and came to the solution that by using extern alias provided in C#, above issue can be resolve.  How ? Let’s see this practically by creating that scenario.

In Visual studio, let’s create one console application and named it as – NameSpaceCollisionApp. Now within the same solution of the application add the two new class library project. In each class library assembly add one new class named – PatientDataContext.cs. But keep in mind that both of these class are within same namespace. The code of both the class looks like this –

ClassLibrary1 / PatientDataContext.cs

namespace DataServiceFactory.DataContext
{
    public class PatientDataContext
    {
        public PatientDataContext()
        {
        }

        public override string ToString()
        {
            return "From Class Library 1";
        }
    }
}

ClassLibrary2 / PatientDataContext.cs

namespace DataServiceFactory.DataContext
{
    public class PatientDataContext
    {
        public PatientDataContext()
        {
        }

        public override string ToString()
        {
            return "From Class Library 2";
        }
    }
}

When you build the application, you’ll get the error highlighted above. So let’s resolve it by following the below steps.

Step-1: In the solution explorer, expand the “References” folder and  select the required assembly name then right click on it and open its property window.

Service1Property

Step-2: In the property window, change the aliases name from “global” to “Service1 (Whatever you want)”.

ChangeAliase

Step-3: Same way follow the Step-2 for ClassLibrary2 reference also.

Step-4: Now to use it in your main application, you need to add – extern alias “alias name”; line of code to the top of your source file, something like this –

extern alias Service1;
extern alias Service2;

using System;

namespace NameSpaceCollision
{
    class Program
    {
        static void Main(string[] args)
        {
            var object1 = new Service1.DataServiceFactory.DataContext.PatientDataContext();

            var object2 = new Service2.DataServiceFactory.DataContext.PatientDataContext();

            Console.WriteLine(object1);
            Console.WriteLine(object2);
            Console.ReadLine();
        }
    }
}

And we are done. Hope you like this post and hope it may help to my future readers. You can find the demo application from here.

 

Get list of property value from another list based on supplied property name using indexer in c#

Recently in one of our MVC application, I have had a requirement to read property value from one generic list by using property name, i.e. For exa. Consider one function named – GetPropertyValueList() which has one parameter named – propertyName. By using that parameter this function return the List<object> (List of property value).

OK, Let me explain further my requirement in detail. One of our end user wanted to migrate some of his customers manually. So I had to develop one page which displays specific customer list retrieve from the database. Now this page contains different sections to display list of property value. For exa. “LastName” property section displays only list of customer’s last name in radio-button list. Same way in other section let say “Age” property section displays only list of customer’s age in radio-button list. Same way for other properties too of customer class.

Now let’s see this practically. To achieve this functionality I need to develop several modal classes in my application’s modal layer. For demo purpose I have shown you these things in action in one console application in this post.

My first modal class is a normal “Customer” class.

public class Customer
{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

    public string MobileNo { get; set; }

    // Same way there are more than 20 properties in my mvc application
    //public string Address { get; set; }
}

My second modal class is “SourceCustomerInfo” class.

public class SourceCustomerInfo
{
	///<summary>
	/// To get the name of property at run time of Customer class
	/// </summary>

	public Customer customerField { get; set; }

	///<summary>
	/// Contain list of customers from database to migrate
	/// </summary>

	public List<Customer> customerList { get; set; }

}

 

In SourceCustomerInfo class first property customerField is used to get list of property value from customerList property. You can see the detail usage of this class in our console application.

My third modal class is “CustomerFieldValueList” class.

public class CustomerFieldValueList
{
	///<summary>
	/// Contain name of the property to render in the lable
	/// </summary>

	public string FieldName { get; set; }

	///<summary>
	/// Contain list of property value to render in the radio-button list
	/// </summary>

	public List<object> FieldValueList { get; set; }

}

Why I need to develop this modal ? Well, my MVC View renders all labels and its related radio-button list dynamically (By using above modal class). In the above class first property FieldName is used as label in MVC View and second property FieldValueList is used to fill radio-button list. Hmmm sorry for my bad English, But Here is the screen-shot of this class of what you’ll get at run time in each property for better understanding.

FieldValueList

All right, now the key point is here. To achieve my key requirement I need to use “Indexers” – a very special type of class member in C#. An indexer allows an object to be indexed like an array. The main use of “indexers” is to support the creation of specialized arrays or list. For more information on “Indexers” refer this MSDN link.

Here is the indexer that I have added in “Customer” class.

public class Customer
{

	///<summary>
	/// Get the value by supplied property name
	/// </summary>
	/// <param name="propertyName"></param>
	/// <returns></returns>
	public object this[string propertyName]
	{
		get
		{
			return this.GetType().GetProperty(propertyName).GetValue(this, null);
		}
	}

	public string FirstName { get; set; }

	public string LastName { get; set; }

	public int Age { get; set; }

	public string MobileNo { get; set; }

	// Same way there are more than 20 properties in my mvc application
	//public string Address { get; set; }

}

As you can see that I have read property value by using propertyName as parameter thru reflection in indexer.
Let’s combine all of these modal classes in one console application and see it in action. Here i have show you only the Main() method code. You can download the full source code from here.

static void Main(string[] args)
{
	var sourceCustomerInfo = new SourceCustomerInfo() {customerField = new Customer() };

	// Get the name of all property of customer class using reflection in array.
	var arrayPropNames = sourceCustomerInfo.customerField
							.GetType()
							.GetProperties()
							.Select(p => p.Name)
							.ToArray();
	// Fill the Customer list
	sourceCustomerInfo.customerList = new List<Customer>
	{
		new Customer() { FirstName="Kapil", LastName="Dev", Age=55, MobileNo="123" },
		new Customer() { FirstName="Sachin", LastName="Tendulkar", Age=45, MobileNo="123" },
		new Customer() { FirstName="Rahul", LastName="Dravid", Age=50, MobileNo="123" }
	};

	var fieldValueList = new List<CustomerFieldValueList>();
	//Now we iterate thru each property name that we already get in array
	foreach (var propertyName in arrayPropNames)
	{
		// Check propertyName is not blank or not our indexers
		if (!string.IsNullOrEmpty(propertyName) && propertyName != "Item")
		{
			// Initialize new instance of CustomerFieldValueList class
			var customerFieldValueList = new CustomerFieldValueList();

			// Set customerField with current property name
			customerFieldValueList.FieldName = propertyName;

			// Get the list of property value by supplied propertyName parameter using indexers
			// from the customerList property of SourceCustomerInfo class.
			customerFieldValueList.FieldValueList = sourceCustomerInfo.customerList.Select(p => p[propertyName]).ToList();

			// Now add this class instance into fieldValueList List.
			fieldValueList.Add(customerFieldValueList);
		}
	}

	// Now we are ready to render it in our MVC View.
	// Here we'll render it in console.
	fieldValueList.ForEach(obj =>
		{
			// Display FieldName value after 15 spaces
                        Console.WriteLine("FieldName  => {0, 15}", obj.FieldName);

			obj.FieldValueList.ForEach(lst =>
				{
					// Display property value after 15 spaces
					Console.WriteLine("     List  => {0, 15}", lst);
				});
			Console.WriteLine("=========================================");
		});

	Console.ReadLine();
}

And here is the output in console.

FinalResult

That’s it folks. Hope you like this post. Leave your comments.

ASP.NET MVC: Post a list or collection of complex types with non-sequential indices

In ASP.Net MVC when you post your form then DefaultModelBinder bind your form’s submitted value. Now what if your model is list / collection of complex type which you want to post and the case is become even worse when the sequence or let say index is not maintained. Okay let’s see it in detail.

In one of my project developed in MVC 4, I had a requirement to bind list of complex type model to view. Furthermore, from this view user can add or remove items using Jquery / JavaScript before submitting it. Let’s create this situation. Let say, I want to add more than one students in “ClassRoom” table in single submit. So, I have model named – “ClassRoomViewModel” which contain property “Students” of type List.

public class ClassRoomViewModel
{
	public List<Student> Students { get; set; }
}

public class Student
{
	public string StudentName { get; set; }
	public int Age { get; set; }
}

As this is student entry form. So it opens as an empty form using below Action method that renders a view.

public ActionResult Index()
{
	var classRoom = new ClassRoomViewModel()
	{
		Students = new List<Student>()
	};
	
	return View(classRoom);
}

Now let’s create a view which call another partial view. Here is the code snippet.

@model PostListWithBrokenSequence.Models.ClassRoomViewModel

@{
	ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>Enroll Students</h1>
</div>
<div class="row">
	@using (Html.BeginForm())
	{
		<div class="col-md-4">
			<h2>Add Student</h2>
			@Html.Partial("_PartialAddStudent", 0)

			@Html.ActionLink("Add Student", "LoadBlankFormView", null, new {@id = "lnkAddStudent", @class = "btn btn-primary"})
			<button class="btn btn-default" type="submit"> Save </button>
		</div>
	}
</div>

And for partial view named – “_PartialAddStudent.cshtml”. here is code snippet.

@model int

<div class="form-horizontal" id="dv_@Model" data-rownum="@Model">
    <!-- <input type="hidden" name="Students.Index" value="@Model" /> -->
    <div class="form-group">
        @Html.Label("Name", new { @class = "control-label" })
        <div>
            @Html.TextBox("Students[" + Model + "].StudentName", "", new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.Label("Age", new {@class = "control-label"})
        <div>
            @Html.TextBox("Students[" + Model + "].Age", "", new {@class = "form-control"})
        </div>
    </div>
    <div class="form-group">
        <a href="#" class="deleteStudent btn btn-primary">Remove</a>
    </div>
    <hr/>
</div>

When you run the application it looks like this in browser.

AddStudentForm

To bind complex objects like list etc., we need to provide an index for each row as shown in “_PartialAddStudent” view. Yes, Index which start with 0 and incremented by 1. That’s why I render “_PartialAddStudent” view with 0 index in “Index” view using HTML.Partial() method. As you see in the above code that I have manually build names and ids of all control in the partialview. Well you can use templated helper by creating strongly typed partialview in “~/Views/Shared/ EditorTemplates” and achieve the same result with less code by using the built-in Html.EditorFor() or Html.EditorForModel() helpers, but in our case it would be difficult to use as we add and remove rows dynamically from the DOM.

All-right coming to the point, Index must be in sequence when posting the form with list of complex object, otherwise MVC DefaultModelBinder can’t able to bind it to our complex object (In our case its List<Student>). Okay let’s see it practically. As you see in above image, “Add Student” button which dynamically add our partialview (row) to DOM using jquery. Below is the code snippet.

$('#lnkAddStudent').click(function() {
	var index = parseInt($('.form-horizontal:last').data('rownum')) + 1;

	$.ajax({
		url: this.href + '/' + index,
		type: "GET",
		cache: false,
		success: function(html) {
			$('.form-horizontal:last').after(html);
		}
	});
	return false;
});

When you click on “Add button”, it makes AJAX request and call “LoadBlankFormView” action method which append partialviews’ html to DOM.

public ActionResult LoadBlankFormView(int id)
{
	return PartialView("_PartialAddStudent", id);
}

Now run the application and click on “Add Student” button 2 times and then fill the form and submit the form by click on “Save” button.

StudentFormWithData

As there is no broken index so DefaultModelBinder binds our complex object correctly when you debug the application, you can see all records posted back correctly as show in below image.

FormPostWithProperIndex

Now let’s remove any of the row which break the index and makes the index as 0, 2, ..etc and our HTML in DOM looks like this –

<form action="/" method="post">        
<div class="col-md-4">
    <h2>Add Student</h2>
	<div>
		<div class="form-group">
			Name
			<div class="col-md-10">
				<input class="form-control" name="Students[0].StudentName" type="text" value="John Miller" />
			</div>
		</div>
		<div class="form-group">
			Age
			<div class="col-md-10">
				<input class="form-control" name="Students[0].Age" type="text" value="65" />
			</div>
		</div>
		<hr />
	</div>
	<div>
		<div class="form-group">
			Name
			<div class="col-md-10">
				<input class="form-control" name="Students[2].StudentName" type="text" value="Krishn" />
			</div>
		</div>
		<div class="form-group">
			Age
			<div class="col-md-10">
				<input class="form-control" name="Students[2].Age" type="text" value="90" />
			</div>
		</div>
	</div>
</div>
</form>

See the index in above code. Here is the “Remove” button code which removes row from the DOM.

$(document.body).on("click", "a.deleteStudent", function() {
	$(this).parents('div.form-horizontal:first').remove();
	return false;
});

Now when you post the above form with broken indices, you’ll lost the data from where the sequence get break. See the below image.

FormPostWithBreakIndex

Don’t worry, to overcome this problem we just need an extra hidden input field with the name – “list/collectionName.Index” for each item we need to bind to the list. In our case hidden input field name should be “Students.Index”.

<input name="Students.Index" type="hidden" value="@Model" />

The name of each of these hidden inputs must be the same with unique values. So after adding it to our “_PratialAddStudent” view, run application again and add 2 new records, remove any middle one and all. After doing all of these test cases at the end, look at rendered html code with broken sequence now looks like this –

ViewSourceOfBrokenIndices

Now click on “Save” button and post that form. Even with broken sequence DefaultModelBinder bind your form’s value correctly!!. You can download the sample demo project here. If you have any query then mail me or leave your comments.

That’s it guys for now. Hope you enjoy this post. Thank you.

Wcf parameter validation using IParameterInspector in WCF REST Service

In this blog post we’ll see about a very important feature of the WCF and its extensibility and how it help us to control the behavior of the service. For one of our project, we have developed WCF REST Api to use it in iPhone App. One day we found one bug that one of the wcf service method was not returning the expected output because one input parameter value passed as blank. So we needed to validate parameter before service executed. After some research i have found this IParameterInspector interface which resolved my problem.

Let’s try to understand this powerful feature of wcf. IParameterInspector interface resides in System.ServiceModel.Dispatcher namespace which allows us to inspecting parameters passed in each operation before the call / service is executed and after the response is returned.

This interface contains only two methods:

public interface IParameterInspector
{
	void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState);
	object BeforeCall(string operationName, object[] inputs);
}

AfterCall (string, object[], object, object) :-  Called after client calls are returned and before service responses are sent.

BeforeCall (String, Object[]) :- This method invoked after parameters are deserialized but before they are dispatched to the service operation.

Okay we don’t go too much in theory. So let’s implement the IParameterInspector interface to create a custom parameter inspector which can view and validate the parameters before the call or after the call and see how it throws fault exception if any parameter value not validated.

Here i assume that WCF Service project is already created and let’s create our custom class which implements IParameterInspector interface. Well you can also create separate class library to create custom inspector class and then add this library reference to wcf project.

public class ValidateParameterInspectorAttribute : Attribute, IParameterInspector, IOperationBehavior
{

	public object BeforeCall(string operationName, object[] inputs)
	{
		InputParams.StartValidatingParameters(operationName, inputs);
		return null;
	}

	public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
	{
	}
	
	public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
	{
	}

	public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
	{
		dispatchOperation.ParameterInspectors.Add(this);
	}
}

To attach parameter inspector as an attribute to service operation, i have derived it from “Attribute” class and to add it in service i have implemented “IOperationBehavior” interface. Using “ApplyDispatchBehavior()” method you can add parameter inspector in the DispatchOperation object as shown in above code. Below code snippet shows how you can attach the attribute to an operation.

[ServiceContract]
public interface IStudentService
{
	
	[ValidateParameterInspector]
	[OperationContract]
	[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
			UriTemplate = "/SaveStudentRecord")]
	Response SaveStudentRecord();
	
}

That’s it. No need to do change in web.config file using above approach.

Now when i call SaveStudentRecord() service method from the iPhone app or from the “Advanced Rest Client” then parameter inspector first invoke “BeforeCall()” method, which further call another method of “InputParams” class to validate input parameter as show in below code snippet.

public class InputParams
{
	internal static void StartValidatingParameters(string operationName, object[] inputs)
	{
		var methodParam = inputs.FirstOrDefault() as StudentViewModel;

		if (methodParam != null &&
			string.IsNullOrEmpty(methodParam.StudentName))
		{
			LogErrorMessage(ThrowRequiredValueException(operationName, "StudentName"));
			ThrowFaultException();
		}
		else if (string.IsNullOrEmpty(methodParam.BirthDate))
		{
			LogErrorMessage(ThrowRequiredValueException(operationName, "BirthDate"));
			ThrowFaultException();
		}
		else if (methodParam.RoleID <= 0)
		{
			LogErrorMessage(ThrowRangeException(operationName, "RoleID"));
			ThrowFaultException();
		}
		else if (methodParam.Standard <= 0)
		{
			LogErrorMessage(ThrowRangeException(operationName, "Standard"));
			ThrowFaultException();
		}
		
	}
	
	private static void ThrowFaultException()
	{
		WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
		var wfc = new WebFaultException<Response>(new Response
			(
				false,
				"Oops, Invalid parameter found!"
			), System.Net.HttpStatusCode.OK);
		throw wfc;
	
	}
	
	private static Exception ThrowRangeException(string methodName, string parameterName)
	{
		return new ArgumentException(string.Format("API Name: {0} - Parameter cannot be less than zero.", methodName), parameterName);
	}

	private static Exception ThrowSameValueException(string methodName, string parameter1, string parameter2)
	{
		return new ArgumentException(string.Format("API Name: {0} - Parameter {1} value must not be the same as {2}.", methodName, parameter1, parameter2));
	}

	private static Exception ThrowRequiredValueException(string methodName, string parameterName)
	{
		return new ArgumentNullException(parameterName, string.Format("API Name: {0} - Parameter cannot be blank or null.", methodName));
	}

}

As you see in above code that actual error message would logged for developers’ use and at client side it display only general error message. Well, you can change in above code as per your application architecture and requirement. For demo purpose i have show you only blank value validation and range validation. One important thing is – this is not production-ready code.

And that’s it for now. Hope you enjoyed this post. Leave your comments.