How to create a simple Http Server in NodeJs

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.
In this post I will show you how to create a simple Http Server using node.js Before diving into code let us first install node.js from following link.

https://nodejs.org/

Once the node.js installed.Open the terminal window and type following command.

node –version

image

If you see similar output then node.js is installed on your machine.

Open any text editor and paste following code into it and save it as Sever.js.

 

var http = require("http");

function requestHandler(req, res) {

	res.writeHead(200, { 'Content-Type': 'text/html' });
	res.write("Hello world");
	//end the response
	res.end();

}
//Create http server
var server = http.createServer(requestHandler);
server.listen(8000, function () {
	console.log("Server is up and running");
})

open command prompt and type following command.

node Server.js

image

Convert colum to row without using unpivot operator

In this post I will show you how to convert column to row in SQL.For this post I am going to use following table which have three colum stu_name,sibject and marks.

image

SELECT  stu_name,
        MAX(CASE WHEN subject = 'ECO' THEN marks
                 ELSE 0
            END) ECO,
        MAX(CASE WHEN subject = 'HIS' THEN marks
                 ELSE 0
            END) HIS,
        MAX(CASE WHEN subject = 'MAT' THEN marks
                 ELSE 0
            END) MAT,
        MAX(CASE WHEN subject = 'GEO' THEN marks
                 ELSE 0
            END) GEO,
        MAX(CASE WHEN subject = 'SCI' THEN marks
                 ELSE 0
            END) SCI
FROM    col_to_rows
GROUP BY stu_name
image

How to implement Stack using linked list

Stacks are easier to implement using linked lists. There is no need to set a limit on the size of the stack

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkedlistUsingStack
{
    public class Node
    {
        public int Data { get; set; }
        public Node Next { get; set; }
        public Node(int data)
        {
            this.Data = data;
        }
    }
    public class Stack
    {
        private Node _stackTop;

        public void Push(int newValue)
        {
            Node newNode = new Node(newValue);

            newNode.Next = _stackTop;
            _stackTop = newNode;

        }
        public bool IsEmpty()
        {
            return _stackTop == null;
        }
        public int Pop()
        {
            Node temp = _stackTop;
            var data = temp.Data;
            _stackTop = temp.Next;
            return data;
        }
        public void Print()
        {
            Node current = _stackTop;
            while (current != null)
            {
                Console.WriteLine(current.Data);
                current = current.Next;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();
            st.Push(1);
            st.Push(2);
            st.Push(3);
            Console.WriteLine("Before Pop");
            st.Print();
            st.Pop();
            st.Pop();
            Console.WriteLine(st.IsEmpty());
            Console.WriteLine("After Pop");
            st.Print();
        }
    }
}

How to Find if Linked List contains Loops or Cycles in C#

In this post I will show you how to detect loop in linked list.

We can find the loop in the linked list via Floyd’s Cycle-Finding Algorithm, explained here.

The algorithm is pretty straightforward:

  1. We start at the beginning of the linked list with two pointers.
  2. The first pointer is incremented through each node of the list. The second pointer moves twice as fast, and skips every other node.
  3. If the linked list contains a loop, these two pointers will eventually meet at the same node, thus indicating that the linked list contains a loop.

.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algo
{
    public class Node
    {
        public Node Next { get; set; }
        public int Value { get; set; }
        public Node(int value)
        {
            this.Value = value;
        }

    }
    public class LinkedList
    {
        private Node _head;
        public LinkedList()
        {

        }
        public void AppendLast(Node newNode)
        {
            if (_head == null)
            {
                _head = newNode;
            }
            else
            {
                Node current = _head;
                while (current.Next != null)
                {
                    current = current.Next;
                }
                current.Next = newNode;
            }
        }
        public override string ToString()
        {
            Node current = _head;
            StringBuilder builder = new StringBuilder();
            while (current != null)
            {
                builder.Append(current.Value + "->");
                current = current.Next;
            }
            return builder.ToString();
        }
        public bool IsCycle()
        {
            Node slow = _head;
            Node fast = _head;
            while (fast != null && fast.Next != null)
            {
                fast = fast.Next.Next;
                slow = slow.Next;
                if (slow == fast)
                    return true;
            }
            return false;

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LinkedList list = new LinkedList();
            list.AppendLast(new Node(10));
            list.AppendLast(new Node(20));
            list.AppendLast(new Node(30));
            Node cycle = new Node(40);
            list.AppendLast(cycle);
            list.AppendLast(new Node(60));
            list.AppendLast(cycle);

            if (list.IsCycle())
            {
                Console.WriteLine("Linked List is cyclic as it contains cycle or loop");
            }
            else
            {
                Console.WriteLine("LinkedList is not cyclic, no loop or cycle found");
            }



        }
    }
}

Reverse a given linked list in c#

 

In this post I will show you how to reverse a  given linked list in c#.For example a given linked list as show below

10->20->30-NULL

then output should be

30->20->10-NULL

 

image

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algo
{
    public class List
    {
        public List Next { get; set; }
        public int Value { get; set; }
        public List(int value)
        {
            Value = value;
        }
        public override string ToString()
        {
            List current = this;
            StringBuilder builder = new StringBuilder();
            while (current!=null)
            {
                builder.Append(current.Value + "->");
                current = current.Next;
            }
            return builder.ToString();
        }
        public List ReverseList()
        {
            List prev = null;
            List next = null;
            List current = this;
            while (current!=null)
            {
                next = current.Next;
                current.Next = prev;
                prev = current;
                current = next;
            }
            return prev;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List list = new List(10);
            list.Next = new List(20);
            list.Next.Next = new List(30);
            Console.WriteLine(list);
            var rev = list.ReverseList();
            Console.WriteLine(rev);
        }
    }
}

How to check a tree is a binary tree of not

This is continuation of my post How to create binary tree in c#.In this post I will show you how to check a given tree is a binary tree or not.

  public bool isBST()
        {
            return (IsBST(_root));
        }
private bool IsBST(Node node)
        {
            if (node == null) return (true);

            // do the subtrees contain values that do not 
            // agree with the node? 
            if (node.Left != null && FindMaxValue(node.Left) > node.Data) return (false);
            if (node.Right != null && FindMinValue(node.Right) <= node.Data) return (false);

            // check that the subtrees themselves are ok 
            return (IsBST(node.Left) && IsBST(node.Right));
 } 

Mirror of a binary tree

 

This is continuation of my post How to create binary tree in c#.In this post I will show you how convert a given binary tree into it’s mirror image.

/**
Changes the tree into its mirror image.

So the tree...
       4
      / \
     2   5
    / \
   1   3

is changed to...
       4
      / \
     5   2
        / \
       3   1

Strategy:Uses a recursive helper that recurs over the tree, swapping the left/right pointers.

 public void MirrorTree()
        {
            MirrorTree(_root);
        }

private void MirrorTree(Node node)
        {
            if (node != null)
            {
                // do the sub-trees 
                MirrorTree(node.Left);
                MirrorTree(node.Right);

                // swap the left/right pointers 
                Node temp = node.Left;
                node.Left = node.Right;
                node.Right = temp;
            }
 } 

How to print out all path from root to leaf of a given binary tree

This is continuation of my post How to create binary tree in c#.In this post I will show you how to print all path from root to leaf of a given binary tree in c#.Let’s consider following binary tree.

             *       4
             *    2     5
             *  1    3    

For above tree there are three path from root to leaf

Path 1 : 4 2 1

Path 2: 4 2 3

Path 3: 4 5

  public void PrintPath()
        {
            int[] path = new int[100];
            printPaths(_root, path, 0);
        }
        private void printPaths(Node node, int[] path, int pathLen)
        {
            if (node == null) return;

            // append this node to the path array 
            path[pathLen] = node.Data;
            pathLen++;

            // it's a leaf, so print the path that led to here 
            if (node.Left == null && node.Right == null)
            {
                PrintArray(path, pathLen);
            }
            else
            {
                // otherwise try both subtrees 
                printPaths(node.Left, path, pathLen);
                printPaths(node.Right, path, pathLen);
            }
        }

        private void PrintArray(int[] path, int pathLen)
        {
            for (int i = 0; i < pathLen; i++)
            {
                Console.Write(path[i] + " ");
            }
            Console.WriteLine();
        }

Given a binary tree, find path sum

Given a tree and a sum, returns true if there is a path from the root  down to a leaf, such that adding up all the values along the path  equals the given sum.let’s consider the following binary tree as an example and path sum value is 9.

       4
      / \
     2   5
    / \
   1   3

Root-to-leaf paths:
   path 1: 4 2 1
   path 2: 4 2 3
   path 3: 4 5

You can see that there are two path that gives sum 9 (Path2 and Path 3).Traverse the tree from root to leaves in top down fashion and subtract the node value from the sum  and check to see if the sum is 0 when you run out of tree.

 public bool HasPathSum(int sum)
        {
            return HasPathSum(_root, sum);
        }
        private bool HasPathSum(Node root, int sum)
        { 
            // return true if we run out of tree and sum==0 
            if (root == null)
                return sum == 0;
            else
            {
                int subSum = sum - root.Data;
                return (
                    HasPathSum(root.Left, subSum)
                    || HasPathSum(root.Right, subSum)
                    );
            }

        }


 

How to find min or max value in a given binary tree

This is continuation of my post How to create binary tree in c#.In this post I will show you how to find max or min value in a given binary tree.

Min Value: Loop down to find the leftmost leaf

Max Value: Loop down to find the rightmost leaf

     public int FindMinValue()
        {
            return FindMinValue(_root);
        }

        private int FindMinValue(Node root)
        {
            if (root == null)
                return -1;
            else
            {
                Node current = root;
                while (current.Left!=null)
                {
                    current = current.Left;
                }
                return current.Data;

            }
        }
        public int FindMaxValue()
        {
            return FindMaxValue(_root);

        }

        private int FindMaxValue(Node root)
        {
            if (_root == null)
                return -1;
            else
            {
                Node current = root;
                while (current.Right!=null)
                {
                    current = current.Right;
                }
                return current.Data;
            }
        }

How to calculate max depth of given binary tree in c#

This is continuation of my post How to create binary tree in c#.In this post I will show you how to calculate max depth of a given binary tree in c#.

MaxDepth of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.

  public int MaxDepth()
        {
            return MaxDepth(_root);
        }
        private int MaxDepth(Node root)
        {
            if (root == null)
                return -1;
            // compute the depth of each subtree 
            else
            {
                int leftDepth = MaxDepth(root.Left);
                int rightDepth = MaxDepth(root.Right);
                //Return max of left or right tree.
                return 1 + Math.Max(leftDepth, rightDepth);
            }
        }

How to calculate size of binary tree

This is continuation of my post How to create binary tree in c# .In this post I will show you how to find size of binary tree.Size of binary tree is number of nodes in a given tree.

Following is the recursive implementation of size function

  //Compute the number of nodes in a tree. 
        public int Size()
        {
            return Size(_root);
        }
        private int Size(Node root)
        {
            if (root == null)
                return 0;
            return 1 + Size(root.Left) + Size(root.Right);
        }

How to create binary tree in c#

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

download

Implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BTree
{
    public class Node
    {
        public int Data { get; set; }
        public Node Left { get; set; }
        public Node Right { get; set; }
        public Node()
        {

        }
        public Node(int data)
        {
            this.Data = data;

        }
    }
    public class BinaryTree
    {
        private Node _root;
        public BinaryTree()
        {
            _root = null;
        }
        public void Insert(int data)
        {
            // 1. If the tree is empty, return a new, single node 
            if (_root == null)
            {
                _root = new Node(data);
                return;
            }
            // 2. Otherwise, recur down the tree 
            InsertRec(_root, new Node(data));
        }
        private void InsertRec(Node root, Node newNode)
        {
            if (root == null)
                root = newNode;

            if (newNode.Data < root.Data)
            {
                if (root.Left == null)
                    root.Left = newNode;
                else
                    InsertRec(root.Left, newNode);

            }
            else
            {
                if (root.Right == null)
                    root.Right = newNode;
                else
                    InsertRec(root.Right, newNode);
            }
        }
        private void DisplayTree(Node root)
        {
            if (root == null) return;

            DisplayTree(root.Left);
            System.Console.Write(root.Data + " ");
            DisplayTree(root.Right);
        }
        public void DisplayTree()
        {
            DisplayTree(_root);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            BinaryTree tree = new BinaryTree();
            Node root = new Node();

            tree.Insert(4);
            tree.Insert(2);
            tree.Insert(5);
            tree.Insert(1);
            tree.Insert(3);
            tree.DisplayTree();
        }
    }
}

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:
  1. Go to Control Panel | Programs | Turn Windows features on or off.
  2. Expand the Microsoft .Net Framework 3.5.1 node on Windows 7
  3. Check the checkbox for Windows Communication Foundation Non-HTTP Activation on Windows 7
getfile
Next,Create the IIS application to host the WCF application using TCP protocol.Follow these steps
  1. Open run command and type inetmgr
  2. Create a new application and point to physical folder.
  3. Select the DefaultAppPoll  and make sure your default app pool is a .NET 4.0.X application pool.
  4. 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)
image
Now the service is hosted in IIS using the TCP protocol.

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.”-Wikipedia

Knockout is built around three core features:

  1. Observables and dependency tracking
  2. Declarative bindings
  3. Templating

Before diving to example code first go through the following http://knockoutjs.com/documentation/observables.html#mvvm_and_view_models

Open visual studio and create a new Web API application

image

Open Package Manager console and install knockoutjs as shown in below image

image

Right 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 folder again and add a new Interface class and paste following code

 public interface ITodoRepository
    {
        IEnumerable<TodoItem> GetAll();
        void AddTodo(TodoItem item);
    }
}

Add a new class inside model folder and paste following code inside it

 public class TodRepository : ITodoRepository
    {
        private static List<TodoItem> _localTodos;
        private int MaxId()
        {
            return _localTodos.Max(x => x.Id) + 1;
        }
        public TodRepository()
        {
            _localTodos = new List<TodoItem>() {
                    new TodoItem{Id=1,Title="Todo Item 1",Done=false},
                    new TodoItem{Id=2,Title="Todo Item 2",Done=false},
                    new TodoItem{Id=3,Title="Todo Item 3",Done=true},
                };

        }


        public IEnumerable<TodoItem> GetAll()
        {
            return _localTodos;
        }

        public void AddTodo(TodoItem item)
        {
           
            var id = MaxId();
            TodoItem newTodo = new TodoItem() { Id = id, Title = item.Title, Done = item.Done };
            _localTodos.Add(newTodo);
        }

        public void Delete(int id)
        {
            var taskToDeleted = _localTodos.Find(x => x.Id == id);
            _localTodos.Remove(taskToDeleted);
        }

    }

Go to controller folder and rename the ValuesController to TodoController and paste the following code.

 public class TodoController : ApiController
    {
        // GET api/values
        private ITodoRepository _repo;
        public TodoController()
        {
            _repo = new TodRepository();
        }
        public IEnumerable<TodoItem> Get()
        {
            return _repo.GetAll();
        }

        public void Post([FromBody]TodoItem value)
        {
            _repo.AddTodo(value);
        }

    }

Till now I have not done nothing related to knockoutjs.Let’s start the second part

Opend Index.cshtml and remove everything from it and paste following markup

<h1>Todo App</h1>
<div class="row">

    <form role="form">
        <div class="form-group">
            <label for="email">Title:</label>
            <input type="text" class="form-control" data-bind="value: taskName" id=" txttitle" placeholder="Enter Title">
        </div>

        <button type="submit" data-bind="click:addTask" class="btn btn-default">Submit</button>
    </form>
    <hr />
    <div class="col-md-6">
        <table class="table">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Completed?</th>
                </tr>
            </thead>
            <tbody data-bind="foreach:todos">
                <tr>
                    <td data-bind="text:Title"></td>
                    <td><input type="checkbox" data-bind="checked:Done" /> </td>
                    <td>
                        <a href="#" title="Delete the task" data-bind="click:$parent.deleteTodo" class="glyphicon glyphicon-trash"></a>
                    </td>


                </tr>
            </tbody>
        </table>
    </div>
</div>


 

The basic layout of the html is simple, and taken from the inspiring example applications. The noteworthy parts are the data-bind attributes that are sprinkled in the appropriate places:

There is a input textbox which has the same value as the viewModels taskName and there is button which will fire addTask function on viewmodel.

Right click the project and add new javascript file inside scripts folder named todoApp.js and add following code

function TodoItem(Id, Title, Done) {
    var self = this;
    self.Id = Id;
    self.Title = ko.observable(Title);
    self.Done = ko.observable(Done);
    self.Done.subscribe(function () {


    });
}
function TodoViewModel() {

    var self = this;
    self.todos = ko.observableArray([]);
    self.taskName = ko.observable();

    self.addTask = function () {
        var todoItem = new TodoItem(0, self.taskName(), false);
        self.todos.push(todoItem);
        $.ajax({
            type: "POST",
            url: "/api/todo",
            data: ko.toJSON(todoItem),
            dataType: "json",
            contentType: "application/json",
            success: function (data) {

            }

        });

    };
    self.deleteTodo = function (data) {
        self.todos.remove(data);
        $.ajax({
            type: "DELETE",
            url: "/api/todo/" + data.Id,
            dataType: "json",
            contentType: "application/json",
            success: function () {
               
            }

        });
    };
    self.init = function () {
        $.getJSON("/api/todo", function (data) {
            $.each(data, function (index, item) {
                self.todos.push(new TodoItem(item.Id, item.Title, item.Done));
            });
        });
    };

}
$(document).ready(function () {

    var viewModel = new TodoViewModel();
    viewModel.init();
    ko.applyBindings(viewModel);
});

open _Layout.cshtml and add following script

    <script src="~/Scripts/knockout-3.2.0.js"></script>
    <script src="~/Scripts/todoApp.js"></script>

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 = RouteParameter.Optional }
            );
        }

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);
                       }
                   }   
                }
                lst.Add(cn);
            }
            return lst;
        }

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
image

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
image
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}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 

            appBuilder.UseWebApi(config); 
        } 
    } 

Next, add a Web API controller class. In Solution Explorer, right click the project and select Add / Class to add a new class named HelloController and add following code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace SelfHostWebApi
{
    public class HelloController : ApiController
    {
        // GET api/values/5 
        public string Get(int id)
        {
            return "Hello API";
        }
    }
}
Open Program.cs and add following code inside main method
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SelfHostWebApi
{
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/";

            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                // Create HttpCient and make a request to api/values 
                HttpClient client = new HttpClient();

                var response = client.GetAsync(baseAddress + "api/hello").Result;

                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }

            Console.ReadLine();
        }
    }
}

Your self hosted web api is ready.When you run the application you will see following output if everything works fine
image


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 image
Select Empty MVC application
image
Open Package Manager Console and install SignalR
image
Right click on project and add new class ChatHub and inherit from Hub class that resides in Microsoft.AspNet.SignalR
image
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 automatically by signalr framework
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="signalr/hubs"></script>
    <script>
        $(document).ready(function () {
            var chatHub = $.connection.chatHub;
            chatHub.client.newMessage = function (data) {
                $("#messages").append("<li>" + data + "</li>");
            };
            chatHub.connection.start().done(function () {
                $("#btnSend").click(function () {
                    chatHub.server.sendMessage($("#txtMessage").val());
                });

            });

        });
    </script>
</head>
<body>
    <label for="txtMessage">Message</label>
    <input type="text" name="txtMessage" id="txtMessage" />
    <input type="button" value="send" id="btnSend" />
    <hr />
    <ul id="messages"></ul>
</body>
</html>

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 Ruby

One 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 evens

Linq OrderBy expression equivalent in Ruby

To sort a sets of elements in c# with Linq we use OrderBy

var 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 ordered

Linq Select expression equivalent in Ruby

In .NET to convert a set of items to another set one would use the Select() method. This method is also useful for creating projections of a collection

 var words = new[] {
 	"Hello", "Word"
 };
 var shouting = words.Select(x = > x.ToUpper();

and the ruby equivalent is map

words = % w {
	Hello World
}
shouting = words.map { | x | x.upcase
}
puts shouting

How to post data using HttpClient

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

  private static 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>
        private static async Task Post()
        {
            HttpClient client = new HttpClient();

            var values = new Dictionary<string, string>();
            values.Add("author", "santosh");
            values.Add("text", "singh");
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("http://localhost:4500/quote", content);
        }