I was looking for a simple yet complete example of a working widget with widget factory from a scratch. Having trouble finding one, I came up with this blog post. Here I would explain how to create a custom widget from scratch. Widgets or Plugins are simple generic control or a unit of process that can be attached to any DOM element to give it a specialized behavior with methods and properties. The jQuery UI Widget Factory is the base class which is extended by all widgets.

Dependencies

To build a simple jQuery widget you need jQuery core library and jQuery UI library. JQuery UI is what contains the definition and base classes for widget factory. You may customize it to download the bare minimum to make your widget work. These can be downloaded from jQuery website or referenced as a link to CDN (Content Delivery Network).
JQuery core library can be downloaded from here
JQuery UI can be downloaded from here
Microsoft Ajax CDN contains the links for most jQuery core and jQuery UI that can be referenced. Visit http://www.asp.net/ajax/cdn for more details.

Project Structure

As a good practice for JavaScript coding, there are few things you should follow:
  • Keep jQuery core library files and your custom code files in separate folders
  • Use small case or camel case naming rules
  • Use uncompressed for development/debugging and compressed for production
  • Use namespace that uniquely separates your widget from other jQuery UI widgets
Here is a picture for project structure, I have created:

Widget Code Structure

There are plenty of materials out on the web explaining how to write a widget using widget factory. To kick start here are few good ones:You might come across multiple ways of doing same thing. This is because JavaScript itself is quite versatile and does not impose restrictions like most compiled languages do. However, as we move forward, I will explain the important methods that would get you going and start writing some interesting widgets. Following image explains the structure of a simple widget that uses widget factory.

Note the followings:
  • (function ($) { ... }(jQuery)); - This implies anonymous function to which jQuery is passed as an argument.
  • $.widget - This is where it calls and extends the base class of jQuery UI widget factory.
  • my.roundButton - This is the fully qualified namespace and class name of my widget.
  • Method prefixed with underscore are meant to be private. This is just a convention, since, there is no scope identifier in JavaScript.
  • options: This defines all the widget properties with default values.
  • _create: This is like a constructor. Fired only once by the widget factory during initialization.
  • _init (not in my code): This is also like a constructor. Fired every time by the widget factory each time widget is called without arguments. Mainly, used for default functionality implementation.
  • _setOption: Called to change a single property value of the widget defined in options. Example - $('#elem').roundButton('option', 'size', 100)
  • _setOptions: Called to change a multiple property value of the widget defined in options.
  • _destroy: This is like a Destructor. Cleanup code goes here.

Instantiation

Let us look at the html page that uses this widget. Things to note here is what scripts are referenced and how a widget is initialized with multiple arguments.

Note how multiple properties are set during the instantiation of the widget. Also note how a widget method is called with parameters. We will discuss about the function attached to "OnPressed" property in the next section.

Custom Events

If you have authored any control in any language, you must have come across the need of raising or chaining events to allow user implement custom code during state changes of the control. For example a user wants to execute some custom action when the widget is clicked. It might be a timeout, ajax call or an alert. You, as an author need to raise an event when the widget is clicked and let the user handle the custom action.

This can be done using the "_trigger" function of jQuery core. Signature of this function is : _trigger("callbackFunction", [eventObject], [arguments]). One must also check if the user has provided custom action code. In other words if the callbackFunction is not null then call it using "_trigger" function. For this, we will create a property in options section called "onPressed". During the click event if the "onPressed" is not null, the widget will call the "_trigger" function.

if (this.options.onPressed != null)
    this._trigger("onPressed", this.control);

Complete Code of "roundButton" Widget

(function ($) { $.widget("my.roundButton", { //control properties options: { radius: '5px', text: "Click Me!", backColor: "#bbbbbb", onPressed: null }, //ctor (called only once) _create: function () { //remove and redraw the control this.element.empty(); //save the reference in this.control this.control = $("<div>") .html(this.options.text) .css("border", "2px solid #a1a1a1") .css("padding", "10px 40px;") .css("background", this.options.backColor) .css("width", "300px;") .css("border-radius", this.options.radius) .appendTo(this.element); //create element this._refresh(); //bind events this._bindEvents(); }, _refresh: function () { this.control .css("background", this.options.backColor) .html(this.options.text); }, //single property setter _setOption: function (key, value) { //update widget factory this._super(key, value); }, //multiple property setter _setOptions: function (options) { //update widget factory this._super(options); this._refresh(); }, //bind internal click event that triggers onPressed event _bindEvents: function () { //remove event binding //Notice the use of this.control this._off(this.control, "click"); //rebind this._on(this.control, { "click": function () { //change property this.options.backColor = "#e7e7e7"; this.options.text = "Clicked"; //refresh this._refresh(); //We will learn how to trigger a custom event in jQuery Widget // Signature of _trigger //this._trigger("callbackFunction", [eventObject], [arguments]) if (this.options.onPressed != null) this._trigger("onPressed", this.control); //change property this.options.backColor = "#bbbbbb"; this.options.text = "Click Me!"; //refresh this._refresh(); } }); }, //public method changeText: function(txt){ this.options.text = txt; //refresh this._refresh(); }, //cleanup _destroy: function () { this.element.empty(); } }); }(jQuery));


Hope it helped ... Enjoy !!

 
  Posted in:  jQuery



Heap sort is a common sorting algorithm, but useful in case of hierarchical or tree kind of data structures.
public class HeapSort { private readonly List<int> _heapList; private readonly int _heapsize; public HeapSort(List<int> heapList, int heapsize) { this._heapsize = heapsize; this._heapList = heapList; } private void Heapify(int i, int n) { var iPosition = _heapList[i]; var iChange = 2 * i; while (iChange <= n) { if (iChange < n && _heapList[iChange] < _heapList[iChange + 1]) { iChange++; } if (iPosition >= _heapList[iChange]) { break; } _heapList[iChange / 2] = _heapList[iChange]; iChange *= 2; } _heapList[iChange / 2] = iPosition; } public void Sort() { for (var i = _heapsize / 2; i >= 0; i--) { Heapify(i, _heapsize - 1); } for (var i = _heapsize - 2; i >= 0; i--) { var iValue = _heapList[i + 1]; _heapList[i + 1] = _heapList[0]; _heapList[0] = iValue; Heapify(0, i); } } public string PrintList() { var myValue = ""; for (int i = 0; i < _heapsize; i++) { myValue += _heapList[i] + " "; } return myValue; } }

 
  Posted in:  Algorithm



Find Nth Max or Min Record

This query gets the Nth highest salary from the emp table. You can replace the Max function with Min to obtain Nth lowest salary.

SELECT Eno, Ename, Desig, Sal, Mgr, DNO FROM dbo.Emp AS E1 WHERE(N-1 = (SELECT COUNT(DISTINCT Sal) AS DistinctSal FROM dbo.Emp AS E2 WHERE(Sal>E1.Sal)))

Row Number

This query generates the row number for the records fetched.

SELECT(SELECT COUNT(*) AS Counter FROM dbo.Emp AS e2 WHERE(e2.Eno <= e.Eno)) AS RowNumber, Ename, Desig, Sal FROM dbo.Emp AS e ORDER BY RowNumber

Running Total

This query computes the running total on salary for the records in Emp table.

SELECT a.Ename, SUM(b.Sal) AS RunningTotal FROM dbo.Emp AS a INNERJOIN dbo.Emp AS b ON a.Ename >= b.Ename GROUP BY a.Ename

Find Duplicates

This query finds the duplicate records in Emp table.

SELECT Ename, Desig, Sal, COUNT(*) AS Duplicate FROM dbo.Emp GROUP BY Ename, Desig, Sal HAVING(COUNT(*)>1) ORDER BY Duplicate DESC, Ename

Let SQL Generate SQL

This query emits SQL queries as records fetched.

SELECT 'SELECT DName FROM Dept WHERE Dno=' + CAST(DNO as varchar) FROM Emp

 
  Posted in:  SQL



WCF Kick Start

In this article I would be describing the simplest form of WCF (Windows Communication Foundation) project which would get you started with the WCF concepts and best practices. The purpose is to minimise the confusion from code and configuration and explain the idea along with the best practice. I would also provide description and links to help you move to a more advanced WCF topics as and when required.

For the sake of kick start I would be using basicHttpBinding for the service and consumer, which does not require any kind of authentication when accessing the service. It is kind of open to all.

Below is an overall image of the solution, projects and project files that I have used to demonstrate the simplest form of WCF implementation.

solution

The solution contains a project WcfServiceOne which defines types for contracts exposed by the service. The person class is the data contract, MyService is the service and IMyService is an interface acting as a service contract. This project acts as an API for the services.

The ServiceOneHost is the service exposed to the client. It references the project WcfServiceOne which the actual implementation of the Service as an API. Though, I could have had the service implementation written in the same project, I preferred following the best practices, by implementing the Service and Service API (contracts and its implementation) in a separate project. One advantage of doing this is that, you have decoupled service and Service API, which simplifies using the API in a non-WCF environment by directly referencing it. The web.config file in this project contains the binding information for the service which I will be explaining later in this article.

The ServiceOneConsumer is a simple ASP.Net web application consuming the service exposed by ServiceOneHost. The web.config in this web application contains the binding information defined by the host.

WcfServiceOne

WcfServiceOne project contains:

  • Data Contract - Person.cs
  • Service Contract - IMyService.cs
  • Service Implementation - IMyService.cs
Also notice that the project references System.ServiceModel and System.Runtime.Serialization which are required to assign attributes like ServiceContract, OperationContract, DataContract and DataMember.

Person.cs

using System.Runtime.Serialization;

 

namespace WcfServiceOne

{

    [DataContract]

    publicclassPerson

    {

        [DataMember]

        publicstring FullName { get; set; }

 

        [DataMember]

        publicstring Gender { get; set; }

    }

}

IMyService.cs

using System.ServiceModel;

 

namespace WcfServiceOne

{

    [ServiceContract]

    publicinterfaceIMyService

    {

        [OperationContract]

        string Callme(Person p);

    }

}

MyService

namespace WcfServiceOne

{

    publicclassMyService : IMyService

    {

        publicstring Callme(Person p)

        {

            return"Hello " + p.FullName + "  " + " you are a " + p.Gender;

        }

    }

}

ServiceOneHost

Add a reference to WcfServiceOne and then right click on the project. Select "Add New Item" from the context menu and select "WCF Service" templates. Name the new file ServiceOneHost.svc. The template would also create the code files for you in the App_Code folder. You can delete it, the code file is not required. Open the ServiceOneHost.svc and change the line to:

<% @ ServiceHost Language ="C#" Debug ="true" Service ="WcfServiceOne.MyService" %>

 

Now open the web.config file in this project and add the following block at the last within the closing of configuration tag.

  < system.serviceModel >

    < behaviors >

      < serviceBehaviors >

        < behavior name ="ServiceOneHostBehavior">

          < serviceMetadata httpGetEnabled ="true"/>

          < serviceDebug includeExceptionDetailInFaults ="false"/>

        </ behavior >

      </ serviceBehaviors >

    </ behaviors >

    < services >

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

          < identity >

            < dns value ="localhost"/>

          </ identity >

        </ endpoint >

        < endpoint address ="mex"binding="mexHttpBinding"contract="IMetadataExchange"/>

      </ service >

    </ services >

  </ system.serviceModel >

system.servicemodeltag defines how the consumer is going to connect to the service exposed here. When you add a "WCF service" to the project using template, it responds with adding the above system.servicemodel in the web.config, except the following two lines.

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

Change the name, contract and binding information as shown above. The wsHttpBinding is used to provide more secured communication using certificate. Visit The pattern and practices for WCF security at Codeplex for further guidance on how to implement wsHttpBinding using certificates.

ServiceOneConsumer

Before you proceed with consumer, you need to generate a proxy for the service and define how it connects, in the web.config file. To generate the proxy and the configuration block we would use svcutil. Open the Visual studio command prompt from Visual Studio Tools and use the following command to generate the proxy and configuration.

svcutil http://localhost/ServiceOneHost/ServiceOneHost.svc /Language:C# /out:ServiceHostProxy.cs /config:ServiceHost.config

This will create a ServiceHostProxy.cs and ServiceHost.config. Open the ServiceHost.config and copy the block. Now open the web.config file and paste the block at the end before the closing tag of configuration. The endpoint address might differ depending your host and consumer address URL.

    < system.serviceModel >

        < bindings >

            < basicHttpBinding >

                < binding name ="BasicHttpBinding_IMyService"closeTimeout="00:01:00"

                        openTimeout ="00:01:00"receiveTimeout="00:10:00"

                        sendTimeout ="00:01:00"allowCookies="false"

                        bypassProxyOnLocal ="false"

                        hostNameComparisonMode ="StrongWildcard"

                        maxBufferSize ="65536"maxBufferPoolSize="524288"

                        maxReceivedMessageSize ="65536"

                        messageEncoding ="Text"textEncoding="utf-8"

                        transferMode ="Buffered"

                        useDefaultWebProxy ="true">

                    < readerQuotas maxDepth ="32"maxStringContentLength="8192"

                                 maxArrayLength ="16384"

                                 maxBytesPerRead ="4096"

                                 maxNameTableCharCount ="16384"/>

                    < security mode ="None">

                        < transport clientCredentialType ="None"proxyCredentialType="None"

                           realm =""/>

                        < message clientCredentialType ="UserName"algorithmSuite="Default"/>

                    </ security >

                </ binding >

            </ basicHttpBinding >

        </ bindings >

        < client >

            < endpoint address ="http://localhost/ServiceOneHost/ServiceOneHost.svc"

               binding ="basicHttpBinding"bindingConfiguration="BasicHttpBinding_IMyService"

               contract ="IMyService"name="BasicHttpBinding_IMyService"/>

        </ client >

    </ system.serviceModel >

Default.aspx

Now add the following UI in the home page of your consumer site. In this case it is Default.aspx.

< table style =" width: 400px;"cellspacing="0"cellpadding="0">

    <tr>

        <tdstyle="width:100px; vertical-align:top; text-align:left;">

            Your Name

        </td>

        <tdstyle="width:10px; vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="width:290px; vertical-align:top; text-align:left;">

            <asp:TextBoxID="txtName"runat="server"Width="200"></asp:TextBox>

        </td>

    </tr>

    <tr>

        <tdstyle="vertical-align:top; text-align:left;">

            Gender

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            <asp:DropDownListID="ddlGender"runat="server">

                <asp:ListItemSelected="True"Text="Male"Value="male"/>

                <asp:ListItemText="Female"Value="female"/>

            </asp:DropDownList>

            <asp:ButtonID="btnSubmit"runat="server"Text="Submit"

                onclick="btnSubmit_Click"/>

        </td>

    </tr>

    <tr>

        <tdcolspan="3">

            <br/>

            <asp:LabelID="lblResult"runat="server"Text=""Font-Bold="true"
                    Font-Size="Large"></asp:Label>

        </td>

    </tr>

</ table >

Default.aspx.cs - Code Behind

using System;

using WcfServiceOne;

 

public partial class _Default : System.Web.UI.Page

{

    protectedvoid Page_Load(object sender, EventArgs e)

    {

        txtName.Text = "Manish Kumar Singh";

    }

    protectedvoid btnSubmit_Click(object sender, EventArgs e)

    {

        var p = newPerson {FullName = txtName.Text, Gender = ddlGender.SelectedValue};

 

        var proxy = newMyServiceClient();

        lblResult.Text = proxy.Callme(p);

    }

}

That's it. Now run the consumer site and give it a try.

Enjoy!
Manish


 
  Posted in:  .Net



In this section I would like to demonstrate how to compile a .NET code on the fly. The code has been written in C#. It contains a class "InlineParser" which does the main job. It mainly, defines the class, does in-memory compilation and exposes a method for the execution of an inner method defined in the class. It also supports a choice of language whether C# or VB.NET for compilation.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CSharp; using Microsoft.VisualBasic; using System.CodeDom.Compiler; using System.Reflection; using System.Xml.Linq; namespace com.eforceglobal.crux.bre { internal class InlineParser { string expression = string.Empty; string functionArguments = string.Empty; string language = "CSharp"; XDocument paramList = null; object objBase = null; public InlineParser(string expr, string functionArgs, XDocument parameters, string lang) { expression = expr; functionArguments = functionArgs; paramList = parameters; language = lang; } public bool init() { if (language.ToLower().Equals("csharp")) return InitCSharp(); else return InitVB(); } internal bool InitCSharp() { // Compile the expression in a class on the fly CSharpCodeProvider cp = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); //ICodeCompiler ic = cp.CreateCompiler(); CompilerParameters cparam = new CompilerParameters(); cparam.GenerateInMemory = true; cparam.GenerateExecutable = false; // Reference Assembly cparam.ReferencedAssemblies.Add("system.dll"); cparam.ReferencedAssemblies.Add("mscorlib.dll"); cparam.ReferencedAssemblies.Add("System.Core.dll"); cparam.ReferencedAssemblies.Add("System.Xml.dll"); cparam.ReferencedAssemblies.Add("System.Xml.Linq.dll"); // Write your code StringBuilder sb = new StringBuilder(); sb.Append("using System;\n"); sb.Append("using System.Collections;\n"); sb.Append("using System.Collections.Generic;\n"); sb.Append("using System.Text;\n"); sb.Append("using System.Text.RegularExpressions;\n"); sb.Append("using System.Reflection;\n"); sb.Append("using System.Linq;\n"); sb.Append("using System.Xml.Linq;\n"); sb.Append("namespace com.eforceglobal.crux.bre {\n"); sb.Append("public class EvalClass {\n"); sb.Append("public EvalClass(){}\n"); sb.Append("public object Evaluate(\n"); sb.Append(functionArguments).Append(" ) {\n"); sb.Append(expression).Append("\n"); sb.Append("}\n}\n}"); string code = sb.ToString(); CompilerResults cres = cp.CompileAssemblyFromSource(cparam, code); // Compilation Unsuccessfull StringBuilder errors = new StringBuilder(); foreach (CompilerError cerr in cres.Errors) errors.Append(cerr.ErrorText); if (cres.Errors.Count > 0) throw new Exception(errors.ToString()); // Compilation Successfull if (cres.Errors.Count == 0 && cres.CompiledAssembly != null) { Type ClsObj = cres.CompiledAssembly.GetType("com.eforceglobal.crux.bre.EvalClass"); try { if (ClsObj != null) { objBase = Activator.CreateInstance(ClsObj); } } catch (Exception ex) { throw; } return true; } else return false; } internal bool InitVB() { // Compile the expression in a class on the fly VBCodeProvider vb = new VBCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); //ICodeCompiler ic = cp.CreateCompiler(); CompilerParameters cparam = new CompilerParameters(); cparam.GenerateInMemory = true; cparam.GenerateExecutable = false; // Reference Assembly cparam.ReferencedAssemblies.Add("system.dll"); cparam.ReferencedAssemblies.Add("mscorlib.dll"); cparam.ReferencedAssemblies.Add("System.Core.dll"); cparam.ReferencedAssemblies.Add("System.Xml.dll"); cparam.ReferencedAssemblies.Add("System.Xml.Linq.dll"); // Write your code StringBuilder sb = new StringBuilder(); sb.Append("Imports System\n"); sb.Append("Imports System.Collections\n"); sb.Append("Imports System.Collections.Generic\n"); sb.Append("Imports System.Text\n"); sb.Append("Imports System.Text.RegularExpressions\n"); sb.Append("Imports System.Reflection\n"); sb.Append("Imports System.Linq\n"); sb.Append("Imports System.Xml.Linq\n"); sb.Append("Namespace com.eforceglobal.crux.bre \n"); sb.Append("Public Class EvalClass \n"); sb.Append("Public Function Evaluate ( "); sb.Append(functionArguments).Append(" ) As Object\n"); sb.Append(expression).Append("\n"); sb.Append("End Function\n"); sb.Append("End Class\n"); sb.Append("End Namespace"); string code = sb.ToString(); CompilerResults cres = vb.CompileAssemblyFromSource(cparam, code); // Compilation Unsuccessfull StringBuilder errors = new StringBuilder(); foreach (CompilerError cerr in cres.Errors) errors.Append(cerr.ErrorText); if (cres.Errors.Count > 0) throw new Exception(errors.ToString()); // Compilation Successfull if (cres.Errors.Count == 0 && cres.CompiledAssembly != null) { Type ClsObj = cres.CompiledAssembly.GetType("com.eforceglobal.crux.bre.EvalClass"); try { if (ClsObj != null) { objBase = Activator.CreateInstance(ClsObj); } } catch (Exception ex) { throw; } return true; } else return false; } public string Evaluate() { string result = string.Empty; Type type = objBase.GetType(); MethodInfo mInfo = type.GetMethod("Evaluate"); if (mInfo != null) { ParameterInfo[] pInfo = mInfo.GetParameters(); object[] arguments = null; if (pInfo != null) arguments = new object[pInfo.Length]; if (pInfo != null) { foreach (ParameterInfo p in pInfo) if (paramList.Element("arguments").Elements(p.Name) != null) { arguments[p.Position] = (paramList.Element("arguments") .Elements(p.Name).Single().Value); } if (pInfo.Length != arguments.Length) throw new ArgumentException("Insufficient parameters."); } result = mInfo.Invoke(objBase, arguments).ToString(); } return result; } } }
Notice that the class name of the class to be compiled is "EvalClass" and the inner method of the class is "Evaluate". Calling the "Evaluate()" method requires you to execute the following lines of code.
var parser = new InlineParser(subExpression, funcArgs, Arguments.Document, lang); parser.init(); retString = parser.Evaluate();
Enjoy!!
Manish

 
  Posted in:  .Net