Friday, November 1, 2013

Real Time Web using SignalR


Hi Guys,

This time I made a shopping site which works real time. Yes, you heard it right. It is real time.

If two users ave connected and one buys something, the other person gets the update without him making any interaction to the Server. Surely the potential of this real time web is limitless.

Before you Start,

1) Visual Studio with .NET Framework 4 or higher

Step One : The Solution
Create a Web application project.

Then Right Click on Solution -> Manage NuGet Packages For Solution













Then Search for SignalR, Json2 and jquery as shown and then install them.









Then make Solution as shown













Then Open UpdateStock.js paste the following code.


/// <reference path="../Scripts/jquery-1.6.4.min.js" />
/// <reference path="../Scripts/jquery.signalR-2.0.0.js" />
/// <reference path="../Scripts/jquery-ui-1.10.3.js" />

$(function () {

//Instance of the Hub
var hub = $.connection.updateStockHub;

//Event handler and logic for update stock
hub.client.updateStock = function (cid, pid, chkAmnt) {

$('#stockTable tr input[type=hidden]').each(function () {
if ($(this).val() == pid) {

var stock = $(this).closest("tr").find('#stock');
var stockVal = stock.html();
if (parseInt(stockVal) > 0) {
stock.html((parseInt(stockVal) - chkAmnt));
}

}

});


if ($.connection.hub.id == cid) {
$('#msg').html('<strong> You have Bought it Successfully!</strong>');
}

};



//Event Habndler binding for Buy Now button
$.connection.hub.start().done(function () {
$('#stockTable tr input[type=button]').each(function () {
$(this).click(function() {
var pid = $(this).closest("td").find('input[type=hidden]').val();
hub.server.update($.connection.hub.id, parseInt(pid), 1)});
});
});
});


Then Open UpdateStockHub.cs and paste the following code.




using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalR.UpdateStock
{
[HubName("updateStockHub")]
public class UpdateStockHub : Hub
{

public void Update(string connectionId, int productId, int checkedOutAmount)
{
Clients.All.updateStock(connectionId, productId, checkedOutAmount);
}

}

}



Then Open the index.html and paste the following code.


<head>
<title>Real Time Shopping Site</title>
<script src="../Scripts/json2.js"></script>
<script src="../Scripts/jquery-1.6.4.min.js"></script>
<script src="../Scripts/jquery-ui-1.10.3.js"></script>
<script src="../Scripts/jquery.signalR-2.0.0.js"></script>
<script src='/signalr/hubs'></script>
<script src="UpdateStock.js"></script>
<style>


.highlight {
background-color:PaleGreen;
}

#stockTable {
border:solid;
width:100%;
font-family:Verdana;
font-size:small;
}

#stock {
font-weight:bold;
}


#imgtd {
border:solid 1px 1px 1px 1px;
padding:5px;
border-color:black;
}


#pName {
font-size:larger;
}

</style>
</head>
<body>


<table id="stockTable">
<tr width="50%">
<td colspan="3">
<table>
<tr><td id="imgtd">
<img width="100px" height="100px" src="../Images/shampoo.jpg" /></td></tr>
<tr><td id="pName">Shampoo</td></tr>
<tr><td>$ 2.00</td></tr>
</table>

</td>
<td width="25%" id="stock">10</td>
<td width="25%"><input type="hidden" id="hf1" value="1" />
<input type="button" id="updStock1" value="Buy Now" /></td>
</tr>
<tr>
<td colspan="3">
<table>
<tr><td id="imgtd">
<img width="100px" height="100px" src="../Images/towel.jpg" /></td></tr>
<tr><td id="pName">Towel</td></tr>
<tr><td>$ 2.00</td></tr>
</table>

</td>

<td id="stock">12</td>
<td><input type="hidden" id="hf2" value="2" />
<input type="button" id="updStock2" value="Buy Now" /></td>
</tr>

</table>
<br />
<div id="msg">

</div>

</body>
</html>


Then build and Run the solution. And don't forget to set index.html as your starting page.
And open another connection from another browser.











Then Click on buy now on any of the product in any browser and notice that the other browsers same products count gets reduced automatically.


Wednesday, October 23, 2013

Stack Implementation using Managed Extensibility Framework

Hi Guys,

This time I made a small application to simulate a basic stack data structure. But to make things interesting I used Managed Extensibility Framework.

Before you Start,

1) Visual Studio with .NET Framework 4 or higher (Any Version)

Step One : The Solution

Create a console application project and a class library as shown in the image. Refer both the projects with System.ComponentModel.Composition. And add a reference to Console Application from the class library.

















Step Two : The Code

Paste the following code in the Program.cs file of MEFClient Project. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace MEFClient
{
    //Stack Implementation 
    [Export(typeof(IStack))]
    class MySimpleStack : IStack
    {
        [ImportMany]
        IEnumerable<Lazy<IOperation, IOperationData>> operations;
        int[] arr = { -1, -1, -1, -1, -1 };

        public String Process(String input)
        {
            string command;
            int val;


            int fn = FindSeperator(input); //finds the operator
            if (fn < 0) return "Could not parse command.";

            try
            {
                //separate out the operands
                command = input.Substring(0, fn);
                val = int.Parse(input.Substring(fn + 1));
            }
            catch
            {
                return "Could not parse command.";
            }



            foreach (Lazy<IOperation, IOperationData> i in operations)
            {
                if (i.Metadata.Command.Equals(command)) return i.Value.Manipulate(arr, val).ToString();
            }
            return "Operation Not Found!";
        }

        private int FindSeperator(String s)
        {

            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == ':') return i;
            }
            return -1;
        }


    }


    class Program
    {

        private CompositionContainer _container;

        [Import(typeof(IStack))]
        public IStack stack;


        private Program()
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
            //Location of the directory of extensions
            catalog.Catalogs.Add(new DirectoryCatalog(@"C:\Users\Shahim\Documents\visual studio 2012\Projects\TestApplication\Extensions\bin\Debug"));


            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                this._container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }

        static void Main(string[] args)
        {
            Program p = new Program(); //Composition is performed in the constructor
            String s;
            Console.WriteLine("Enter Command:");
            while (true)
            {
                s = Console.ReadLine();
                Console.WriteLine(p.stack.Process(s));
            }

        }
    }

    //Interface for the stack
    public interface IStack
    {
        String Process(String input);
    }

    //Interface for the operation 
    public interface IOperation
    {
        String Manipulate(int[] arr, int val);
    }

    // //Interface for the operation data 
    public interface IOperationData
    {
        String Command { get; }
    }

    //Push Implemenation
    [Export(typeof(IOperation))]
    [ExportMetadata("Command", "PUSH")]
    class Push : IOperation
    {
        public String Manipulate(int[] arr, int val)
        {
            bool pushed = false;

            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == -1)
                {
                    arr[i] = val;
                    pushed = true;
                    break;
                }
            }

            return pushed ? "Value Pushed!" : "Value Was Not Pushed!";
        }
    }

}

Paste the following code in the ExtensionClass.cs file of Extensions Project. 

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

namespace Extensions
{
    //Pop Implementation
    [Export(typeof(MEFClient.IOperation))]
    [ExportMetadata("Command", "POP")]
    class Pop : MEFClient.IOperation
    {
        public String Manipulate(int[] arr, int val)
        {
            bool poped = false;
            int valuePoped = -1;

            for (int i = arr.Length - 1; i >= 0; i--)
            {
                if (arr[i] != -1)
                {
                    valuePoped = arr[i];
                    arr[i] = -1;
                    poped = true;

                    break;
                }
            }

            return valuePoped.ToString() + (poped ? " Value Poped!" : " Value Was Not Poped!");
        }
    }

    //Show Implementation
    [Export(typeof(MEFClient.IOperation))]
    [ExportMetadata("Command", "SHOW")]
    class Show : MEFClient.IOperation
    {
        public String Manipulate(int[] arr, int val)
        {
            string arrStr = string.Empty;

            for (int i = arr.Length - 1; i >= 0; i--)
            {
                arrStr += arr[i].ToString() + ",";
            }

            return arrStr.Substring(0, arrStr.Length - 1);
        }
    }

}

Step Three : Running the Program 


Tuesday, April 16, 2013

Notifications : Service Broker, SqlDependency and NotifyIcon

Hi Guys,

This time I made a small application to show notifications using Service Broker (Query Notifications), SqlDependency and NotifyIcon.

Before you Start,

1) Sql Server (Any Version)
2) Visual Studio (Any Version)

Step One : Enable Service Broker for the Database you work on.




Step Two : Add the Following Code in a Console/Windows Application
 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            //Start the Dependency
            SqlDependency.Start(ConfigurationManager.AppSettings["Main.ConnectionString"]);
            //Create the Sql Connection
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Main.ConnectionString"]);
            using (con)
            {
                //Check whether Notifications can be requested
                if (CanRequestNotifications())
                {
                    //Open the Connection
                    con.Open();
                    //Create SqlCommand and add parameters
                    SqlCommand cmd = new SqlCommand("SELECT [Message] FROM Message WHERE UserId = @UserId", con);
                    cmd.Parameters.AddWithValue("@UserId", 2303);
                    //Clear notifications
                    cmd.Notification = null;
                    //Create SqlDependency Passing SqlCommand
                    SqlDependency dependency = new SqlDependency(cmd, null, 5);
                    //Add Event Handler to OnChange
                    dependency.OnChange += dependency_OnChange;
                    //Execute the SqlCommand to Bond the Dependency
                    cmd.ExecuteReader();
                }
            }
            //Stop the Dependency
            SqlDependency.Stop(ConfigurationManager.AppSettings["Main.ConnectionString"]);
            Console.Read();
           
          
        }
        static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            //Make the instance of NotifyIcon
            NotifyIcon notifyIcon = new NotifyIcon();
            notifyIcon.Icon = SystemIcons.Information;
            notifyIcon.Visible = true;
            notifyIcon.ShowBalloonTip(5000, "New Message", "You have Received a New Message", ToolTipIcon.Info);
        }
        //Method to check whether Notifications can be requested
        public static bool CanRequestNotifications()
        {
            SqlClientPermission permission =
                new SqlClientPermission(
                PermissionState.Unrestricted);
            try
            {
                permission.Demand();
                return true;
            }
            catch (System.Exception)
            {
                return false;
            }
        }
   
 
      
    }
}

Step Three: Run the Program and Make Some changes to the Dependent Data




 

Monday, March 25, 2013

HTML 5, Bing Map Control to Show your Current Location

Hi Guys,

My this post simply shows you how to use the HTML 5 navigator object and Bing Map Control to show your current location.

Before you Start,

1) You need to have an HTML 5 Compatible browser. Duh, almost all the new browsers supports it.
2) A text Editor (Notepad, Wordpad would do)
3) A Bing API Key (You can get one from www.bingmapsportal.com by registering)

Step One : Open the Text Editor and Paste Following HTML and Save it as HTML.

<!DOCTYPE HTML>
 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript">
      var map = null,lat,lng;

function errorHandler()
{
}            

      function getMap()
      {
                 if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                        lat = position.coords.latitude; lng = position.coords.longitude;

                    }, errorHandler);
                    }

        map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: YOUR_KEY_HERE'});

      }
     
function setView()
{
map.setView({zoom: 12, center: new Microsoft.Maps.Location(lat, lng)});

}
     function pushPin()
{
var pushpin= new Microsoft.Maps.Pushpin(map.getCenter(), null);
        map.entities.push(pushpin);

        map.entities.push(pushpin);
        pushpin.setLocation(new Microsoft.Maps.Location(lat, lng));
        map.setView({center: new Microsoft.Maps.Location(lat, lng)});

}
 
      </script>

</head>
 <body onload="getMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
     
<div>
         <input type="button" value="SetView" onclick="setView();" />
      </div>
<div>
         <input type="button" value="PushPin" onclick="pushPin();" />
      </div>

 </body>
 </html>

Step Two : Double click, run and Allow the browser to get Your Current location.

 
 
Step 3 : Click SetView Button Then the Push Pin to insert a Pin to your Current Location.
 
 
 


 

Tuesday, February 19, 2013

Asynchronous Programming : Sending Mails using async and await in .NET 4.5

Hi Folks, This is Time I am going to tell you how to send mails asynchronously using async and await keywords . Enjoy.

Before You Start you must have,
- Visual Studio 12 installed

Step 1: Create a Console Project in Visual Studio


 
 
Step 2: Make Mail Manager Class to Send Asynchronous mails




Step 3: Call it using the Console application