Skip to main content

Posts

Showing posts from February, 2015

How to create instance of generic class using reflection

In this post I am going to show how to create instance of generic class using c# reflection.The trick is to use the MakeGenericType to make the argument(s) and then call create Instance. Here is a code snippet:Type d1 = typeof(List<>); Type[] typeArgs = { typeof(string) }; Type makeme = d1.MakeGenericType(typeArgs); object o = Activator.CreateInstance(makeme); List<string> itsMe = o as List<string>;

How to host wcf service in IIS using Tcp protocol

In this post I am going to show you how to host WCF service in IIS using TCP protocol.By default, the TCP WCF activation service is not enabled on your machine. You can follow these steps to enable the TCP activation for WCF services:
Go to Control Panel | Programs | Turn Windows features on or off. Expand the Microsoft .Net Framework 3.5.1 node on Windows 7 Check the checkbox for Windows Communication Foundation Non-HTTP Activation on Windows 7
Next,Create the IIS application to host the WCF application using TCP protocol.Follow these steps
Open run command and type inetmgrCreate a new application and point to physical folder.Select the DefaultAppPoll  and make sure your default app pool is a .NET 4.0.X application pool.Right-click on web application, select Manage Application | Advanced Settings, and then add net.tcp to Enabled Protocols.(Make sure you use all lowercase letters and separate it from the existing HTTP protocol with a comma)
Now the service is hosted in IIS using th…

Todo App using Web API and Knockout

In this post I am going to show you how to develop a todo app using knockoutjs and microsoft Web API.What is knockoutjs”Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore: a clear separation between domain data, view components and data to be displayed.”-WikipediaKnockout is built around three core features: Observables and dependency tracking Declarative bindings Templating Before diving to example code first go through the following http://knockoutjs.com/documentation/observables.html#mvvm_and_view_modelsOpen visual studio and create a new Web API applicationOpen Package Manager console and install knockoutjs as shown in below imageRight click the Model folder and add a new class named TodoItem and paste following code. public class TodoItem { public int Id { get; set; } public string Title { get; set; } public bool Done { get; set; } }Right click the model f…

How to enable CORS in web API2

In this post I am going to show you a very simple and useful tips that how to enable CORS in web API2.
What is CORS
Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from anotherdomain outside the domain from which the resource originated
How to enable in CORS in web API2
In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:Install-Package Microsoft.AspNet.WebApi.Cors Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RoutePa…

How to convert DataSet to List

In this post I am going to show you a very useful c# code snippet that convert DataSet to List<T>. public static List<T> ToCollection<T>(this DataTable dt) { List<T> lst = new List<T>(); Type tClass = typeof(T); PropertyInfo[] pClass = tClass.GetProperties(); List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList(); T cn; foreach (DataRow item in dt.Rows) { cn = (T)Activator.CreateInstance(tClass); foreach (PropertyInfo pc in pClass) { DataColumn d = dc.Find(c => c.ColumnName == pc.Name); if (d != null) { if (item[pc.Name] != DBNull.Value) { pc.SetValue(cn, (item[pc.Name]), null); } } } …

Self host web API

In this post I will show you how to create web api that run outside IIS application.
Open visual studio and create a console application

Add the Web API and OWIN Packages From the Tools menu, click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Right click  the project and add new class named Startup.cs and add following code snippet in it
public class Startup { // This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", default…

How to create Fibonacci series using Linq

In this post I am going to show you how to generate fiboancci number series using Linq.What is Fibonacci series : The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. public static IEnumerable<int> Fib(int n) { List<int> fibs = new List<int>(); Enumerable.Range(0, n) .ToList() .ForEach(f => fibs.Add((f <= 1 ? 1 : fibs[f - 2] + fibs[f - 1]))); return fibs; }

How to create chat application using microsoft asp.net signalr

open visual studio and create a new MVC application
Select Empty MVC application

Open Package Manager Console and install SignalR

Right click on project and add new class ChatHub and inherit from Hub class that resides in Microsoft.AspNet.SignalR

public class ChatHub:Hub { //this method is called when client send message public void sendMessage(string message) { //this method brodcast message to all connected client Clients.All.newMessage(message); } } Right click on project and add new class named Startup and add following code inside it
public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } Create a new html page and add following markup inside it.You can see that I have added three JavaScript lib :jquery,jqery-signalr* and  signalr/hubs.Signalr/hubs contains functions for interacting with server side hub class and also it generated automatic…

Access to the Hubs from outside of the Hub class

The Clients dynamic property of the Hub gives you access to all clients connected to the hub within the hub class. However, what if you would like to push data to the clients from outside of the Hub class.Use following code snippet and replace HubClass with your own class and get access of the signalr clients and server dynamic properties/methods.var myHub = GlobalHost.ConnectionManager.GetHubContext<HubClass>();

Compare Linq and Ruby Part1

Linq Where equivalent in RubyOne of the most used (just guessing) LINQ methods would be Where(), in .NET allows you to provide a Lambda that is used to filter a collection of objects var ints = new[] { 13, 42, 96, 2, 83 }; var evens = ints.Where(x = > x % 2 == 0); foreach(int i in evens) { Console.WriteLine(i); }And in Ruby this functionality would be achieved with select.ints = [13, 42, 96, 2, 83] evens = ints.select { | x | x % 2 == 0 } puts evensLinq OrderBy expression equivalent in RubyTo sort a sets of elements in c# with Linq we use OrderByvar words = new[] { "Perl", "c#", "ruby", "java" }; var ordered = words.OrderBy(x = > x); ordered.ToList().ForEach(Console.WriteLine);And in Ruby this functionality would be achieved with sort. words = ["Perl", "c#", "ruby", "java"] ordered = words.sort puts orderedLinq Select expression equivalent in RubyIn .NET to convert a set of items to anot…

How to post data using HttpClient

In this post I will show you how to post data to web api using HttpClient.

privatestatic async Task PostJSON() { HttpClient httpClient = new HttpClient(); HttpContent content = new StringContent(@"{ ""Username"": """ + "etc." + @"""}"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await httpClient.PostAsync("http://myapi.com/authentication", content); string statusCode = response.StatusCode.ToString(); } /// <summary>/// Post Key/Value/// </summary>/// <returns></returns>privatestatic async Task Post() { HttpClient client = new HttpClient(); var values = new Dictionary<string, string>(); values.Add("author", "santosh"); values.Add(…