MVC Tooltip Validation using jQuery and Bootstrap

Check the Sample Code Github

Me and Ahmad Aqrabawi created a simple jQuery plugin to convert MVC Validation to a Boostrap tooltip validation error.

When you create a form; Validation Errors could change in the layout when its appear and may messed up the your layout .. So its error tooltips could be useful sometimes.
Simply, create new MVC project and navigate to “Register View” .. Add a validation message from Html helper directly after the text box

@Html.TextBoxFor(m => m.UserName, new { @class = “form-control” })

@Html.ValidationMessageFor(m => m.UserName)

Same thing for the other fields.

@section Scripts {



$(function () {

$(“form input”).tooltipValidation();




Also you can add placement option (by default its top)

$(“form input”).tooltipValidation({

placement: “right”


One more thing … your tooltips will appear in black colour now. If you to make it in red add this file

<link href=”~/Content/jquery.validate.mvc.css” rel=”stylesheet” />


Check the Sample Code Github

JayData Makes Web Phenomenal !


Creating Single Page Application, Web API, Upshot, An Exposed Service bring your data from Json Endpoints (maybe WEB API) … all of this is the new nueva moda.

This is nice till now. But the catastrophy started when you want to map your JSON with your EF Objects. Serializing stuff! Not Serializble! What the Hell! so change return type to ‘dynamic’ and bring ‘anonymous object’ … upshot is not documented!! And the Single Page Architecture Template (which is provided by Microsoft) .. Not mature enough! So simply they removed it from VS 12.

And Finally God guide me to JayData! Its amazing and phenomenal.

That’s what happened to me when I saw the first video for JayData

Imagine, Silverlight RIA can be used in Web. This “Framework” .. not just library

Solve this things in Previous Microsoft Single Page Architecture:

  • Generating the whole EF Model + Metadata automatically using JaySvcUtil.exe (You can see this in video)
  • Do not bother your self by creating many Web API controllers and doing all that mapping stuff between C# and JavaScript.
  • Getting optimized Data (Just needed data):

7-31-2012 6-02-35 AM

In this image you can see how I’m getting the Whole users from the WCF Data Service.

map ==> Used to get a specific properties from the object (That’s will minimize the size of the requested data; which means some KBs instead getting the whooole object).

Also I’m using Knockout to bind UI Elements with self.users observable array

7-31-2012 6-08-34 AM

  • You can use LINQ in JavaScript. Haha, Brilliant! For example if you have a users table and People table. And Each User is a Person. Lets see how to get Person Data if you clicked on a User.

7-31-2012 5-52-38 AM

First Param is a predicate that brings a person by Id.

this.Id ==> Passed in Second param as you see.

And Third one; is the callbacks from the operation. Awesome!

showPerson binded with list of users using Knockout JS (2nd image shows how I binded Div Element with showPerson function).

What else, See this video

Silverlight Tags Control Using RichTextBox, Popup and ListBox.


Download Sample



Before couple of days I created a an editable tagging control with autocomplete list.
I decided to create one “some how” Smile similar to Live mail application “To” field.


That’s exactly what I need; RichTextBox, Popup Control, and a ListBox inside that popup, and SL Cinch MVVM Framework.

And one more thing InlineUIContainer that contains my Tag Item control.

InlineUIContainer object used to wrap FrameworkElement controls inside RichTextBox; so the only way to add (border, StackPanel, or even buttons) is by using this object.


Buttons will be disabled if RichTextBox ReadOnly property equal false.
So if you want to add delete button to your Tag Item; I think that you should to make your RichTextBox works in modes (Editable, ReadOnly).
Editable: to add inline tag items.
RedOnly: to click on delete buttons for each tag Item.

I did not like this kind of user experience. So I just delete delete button from tag item. Make things simpler that better Smile. You can just delete it using backspace or by highlighting some item then delete “As you saw in Video”.


When you download the sample, you will find a Silverlight library project called bunjeeb.SL.Controls

Three DLLs added to this project:

  • Microsoft.Expression.Interactions
  • System.Windows.Interactivity
  • Cinch.SL

You can find these three DLLs in dependencies folder with the sample.

As you see below TagTextBox is very simple:

<Grid x:Name="LayoutRoot">

<Popup x:Name="PopupTags" IsOpen="False">
<ListBox x:Name="PopupTagsList" Height="Auto" 
    MinWidth="200" MaxHeight="250"

<RichTextBox x:Name="rtb"
   Background="{x:Null}" BorderThickness="1,1,0,0">
     <i:EventTrigger EventName="KeyUp">
         Command="{Binding RichTextBoxKeyUp, 
     <i:EventTrigger EventName="KeyDown">
         Command="{Binding RichTextBoxKeyDown,
     <i:EventTrigger EventName="ContentChanged">
         Command="{Binding RichTextBoxContentChanged, 
     <i:EventTrigger EventName="LostFocus">
         Command="{Binding RichTextBoxLostFocus, 



As you see here; I used EventToCommandTrigger to invoke these events using Commands. And that’s gonna help MVVMers to create there own ViewModel for that control. (If they want)

I’m sure that Sacha Barber (This one who creates Cinch Framework) used WeakReferences. and that gonna help GC to do his work. Smile Or simply you just use the delegate commands, or relay commands instead in PRISM. For me I prefer to use Cinch framework; I think it’s a preference.

TagsTextBox Control contains three properties:

  • Tags DependencyProperty: To display tags in RichTextBox.
  • AllTags DependencyProperty: Which contains all tags to display it on autocomplete popup.
  • InlineUITags CLR read only property: Which contains the Tag Items that you can find it in RichTextBox. 

When user starts typing FilterPopupList will be executed. The Main functionality of this Method is to:

  • Iterating into all InlineUIContainers to get tags texts.
  • Tags Popup will display = all tags except existing tags in RichTextBox.
private void FilterPopupList(string changedText)
   if (changedText == null)
      PopupTagsList.ItemsSource = null;

   //Get Tags from RichTextBox
   List<string> newTags = new List<string>();
   foreach (InlineUIContainer inlineUiContainer 
                in this.InlineUITags)
     TextBlock tagNameTxtBlock = (TextBlock)((StackPanel)

   IEnumerable<string> tags = this.AllTags
                .Where(x => x.ToLower()

   PopupTagsList.ItemsSource = null;
   PopupTagsList.ItemsSource = tags;


When user commit tag insertion (by clicking enter or by choosing one of the items in the list); Then the source should be updated.

UpdateTagsPropertyAndBindingSource will do this work. Let me explain the logic
this method in three points.
  • Reset popup state if you want using isResetPopupState parameter.
  • Collecting the new added Tags.
  • Some Tags were deleted; so we should tell the source about it.
  • And Some tags were added; and we should tell the source about it also.
  • Update source using binding.UpdateSource()
  • And Finally, Raise TagsChanged event which contains Tags Added & Tags Deleted.

  • private void UpdateTagsPropertyAndBindingSource(
              bool isResetPopupState)
          if (isResetPopupState)
          IEnumerable<string> newTags = GetNewItemsAdded();
          // If some item found in Tags Collection And 
          // not in RichTextBox; So we should delete it.
          IEnumerable<string> mustBeDeleted = 
          List<string> mustBeDeletedList = null;
          //Tags must be deleted from the source
          int mustBeDeletedCount = mustBeDeleted.Count();
          int lastRemoveIndex = mustBeDeletedCount - 1;
          if (mustBeDeletedCount > 0)
             mustBeDeletedList = mustBeDeleted.ToList();
             for (int i = lastRemoveIndex; i >= 0; i--)
           //Tags must be added to the source
           IEnumerable<string> mustBeAdded = 
           IEnumerable<string> mustBeAddedList = null;
           int mustBeAddedCount = mustBeAdded.Count();
           if (mustBeAddedCount > 0)
             mustBeAddedList = mustBeAdded.ToList();
             foreach (string mustAddItem in mustBeAdded)
            if (mustBeDeletedCount > 0 || mustBeAddedCount > 0)
             BindingExpression binding = 
               if (null != binding) binding.UpdateSource();
               if (this.TagsChanged != null)
                   new TagsChangedArgs()
                    TagOwner = binding.DataItem,
                    TagsAdded = mustBeAddedList,
                    TagsDeleted = mustBeDeletedList

Ok, One more thing to know, What If you have multiple instances of this control. And as you see in the video; that you can add entire new tag which is not listed in the auto complete popup list.

So how could tell other controls that All Tags List changed?

If sure that you folks have many many solutions in binding, Observable collection has the ability to notify the UI when item added. yeah you are right.

I decided to use the Mediator in Cinch framework. Its really amazing (pub sub mechanism) which is like Event Aggregator in PRISM.

So I just publish new All Tags List.

I just passed the Id to refocus RichTextBox.

        public void CandidateTagsChangedMessage(
            Tuple<int, IEnumerable<string>, Type> tuple)
       this.AllTags = tuple.Item2;

       PropertyInfo pinfo = tuple.Item3.GetProperty("Id");
       int currentId = (int)pinfo.GetValue(this.DataContext,
       int updatedId = tuple.Item1;

       if (updatedId == currentId)


So the above code for the subscriber. And the publisher is our main view model.

public ICommand TagsChangedCommand { get; set; }
private void OnTagsChangedCommand(EventToCommandArgs args)
    TagsChangedArgs e = args.EventArgs as TagsChangedArgs;

    // TODO: Remove, add tags, Submit Changes to RIA Service
    // e.TagsAdded
    // e.TagsDeleted

       .Send(new Tuple<object>(e.TagOwner));


This command is binded with our TagsTextBox.TagsChanged Event

<bunjeebControls:TagsTextBox x:Name="MyTagsTextBox2"
   AllTags="{Binding AllTags}" 
   Tags="{Binding SomeTags2, Mode=TwoWay}" >

        <i:EventTrigger EventName="TagsChanged">
        Command="{Binding TagsChangedCommand}"/>



Sorry for not completing the 2nd article of pivot view control. I found that its more important to talk about Tagging Control. Since I did not any Silverlight Tagging Control.

That’s it. Wishing best coding in your life Smile

Download Sample

Silverlight Pivot View Control – Part 1


Download Sample


Just before one month from now, I worked with a new company; I really loved my new Job. New experience taken from Michael Ruddick; He is a Chief architect in T-Force.

I will not forget to talk about Tareq Amin “The Vise president in T-Force”. He is a big fan of the new Metro Apps style; Yeah Metro is amazing.

Tareq is listening to me a lot, sharing Ideas, respecting people.
Also he is studying to make Google’s 80/20 Innovation Model part of our work; or maybe to do like Innvoation Center in Amman Office; That’s really coool!

Ok, Lets talk about some geeky stuff here. Watch the video to see the output; And If you like it; Continue reading and download the sample from link below. Smile


Download Sample



I’ve just created a simple control, I called it Pivot View Control.

Simply this control contains

this control divided into three parts:
Title: Just a title for the Pivot Control (you can expose this property as a Dependency Property).
Header: Contains Items Control for Tabs (or Pivot Headers).
Content: Each header related with a UIElement which loaded in the Content Presenter.

<Grid x:Name="LayoutRoot" Background="White">
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" MinHeight="30"/>
        <TextBlock TextWrapping="Wrap"
Text="Title, select one of items below"
FontFamily="Segoe UI Semibold"
FontSize="21.333" Margin="7,0,0,0"/>
        <ListBox x:Name="PivotItemsHeaderList"
SelectedItem="{Binding SelectedItem, ElementName=PivotViewCtrl, 
                 Margin="0" Grid.Row="1"
Background="#00000000" BorderBrush="{x:Null}"
                 ItemsSource="{Binding Items, ElementName=PivotViewCtrl}"
                 ItemsPanel="{StaticResource ItemsPanelTemplate}"
          ItemContainerStyle="{StaticResource ListBoxItemContainerStyle}"
                 FontFamily="Segoe WP SemiLight" FontSize="24"
                 ItemTemplate="{StaticResource DataTemplateListItem}"/>
      <ContentPresenter x:Name="ContentPresenter" Margin="0" Grid.Row="2">
              <PlaneProjection CenterOfRotationX="0"/>

The animation createed using Visual State Manager, In the next version I’m going to add many animation options. For now this animation is good Smile.

Simply you can change the animation using Expression Blend, Go to states tab in blend and change the animation.

I have two states in my control;

GoAway: will hide current displayed content. And this animation completed I will change the content of it.

ComeIn: When GoAway animation completed and content changed.  Start the animation to bring the new content.


This is the animation completed Event:

void StoryBoardGoAway_Completed(object sender, EventArgs e)
   string headerValue = this.PivotItemsHeaderList.SelectedItem.ToString();
   var pivotItem = this.ItemsSource
        .SingleOrDefault(p => p.Header == headerValue);
   this.ContentPresenter.Content = (UIElement)pivotItem.Content;
   VisualStateManager.GoToState(this, "ComeIn", true);


This control is a dependency control; Its something like Tab Item.

public class PivotItemControl : DependencyObject
        public DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(String),
            typeof(PivotItemControl), null);
         public String Header
                return (String)GetValue(HeaderProperty);
                SetValue(HeaderProperty, value);
        public DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(UIElement),
            typeof(PivotItemControl), null);
         public UIElement Content
                return (UIElement)GetValue(ContentProperty);
                SetValue(ContentProperty, value);

How to use it?

public MainPage()
            this.Loaded += MainPage_Loaded;
         void MainPage_Loaded(object sender, RoutedEventArgs e)
            this.Loaded -= MainPage_Loaded;
       private void BindPivotItems()
          List<PivotItemControl> list = new List<PivotItemControl>();
          String[] headers = new string[] {"details","documents","notes"};
             foreach (string item in headers)
                 list.Add(new PivotItemControl()
                            Content=new DummyContentControl() { Tag=item }
           this.PivotViewControl.ItemsSource = list;

Some enhancements could occurred; like using one Usercontrol as a Content; And Change the DataContent when GoAway Animation Completed. But I think you need to Expose an Event, Yeah that gonna be great.

Step by Step – Filtering List using Reactive Extensions (Rx Framework)

  1. Download Rx Framework from here.
  2. Install it.
  3. Create New Windows Forms project (you can choose WPF, Silverlight, WP7). I used WinForms in my example.
  4. Add TextBox and ListBox to it as you see below.

Screen shot 2011-07-14 at 1.50.46 AM

  5.   Add System.Reactive reference to your project (see image below).

Screen shot 2011-07-14 at 1.53.05 AM

6.  Create any dummy data (you can use any repository you want) and just to make things fast Smile

Screen shot 2011-07-14 at 1.51.58 AM

7. Add this chunk of code.

Screen shot 2011-07-14 at 1.52.17 AM

When TextChanged raised the subscribed code will be executed Asynchronously.

That’s it. As simple as that.

Good night. Smile Grid View with jQuery Ajax (Dynamic Load for ASCX HTML)

After a couple of months without touching anything related to WEB. I’m doing some refreshment by creating Web Diagram Tool using jQuery “Something like Visio on WEB”.

Also my brother asked me to help to him to do a paging using AJAX.

I found some articles that used Update Panel …Yuk!!! .. Come-on people! are you still use it!! Update Panel could be useful sometimes. But its not a full AJAX. It will create a request for the whole page and when response comes back; It will refresh the part which in update panel.

I did something deferent and better. Its not new at all. Actually I worked on this task before a couple of years; I’m doing some refreshment, my brother just triggered me when he ask.

Simply, I loaded the Usercontrol  dynamically. and the Usercontrol contains anything you want (in my case it’s a GridView). Tada! pretty easy.

to load controls dynamically use this static method. I you want to use it; just modify it by adding your control and set your own properties.

private static String GetGridControlContent(String controlLocation,
 int pgIndex, int pgSize)
   var page = new Page();

   var userControl = (MyGridView)page.LoadControl(controlLocation);

   if (pgIndex < 0)
         pgIndex = 0;

   userControl.PageSize = pgSize;
   userControl.PageIndex = pgIndex;


   String htmlContent = "";

   using (var textWriter = new StringWriter())
    HttpContext.Current.Server.Execute(page, textWriter, false);
    htmlContent = textWriter.ToString();
   return htmlContent;


As you see above; you can pass any parameter to the Usercontrol by creating a properties in that user control. For me I created PageSize & PageIndex properties.

You can wrap this method in a web method to call it from Javascript.

public static string AjaxGetGridCtrl(int pgIndex, int pgSize)
     return GetGridControlContent("~/MyGridView.ascx", pgIndex, 


So you can load you control using script mnager or using jQuery AJAX library. I used the 2nd choice

    type: 'POST',
    url: 'MyDefault.aspx/AjaxGetGridCtrl',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
    data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"



jQuery AJAX is really nice. Let’s talk more about the options above.

type: you choose you either GET, or POST options.

url: I request this URL using POST.

contentType: used when you want to send data to the server (data is the last option). is this case the data will be sent in JSON format with UTF-8 Encoding.

dataType: The type of data that you’re expecting back from the server.

success: response will be handled here; if request succeeded.

I n this example; the HTML result will be rendered in mainDiv element.

data: parameters will be sent to the web method here.

Current Page Index and Page Size are stored in a Hidden Fields. And when user clicked on Next button; the value will be added by 1. And the AJAX call started by sending the new PageIndex.


function FillGrid(flag) {

 var pgIndex = 0;
 var pgCurrentIndex = $('#txtPgIndex').attr('value');
 var pgSize = $('#txtPgSize').attr('value');

 switch (flag) {
      case 'prev':
          pgIndex = parseInt(pgCurrentIndex) - 1;
      case 'next':
          pgIndex = parseInt(pgCurrentIndex) + 1;


           type: 'POST',
           url: 'MyDefault.aspx/AjaxGetGridCtrl',
           contentType: "application/json; charset=utf-8",
           dataType: 'json',
           success: function (data) {
           data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"


Calling GetGridControlContent will cause a crahs at this line

HttpContext.Current.Server.Execute(page, textWriter, false);
To avoid this crash; all you need to do is to add
a [run at server form tag] to your Usercontrol
<%@ Control Language="C#" AutoEventWireup="true" 
    Inherits="test.MyGridView" %>
<form id="form1" runat="server">
<asp:GridView ID="gv" runat="server" AllowPaging="true" 
        <asp:BoundField DataField="ID" 
               HeaderText="First Name" Visible="false" />
        <asp:BoundField DataField="FirstName" 
               HeaderText="First Name" />
        <asp:BoundField DataField="LastName"
               HeaderText="Last Name" />
        <asp:BoundField DataField="Mobile" 
               HeaderText="Mobile" />
        <asp:BoundField DataField="EmpSalary" 
               HeaderText="Salary" />
        <asp:BoundField DataField="HiringDate" 
               HeaderText="Hiring Date" />
        <asp:BoundField DataField="DOB" 
               HeaderText="Date of Birth" />
<div id="pgingFooter">
    <a href="javascript:void(0);" id="prev">Previous</a> 
        &nbsp;|&nbsp; <a href="javascript:void(0);"



And there is no magical things in the code behind for this user control, Just fill your GridView Control according to PageIndex & PageSize properties.

public partial class MyGridView : System.Web.UI.UserControl
        private List<Employee> lstEmployees;

        public int PageSize { get; set; }
        public int PageIndex { get; set; }

        protected void Page_Load(object sender, EventArgs e)
            lstEmployees = new List<Employee>();

            lstEmployees = 
                       lstEmployees.Skip(this.PageIndex * this.PageSize)

            gv.DataSource = lstEmployees;

        private void FillList()
            for (int j = 1; j <= 100; j++)
                lstEmployees.Add(new Employee { 
                     ID = j, FirstName = "First" + j, 
                     LastName = "Last" + j, 
                     Mobile = "+932 55 1212" + j, 
                     EmpSalary = j * 100, 
                     DOB = "12/12/1990", 
                     iringDate = "12/12/2010" });


You can download the sample from here

Host WCF Service in WAS

Before doing these steps; host your WCF service in IIS. I assumed that you already did that. And my target here is to host the service in WAS with net.tcp port 🙂 thank you.

Installing WAS (you can ignore these steps if WAS already installed)

1.Control Panel >> Programs.
2.Under Programs and Features, click Turn Windows Features On And Off.
3.Select Windows Process Activation Service and its sub-features.
4.Select Microsoft .NET Framework 3.51 and its sub features.
5.Click OK.
Let’s Configure the Host Environment for the WCF Service to Support the TCP Protocol:

1.  Start inetmgr as administrator.

2.  Default site >> Right click >> Edit Bindings.

3.  If you have installed WAS correctly, it should list the default protocol bindings for the Web site, as shown in the following image:

Hosting WCF TCP Port

4.  Expand the Default Web Site item, and then click on your service (which is already hosted in IIS) application.

5.  Advanced Settings.

6.  In the Enabled Protocols add comma then net.tcp

Host WCF Service in WAS

7.  Click OK.

Now, Lets Configure the Client Application to Connect by Using the TCP Protocol.

  1. Test the service on the browser (copy paste the url to your browser) and make sure if it works.
  2. Now, Regenerate the proxy using the svcutil.exe
  3. Open the new output.config
  4. Get the new TCP Binding & endpoint from the file and add it to your client app.
    (The green bubbles below shows the net.tcp configuration).

5. Open the main() method in your client application and paste this line below:

ProductsServiceClient proxy = new ProductsServiceClient();

6. Run your app.

7. !!! What was that! Crash!

You have more than one endpoint available; you must specify which endpoint to use.

8. Just add your TCP endpoint’s name to your proxy constructor.

ProductsServiceClient proxy = new ProductsServiceClient(“NetTcpBinding_IService”);

TCP Endpoint name taken from:

10. Another Crash!! Go to the next step to solve that :).

11.Very important notes here:

  1. In most cases your machine will block the default TCP port; which is 808.
  2. For testing turn off your firewall.
  3. Add the port to the trusted ports:
  4. And to make sure that your Firewall will not block your port (if you do not turn it off); do the following:

i.     Go to Windows Firewall with advanced security.

ii.     And finally; add the port to Inbound Rules and Outbound Rules.