August 28, 2012

SQL Server Indexes - Definition

One of the most important technique to high performance queries in a SQL Server database is the index. Like we have index in books for fast searching, indexes speed up the querying process by providing fast access to rows in the data tables.

Indexes are of two types, clustered and nonclustered indexes.

Clustered Index

A clustered index is an index that stores the actual data. It is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A clustered index stores the actual data rows at the leaf level of the index. An important characteristic of the clustered index is that the indexed values are sorted in either ascending or descending order. As a result, there can be only one clustered index on a table or view. In addition, data in a table is sorted only if a clustered index has been defined on a table. A table that has a clustered index is referred to as a clustered table. A table that has no clustered index is referred to as a heap.

Non-Clustered Index

A non-clustered index is just a pointer to the data. It is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf nodes of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Unlike a clustered indexed, the leaf nodes of a nonclustered index contain only the values from the indexed columns and data row pointers , rather than contain the data rows themselves. This means that the query engine must take an additional step in order to locate the actual data.

A row pointer depends on whether it points to a clustered table or to a heap. If referencing a clustered table, the row locator points to the clustered index, using the value from the clustered index to navigate to the correct data row. If referencing a heap, the row locator points to the actual data row.

July 27, 2012

VisualStudio 2010, Define shortcut keys to Enable/Disable All Breakpoints


In Visual Studio, you can create or delete a single breakpoint by hitting F9, and can delete all breakpoints by Ctrl+Shift+F9 shortcut. It does not provide shortcut keys to disable or enable all breakpoints, but you can define that by yourself.
  • Go to Tools > Options popup.
  • Enter "DisableAllBreakpoints" in the textbox for Show commands containing:.
  • I am using Global option from User new shortcut in: combobox.
  • Set focus on Press shortcut keys textbox and hit your shortcut keys you want to set. (e.g. I am using Alt+1)
  • Press Assign button
  • Now press OK and use your new shortcut keys.(Make sure your newly created shortcut key is selected in Shortcuts for selected command) combobox while hitting OK button.
Similary you can set shortcut key for EnableAllBreakPoints or any other command.

June 27, 2012

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)

I have installed SQL Server and Management Studio on new machine and facing issues while connecting to SQL Server through remote machines on my local area network. After thorough searching and experimenting I have got resolved the error. Following are the steps(not necessary all) to resolve the issue.

SQL Server should be running

Go to All Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Configuration Manager. Select node SQL Server 2005 Services, under SQL Server Configuration Manager parent node. SQL Server's state should be Running. SQL Server Browser service should also be Running (you can Start/Stop by right click on service name)

Enable TCP/IP in SQL Server Configuration

Go to All Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Configuration Manager. Select node Protocols for SQLServer(your server's instance name) , under SQL Server 2005 Network Configuration.
TCP/IP's state should be Enabled. (can be Enabled/Disabled by right click on Protocol Name)

App Exception for SQL Server TCP Port in Windows Firewall

Go to Conctrol Panel > Windows Firewall > Exceptions (tab). Click button Add Port, enter name and port number 1433. Make sure your entered name is displaying in Programs and Services section, and should be checked while pressing OK button on the tab.

App Exception for sqlbrowser.exe in Windows Firewall

In Firewall window > Exceptions tab, click on Add Program. Locate the sqlbrowser.exe by Browse button. Click OK. At my system, it is located at C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe.

App Exception for sqlservr.exe in Windows Firewall

Similarly add sqlservr.exe in Firewall Exceptions. At my system, it is located at C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe.

Enable Remote Connection

Right click on SQL Server main node in Management Studio, and go to Properties. Select Connections page from Select a Page section. Allow remote connections to this server should be checked.

References


May 8, 2012

MS sql what is CTE? how to write recusive query in sql?


A common table expression (CTE) can be thought of as a temporary result set defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

Pseudocode and semantics

The recursive CTE structure must contain at least
  • one anchor member

    The first invocation of the recursive CTE consists of one ( or more) CTE_query_definition(s). Because these query definitions form the base result set of the CTE structure, they are referred to as anchor members. All anchor-member query definitions must be positioned before the first recursive member definition, and a UNION ALL operator must be used to join the last anchor member with the first recursive member.
  • one recursive member.

    The recursive invocation includes one or more CTE_query_definitions joined by UNION ALL operators that reference the CTE itself. These query definitions are referred to as recursive members.
The following pseudocode shows the components of a simple recursive CTE that contains a single anchor member and single recursive member.
WITH cte_name ( column_name [,...n] )
AS
(
CTE_query_definition –- Anchor member is defined.
UNION ALL
CTE_query_definition –- Recursive member is defined referencing cte_name.
)

-- Statement using the CTE
SELECT *
FROM cte_name
Example
Let's demontrate the Category table example, we have table with different categories, sub-categories, sub-sub-categroies etc... to Nth level.
We have the following data in our Category table:

CategoryID Name ParentID
1 Office NULL
2 Computer NULL
3 Books NULL
4 Office Accessories 1
5 Furniture 1
6 Decoration Items 1
7 LCDs 2
8 CPUs 2
9 Keyboards 2
10 Urdu 3
11 Programming 3
12 ASP.Net 11
13 C# 11
14 VB.Net 11
15 Java 11
16 PHP 11
17 Poetry 10
18 Stories 10
19 Novels 10
20 Kids 18
21 Funny 18
We are interested to get the full category names (from parent category to last child category, e.g. Books > Programming > C# ), we acheive the result implementing the same CTE pseudocode.
WITH CategoryList
AS
(
-- Anchor Query Member
SELECT parent.CategoryID, CONVERT(VARCHAR(50), Parent.Name) as Name, parent.ParentID
FROM Category as parent
WHERE parent.ParentID IS NULL

UNION ALL

-- Recursive Query Member
SELECT child.CategoryID, CONVERT(VARCHAR(50), CL.Name + ' > ' + child.Name) as Name, child.ParentID
FROM Category as child
INNER JOIN CategoryList as CL ON child.ParentID = CL.CategoryID -- Can be think of as the termination condition
WHERE child.ParentID IS NOT NULL
)

SELECT *
FROM CategoryList
That's simple, you will get the required output as:

CategoryID Name ParentID
1 Office NULL
2 Computer NULL
3 Books NULL
10 Books > Urdu 3
11 Books > Programming 3
12 Books > Programming > ASP.Net 11
13 Books > Programming > C# 11
14 Books > Programming > VB.Net 11
15 Books > Programming > Java 11
16 Books > Programming > PHP 11
17 Books > Urdu > Poetry 10
18 Books > Urdu > Stories 10
19 Books > Urdu > Novels 10
20 Books > Urdu > Stories > Kids 18
21 Books > Urdu > Stories > Funny 18
7 Computer > LCDs 2
8 Computer > CPUs 2
9 Computer > Keyboards 2
4 Office > Office Accessories 1
5 Office > Furniture 1
6 Office > Decoration Items 1

References

http://msdn.microsoft.com/en-us/library/ms175972.aspx

April 28, 2012

Cannot resolve collation conflict for column 1 in SELECT statement.

In MS SQLSERVER, When you try to concatenate, compare, make joins on columns (defined with different collations), you will get the following error message:

Cannot resolve collation conflict for column 1 in SELECT statement.

In MS SQLSERVER, collation can be set at column level. You can resolve the issue in different ways :
  1. Define same collation for each column in the subject query (Right click TableName > Design/Modify > Select Column > set Collation property in TableDesigner section of Column Properties pane).
  2. Place COLLATE DATABASE_DEFAULT after each column name used in the query. e.g.
    SELECT TOP 1
        FirstName COLLATE DATABASE_DEFAULT + ' ' +
        LastName COLLATE DATABASE_DEFAULT + ' ' +
        Email COLLATE DATABASE_DEFAULT + ' '       
    FROM [User]
    
  3. Place COLLATE DATABASE_DEFAULT after select clause, but before from clause. e.g.
    SELECT TOP 1
        FirstName + ' ' +
        LastName + ' ' +
        Email + ' '       
      COLLATE DATABASE_DEFAULT
     FROM [User]
    

April 23, 2012

How to edit selected rows manually in SQL Server Mangament Studio

Right-click on any specific table in SQL Sever object explorer, gives you the option Edit top 200 rows, and displays the top 200 rows in grid format, where you can edit values manually. But the problem arises when you want to edit rows in this way, but need rows of your choice, not top 200. You need the rows e.g. based on where clause filter expressions.

To obtain this behavior, you need the following steps :
  1. Right-click on any table
  2. Click Edit top 200 rows
  3. Right-click on any cell of the rows (displaying in the result pane)
  4. Goto Pane > SQL
  5. Now you can use where clause with filter expressions and you required and get the results in grid form which you can edit manually.

April 21, 2012

How to fix local host port number in visual studio

Recently I have faced an issue, how to fix the localhost port number in visual studio. With visual studio's default behavior, it changes the port number randomly (by checking any available port). But for some testing purpose I need it be retain at fixed number, so that I could refer the site with some static url for a specific timespan.

Following are the steps to set the fixed/static port number:
  • Select the website project node in solution explorer.
  • Right-click > Properties, OR press F4.
  • Set Use dynamic ports to false.
  • Enter any fixed available port number in the field Port number.

Now your localhost website's url remains on static port while you rerun you website.

April 14, 2012

jQuery with ASP.NET III - Animations

Since jQuery has emerged, interactive and more responsive web applications become easier to develop in today's world. It provides many powerful features that you could get use very efficiently with less coding, which otherwise requires more development efforts and lines of code to accomplish a single effect. In this article we will focus on animation features provided by jQuery and use animation effect in our ASP.Net website.

Background

In last post jQuery in ASP.Net II - GridView, we explored some responsive behavior with GridView control and validate our multi-line textbox to specified limit of characters. Here we set our focus on different animation methods provided:
  • Enlarging text on mousehover
  • Creating fade effect on mousehover
  • Sliding elements
  • Animating the panel
  • Hide and Display panels
  • Chain of animations
Note that we only discuss code segments here for jQuery, with assumptions that corresponding ASP.Net controls are already placed on the webpage. You will get cleared while we proceed further. We will only discuss the code placed inside the script segment required for jQuery, like:
<script type="text/javascript">
     $(document).ready(function () {
         
         // our jQuery code will goes here...

     });
    </script>

Enlarging text on mousehover

We place a label with some text displayed in it, and on mousehover we will enalrged the text inside the label by changing its font size.
var origFontSize = parseFloat($(".enlarge").css('font-size'));
    $("#content").hover(
        function () {
            $(".enlarge").css("cursor", "pointer");
            var newFontSize = origFontSize * 3;
            $(".enlarge").animate({ fontSize: newFontSize }, 300);
        },
        function () {
            $(".enlarge").animate({ fontSize: origFontSize }, 300);                    
        }
    );
Assumption : You have placed a fieldset with ID = content and dropped a Label with CssClass = enlarge, and put come text content int it. We have defined the enlarge class as :
.enlarge
    {
        font-size: 12px;
        font-family: Arial,sans-serif;
    }
  • parseFloat($(".enlarge").css('font-size')) selects our label which
    has css class enlarge, and retrieve its font-size property, parseFloat to our variable origFontSize.
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our label control to pointer
  • newFontSize set our font size variable with new size, by multiplying original font size with our multiplier scale, 3 in this case.
  • $(".enlarge").animate({ fontSize: newFontSize }, 300); here the actual method comes which do the animation on our label control. animate method takes the animation object with properties required to animate. In our case we only passed the property fontSize with our new size value newFontSize. This directs the animate method to change the properties passed as parameters with new values. And the second parameter for animate method, we passed the time span value in milliseconds. In our case it takes 300 milliseconds to changes its font-size with new value.
  • $(".enlarge").animate({ fontSize: origFontSize }, 300); Inside the
    mouseout function, we reset our fontSize with original value contained in the variable origFontSize

Creating fade effect on mousehover

Place a fieldset with id = content and put an image control inside fieldset container.
$("#content").hover(
            function () {
                $("#<%=Image1.ClientID%>").css("cursor", "pointer");
                $("#<%=Image1.ClientID%>").fadeOut(1000);
            },
            function () {
                $("#<%=Image1.ClientID%>").fadeIn(1000);
            }
        );
Assumption : You have placed a fieldset with id = content, and have an image control inside the fieldset container with ID = Image1. Set its src property to an image's path, here we create an images folder at the website's root and put our image.jpg in this folder. Also set CssClass for our image control to imagecontent, which we defined as :
.imagecontent
        {
            width: 350px;
            height: 250px;
        }
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our image control to pointer
  • fadeOut is the actual method with creates the animation effect of fadeout. It takes the parameter to set the time span consumed to create the desired effect.
  • fadeIn Inside the mouseout function, we reset our image control with fadeIn with the required time span parameter.

Sliding elements

Drop a button control to provide the user a way to click and get slide the elements. Place a div with our any html content.
$("#<%= btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();
            if ($(".slide").is(":hidden")) {
                $(".slide").slideDown("slow");
            }
            else {
                $(".slide").slideUp("slow");
            }
        });
Assumption : You have placed a Button control on the form with ID = btnSubmit. And have a div with css class code>slide, we defined as :
.slide
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            display: none;
            height: 100px;
            background-color: #148A21;
            color:#000000;
        }
  • Attach click event for button btnSubmit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $(".slide").is(":hidden") first check, if our element with css class slide is already hidden, if so, then slideDown("slow") our element. We have passed the constant timespan slow defined with jQuery, you could also change to any desired timespan value.
  • if our element is not already hidden, then we will slideUp our element with the constant timespane value slow.

Animating the panel

Drop a button control to let the user do animate the panel accordingly. Place a panel with our html content.
var regular = true;
        $("#<%=btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();

            if (regular == true) {
                $(".contentArea").animate({
                    opacity: 0.5,
                    width: "500px",
                    height: "280px",
                    fontSize: "36px",
                    borderWidth: "15px"
                }, "slow");
            }
            else {
                $(".contentArea").animate({
                    opacity: 1.0,
                    width: "300px",
                    height: "100px",
                    fontSize: "12px",
                    borderWidth: "5px"
                }, "slow");
            }

            regular = !regular;
        });
Assumption : You have dropped a button control on the form with ID = btnSubmit. Placed a panel with CssClass = contentArea, we have defined as :
.contentArea
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            width: 300px;
            height: 100px;
            background-color: #9999FF;
            border: solid;
        }
  • var regular = true define our variable to maintain the status for our panel animation.
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • regular == true first check, if we have not already applied our animation on the panel. then (".contentArea").animate() method is called with different values for different css properties we have to change or applied on our panel content, and second paramter (slow)for animate method is the timespan to consumed in the animation effect.
  • else if have already applied the animation effects, now we are reverting back to
    our original css properties for the panel. We have set our orinial values for different css properties to be set for the targeted panel.

Hide and Display panels

Lets hide and display different panels, a menu like panel headers displayed on the
web page and we explore the corresponding content panels when we clicked on any
header panel.
$(".content_head").click(function () {
            $(".content_body").hide(100);
            $(this).next(".content_body").slideToggle("slow");
        });
Assumption : You have placed a series of pairs of panels. Set CssClass = content_head for first panel, which act as menu header, and set CssClass = content_body for second panel which displays the content for that menu item. We defined these css classes as :
.content_head
    {
        width: 150px;
        height: 30px;
        background-color: #CCCCCC;
        cursor: pointer;
    }
    .content_body
    {
        display: none;
        width: 150px;
        height: 50px;
        background-color: #9999FF;
    }
  • Attach the click event for the panels with css class content_head.
  • $(".content_body").hide(100) first hide all the content elements, if already explored some other menu item and showing the content, we first hide that contents.
  • $(this).next(".content_body").slideToggle("slow") now grab the current clicked element by this and find the next content item attached for this menu item by next(".content_body"). Here we reached the content panel attached to the click menu item. Now we toggle the slide status by calling slideToggle() with constant timepspan slow.

Chain of animations

Now we place a panel box on the web page and animate it. We are not restricted to
animate our elements only once but jQuery provides the the power to chain your animation effects for any elements you want.
$("#<%=btnSubmit.ClientID%>").click(function (e) {
        e.preventDefault();
        $('.contentArea').animate({ left: "+=200"}, 2000)
                .animate({ top: "+=100"}, 700)
                .animate({ left: "-=400"}, 1200)
                .animate({ top: "-=100"}, 700)
                .animate({ left: "+=200"}, 2000);
        });
Assumption : You have dropped a button control with ID = btnSubmit
and let the user to control the animation effect by this button. Place a panel with
CssClass = contentArea, we have defined the css class as :
.contentArea
    {
        width: 50px;
        height: 50px;
        background-color: #71B3A2;
        border: solid;
        position: relative;
    }
    
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $('.contentArea') select our panel and call animate()
    methods repetitively in a chain model. Keep min minde that the animate() methods returns object element to which it is already called, so by repetitively calling this method with continous . notation we actually calling this method for the same object in reptition pattern, because the method returns the same object to which it is called with updated object status.
  • animate({ left: "+=200"}, 2000)animates the panel by changing its position on the webpage, set its css left property to some new value, and provide the timespan 200 in milliseconds to complete the animation in this span.
  • animate({ top: "+=100"}, 700) changes the top position of the panel
    by adding some new value to its css property top.
  • animate({ left: "-=400"}, 1200) again change the left
    css property, but this time passes a negative value, so this value is now subtracted
    form the current left position of the panel on the webpage.
  • animate({ top: "-=100"}, 700) change the top css property, but this time passes a negative value, so this value is now subtracted form the current top position of the panel.
  • .animate({ left: "+=200"}, 2000); again change the left css property, and add change the left position of the panel.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

We have explored some jQuery functions for achieving animation effects. jQuery offers many useful utilities to design animation, thus empowering developers to build rich animated pages for a better interactive experience for the web users. You must explore those methods and you will find that its now become very easy to develop interactive web pages with jQuery by spending very little effort.

You could download the working copy for these code samples from my CodeProject post
jQuery with ASP.NET III - Animations

March 30, 2012

jQuery in ASP.Net II - GridView

jQuery now become the major part of web development in current environment. In my
last post Getting started with jQuery in ASP.Net, we have started to explore jQuery methods with ASP.Net common controls. Now we are going one step further in jQuery use for our ASP.Net website.
We have already explored some most common tasks we encounter with asp.net controls in jQuery. Now we will discuss :
  • Creating "Back to Top" link
  • Highlight GridView's row or cell on mouseover
  • Remove GridView's row on mouseclick
  • Remove GridView's column on mouseclick
  • Character limit validation in Multiline Textbox
Note that we are only discuss code segments here for jQuery, with assumptions that corresponding asp.net controls are already placed on the webpage. You will get cleared while we proceed further. The code segments we discussed would be placed inside the script segment required for jQuery(now it seems to become a convention for most of the developers), like:
<script type="text/javascript">
     $(document).ready(function () {
         
         // our jQuery code will goes here...

     });
    </script>

Creating "Back to Top" link

In lots of websites, we see the hyperlink "Back to Top". Let's use it in our webpage
with the help of jQuery.
$(".backtotoplink").attr("innerHTML", "Back to Top");
$(".backtotoplink").attr("title", "Back to Top");
$(".backtotoplink").attr("href", "#Top");
Assumption : You have large blocks of html content placed on the webpage, and at the end of each block, we placed a hyperlink with css class backtotoplink, which we have defined as :
.backtotoplink
    {
        color: Blue;
        cursor: hand;
    }
  • $(".backtotoplink").attr("innerHTML", "Back to Top");
    selects our hyperlink which has css class backtotoplink, and place "Back to Top" text as its content by setting its innerHTML attribute.
  • $(".backtotoplink").attr("title", "Back to Top"); sets "Back to Top" text in title attribute.
  • $(".backtotoplink").attr("href", "#Top"); sets #Top anchor target for our hyperlink showing Back to Top text.

Highlight GridView's row or cell on mouseover

GridView is the control developers used more frequently because of its different capabilities. GridView is rendered in html as tree strcuture of table,tr,td. All we have to play with these html tags to build GridView attractive or response to mouseevents.
$("# ˸%=GridView1.ClientID% ˺ td").hover(
            function () {
                $(this).addClass("highlight");
            },
            function () {
                $(this).removeClass("highlight");
            });
Assumption : You have placed a GridView control on the form with ID = GridView1. And have a css class defined some where, we have :
.highlight
        {
            background-color: #34FF6D;
        }
  • $("#<%=GridView1.ClientID%> tr").hover() attach a mouse hover event for GridView control, note that jQuery's hover
    method contains two function arguments, for mouseover and mouseleave.
    After GridView1.ClientID we place tr to select only rows (you can replace this with td to obtain same functionality with individual cell rather than row.)
  • $(this).addClass("highlight"); in mouseover event function we add class highlight to current row (or cell if you are using td in jQuery selector).
  • $(this).removeClass("highlight");in mouseleave event function we remove class highlight from current row (or cell if you specified that).

Remove GridView's row on mouseclick

Now capture click event for the row (tr) and remove all its cells (td) and itelself.
$(("#˸%=GridView1.ClientID %˺ tr(").click(function () {
                $(this).find(("td(").each(function () {
                    $(this).remove();// remove td
                });
                $(this).remove();// remove tr
            });
Assumption : You have placed a GridView control on the form with ID = GridView1.
  • Attach click event for each row.
  • Inside the click even, loop for each cell (ts) and remove it.
  • Remove the row (tr) itself too.

Remove GridView's column on mouseclick

Now capture click event for the column (th) and remove all its cells (td) and itelself. We handle event only for th, so it only works when you click on columns headers.
$("#<%=GridView1.ClientID %> th").click(function () {
            var count = $(this).closest("th").prevAll("th").length;
            $(this).parents("#˸%=GridView1.ClientID %˺")
              .find("tr").each(function () {
                $(this).find("td:eq(" + count + ")").remove();
                $(this).find("th:eq(" + count + ")").remove();
            });
        });
Assumption : You have placed a GridView control on the form with ID = GridView1.
  • Attach the click event for column headers (th).
  • .closest() begins with the current element and searches up in DOM tree till it finds a matching element.
  • .prevAll() finds all the predecessors for the current element in DOM tree. Place all founded elements length in the variable count.
  • Loop through each row (tr) in the GridView
  • Remove the td that founded with matching count.
  • Also remove the header cell (th) that founded with matching count.

Character limit validation in Multiline Textbox

When use multiline textboxes in asp.net, sometimes we need to restrict number of characters entered. In this example we restrict our textbox to accept characters in limit of 5-100
var minCount = 5;
        var maxCount = 100;
        $("#˸%=txtComments.ClientID%˺").bind("cut copy paste", function (e) {
            e.preventDefault();
        });

        $("#˸%=txtComments.ClientID%˺").keypress(function (e) {
            var strCount = $("#˸%=txtComments.ClientID%˺").val().length;
            $("#˸%=txtNumber.ClientID%˺").val(strCount);
            if ((strCount ˸ minCount) || (strCount ˺ maxCount)) {
                $("#message").text("Please enter characters in the range 5 - 100");

                if (strCount ˺ maxCount) {
                    e.preventDefault();
                }
            }
            else {
                $("#message").text("");
            }
        });
Assumption : You have placed a comments textbox control with ID = txtComments, and another textbox with ID = txtNumber to display number of characters entered.
  • Bind the event hander for cut/copy/paste operations for textbox, and disable these operations so that we could capture keypress event in order to update the character count.
  • Set txtComments value's length in the variable strCount.
  • Set this count in txtNumber text to display.
  • Check if strCount is less than minCount or strCount is greater than maxCount, then display message for user to enter characters in correct range.
  • e.preventDefault(), Finally disable the default behaviour for keypress event, to further accept any input character.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

We did some interesting things with GridView control at runtime by capturing mouse events. Then we restrict our comments textbox to accept a predefined number of characters, and notify user to input in valid range. Definitely, we can all do these tricks with traditional javascript techniques, but you see how easier it becomes with the help of jQuery.

You could download the working copy for these code samples from my CodeProject post
jQuery in ASP.NET: Part II - GridView

March 20, 2012

Blog verification

Technorati
4KC8DQ5PKZEB

Blog Directory
http://www.blogbal.com/submit.php
Free Blog Directory


addyourblogbanner




www.bloghints.com
BLOG DIRECTORY, Submit blog free, Promote Blog, Best directory


DotNetTechy
Dotnettechy for .Net Professionals
This is for .Net professionals to professionals
Free Online Image resizer
There are three easy steps to resize images, photos for your blog, website, facebook etc.
It is very fast, no need to install any software on your system and it does not require any registration.


Blogs Rating
Blogs Rating
Blogs Archive Blogs Archive
BlogsRater Blogs lists and reviews

Blog Directory Top Blog Sites
Blog Promotion, Promote Your Blog
Submit Blog, Blog Directory Submission
Blogs Blog Tools Promote Blog

Blog directory

Find the best blogs at Blogs.com.

Technology Blogs - Blog Rankings

March 16, 2012

Let's start JQuery with ASP.Net

JQuery is the most widely used JavaScript library in web applications today, supported by an active community of developers. It is a complex JavaScript object, could be think of as a wrapper over selected DOM elements with extended functionality. JQuery is designed to be lightweight, cross browser, and CSS3 compliant. It simplifies the way DOM elements are selected, and make your operations on that elements.

jQuery can be implemented with various web platforms such as .NET, PHP and Java.
Now having the official support of Microsoft, it is now distributed with Visual
Studio (Version 2010 onwards). The library has gained popularity with ASP.NET developers. jQuery can be very easily implemented with ASP.NET controls as well as custom user controls. It can be used to validate controls using client side scripts, incorporate cool animation effects.

jQuery Selectors allow you to select DOM elements so that you can apply functionality to them with jQuery’s functional methods, and helps to encorporate CSS very easily. Using CSS means that you use selector syntax you’re probably already familiar with from HTML styling. You can select elements by id, CSS class, attribute filters, by relationship to other element and also filter conditions that can be combined together.

JQuery could be downloaded from official JQuery website .

Start JQuery

We use local copy of JQuery in our samples. Look at the head section of aspx page
where the JQuery script is placed:
<script src="js/jquery-1.4.1.js" type="text/javascript"> </script>
      <script type="text/javascript">
        
        /* INCLUDE JQUERY MARKUP HERE */

    </script> 
First script tag points to our local copy of JQuery i.e, in js folder, inside website's root directory. Second script will be populated with our JQuery implementations or any javascript code.

Our page is now enabled for using jQuery. We can now include the required jQuery
markup in the script block as follows:
<script type="text/javascript">
$(document).ready(function() {

//any jquery code goes here...

});
</ script>
All the jQuery markup on the page should be included in the code>$(document).ready() function. This function is executed as soon as the DOM is loaded and before the page contents are rendered.

Disallow cut/copy/paste operations for textbox

Inside the document's ready JQuery script, place the event handler's
of textbox for cut/copy/paste operations. e.g. The following code segment disallow
these operations for our textbox txtPwd :
$('#<%=txtPwd.ClientID%>').bind('cut copy paste',

            function (e) {
                e.preventDefault();
                alert("Cut / Copy / Paste are not allowed in this field");
          
            });
Assumption : Your form contains a textbox control with ID = txtPwd

e.preventDefault() is the key method provided by the script engine,
to disable the default operations to proceed further. We first stop the event for further bubble up to any other parent controls. And put any custom logic of your interest, after that, here we are notifying the user that these operations are not allowed for this textbox.

Display selected items of Checkboxlist

Again, in the document's ready function, attach the handler for our checkboxlist's click event. Within the click event handler, we traverse through each checkbox (by checking its input[type=checkbox]) by JQuery's each() function, which actually called for every check box with in this list.
$('#<%=CheckBoxList1.ClientID%>').click(function () {
                var str = "";
                
                $('#<%=CheckBoxList1.ClientID%>input[type=checkbox]')
                   .each(function () {
                    if ($(this).is(':checked')) {
                        str = str + " - " + $(this).next().text();
                    }
                });

                $('#message').text(str);
            });
Assumption : Your form contains a CheckBoxList control with ID = CheckBoxList1

Now explore some more powerful methods provided by JQuery.
  • input[type=checkbox] filters all checkboxes within our CheckBoxList1 control.
  • $(this) segment, it represents the current item being focused on by code. i.e. this time, it behaves as checkbox individual item iteself.
  • .is() method, used to find the state of current checkbox, by query its checked property.
  • .next() method, retreives the next sibling for current node/control. Sinch each checkbox is rendere with two html tags, label and input. So we are at label context, and use code>next() method to move our focus to input (real checkbox).
  • .text() method, retreives the text content of the current item in focused.
  • $('#message') method, retreives the html control with id="message".
  • .text(str) method, sets the text content (passed as parameter) for the control it is called.

Get selected text/value from DropDownList

Within the document's ready function, bind the handler for our keyup and change events of DropDownList.
$('select[id$=<%=DropDownList1.ClientID%>]').bind("keyup change", 
function () {
                var selectedItem = $(this).find(":selected");
                if (selectedItem.val() != "") {
                    var msg = "Text : " + selectedItem.text() + ' Value: ' 
                               + selectedItem.val();
                    $('#message').text(msg);
                }
                else {
                    $('#message').text("");
                }
            });
Assumption : Your form contains a DropDownList control with ID = DropDownList1
  • .find() retreives the selected item, and we put in our variable selectedItem.
  • For root item, we put empty string in its value property. So here we check if its value it empty, then remove any message placed in message div.
  • If we have non-empty string in value property, then its a valid item selected from the list. So we can get its .text() and .val() and use it for our code.

Change focus to next control on Enter key

Bind the keydownevent handler for our textboxes.
$('input:text').bind("keydown", function (e) {
                if (e.which == 13) { //Enter key
                    //to skip default behavior of the enter key
                    e.preventDefault(); 
                    var nextIndex = $('input:text').index(this) + 1;
                    var control = $('input:text')[nextIndex];
                    if (typeof control == 'object') {
                        control.focus();
                    }
                    else {
                        // we reached at last control, 
                        // return focus to first input control.
                        $('input:text:first').focus();
                    }
                }
            });
Assumption : Your form contains a series of textboxes, and no any other control
is encountered in between the series.

  • In handler function, we check for Enter key code e.which==13, when we get Enter key then first we prevent the default behaviour of Enter, and put our logic.
  • Get the next textbox's index, first get index of current textbox, then add 1 to this index. And set next textbox control in our variable control.
  • Check if typeof control is object, means we reached the next textbox properly, so set focus to it. Otherwise set focus return to our first textbox in the series.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

JQuery is a powerful scripting library that makes developing in JavaScript easier. It has a lot of practical benefits for JavaScript developers and can perform in a variety of situations. JQuery also provides the utility functions that implement common functions useful for writing jQuery. These functions by themselves are particularly facilitates the development with ease and great pace.

You could download the working copy for these code samples from my CodeProject post
Let's start jQuery with ASP.NET

February 27, 2012

MongoDB - Updating Records

Introduction

I have covered the basic queries (select, insert and delete) of MongoDB in my last post, now I will describe here how to update records in MongoDB. Update recrods is one the four basic operations CRUD (create, read, update and delete) for any database we required. MondoDB also provided its update queries, with more sophisticated tasks. Update queries funtion in Mongo is not straight forward like sql databases, its a little more enhanced functional component than simple update. You will find that it facilitates the general operations of routine development tasks, and we could made our database operations with less complications in the data layer.

Background

Update queries are capable to do the following jobs :
  • It could replace the entire document (recall, you could think of it as DataRow in .Net environment)
  • Simply update the recrods like in simple sql databases, the number of fields you specify will be updated with the provided condition.
  • Provide special $inc modifier, if you need to increment or decrement a field's value.
  • $push modifier adds a value to the array (recall, you could place entire arrays in your document's fields)
  • An upsert updates the document if found or inserts it if not.

Description

In its simplest form, update takes 2 arguments: the selector (where) to use and what field to update with. If Imran has to change the category he played, we could execute:
db.KarachiTigers.update({name: 'Imran'}, {category: 'Bowler'})
If this was real code, you'd probably update your records by _id, but since I don't know what _id MongoDB generated for you, we'll stick to names. Now, if we look at the updated record:
db.KarachiTigers.find({name: 'Imran'}) 
You should discover updates first surprise. No document is found because the second parameter we supply is used to replace the original. In other words, the update found a document by name and replaced the entire document with the new document (the 2nd parameter). This is different than how SQL's update command works. In some situations, this is ideal and can be leveraged for some truly dynamic updates. However, when all you want to do is change the value of one, or a few fields, you are best to use MongoDB's $set modifier:
db.KarachiTigers.update({name: 'Imran'}, {$set: {category: 'Bowler',
dob: new Date (1979, 7, 18, 18, 44), hobbies: ['cricket'], gender: 'm'}}) 
This'll reset the lost fields. It won't overwrite the new category since we didn't specify it. Now if we execute:
db.KarachiTigers.find({name: 'Imran'}) 
We get the expected result. Therefore, the correct way to have updated the category in the first place is:
db.KarachiTigers.update({name: 'Imran'}, {$set: {category: 'Bowler'}}) 
In addition to $set, we can leverage other modifiers to do some interesting things. All of these update modifiers work on fields - so your entire document won't be wiped out. For example, the $inc modifier is used to increment a field by a certain positive or negative amount. For example, if Amir was incorrectly awarded a wicket , we could correct the mistake by executing:
db.KarachiTigers.update({name: 'Amir'}, {$inc: {wickets: -1}})
If Saeed Ajmal has to update his bolwing actions, e.g, he could bowl off-spin and doosra, we could set the array items defined in actions field of the document:
db.KarachiTigers.update({name: 'Saeed Ajmal'},
{$set: {actions: ['off-spin', 'doosra']}})

Let's say, if Saeed Ajmal suddenly developed a teesra bowling action, we could add a value to his actions field via the $push modifier:
db.KarachiTigers.update({name: 'Saeed Ajmal'}, {$push: {actions: 'teesra'}})
The Updating section of the MongoDB website has more information on the other available update modifiers.

One of updates more pleasant surprises is that it fully supports upserts. An upsert updates the document if found or inserts it if not. Upserts are handy to have in certain situations and, when you run into one, you'll know it. To enable upserting we set a third parameter to true. An everyday example is a hit counter for a website. If we wanted to keep an aggregate count in real time, we'd have to see if the record already existed for the page, and based on that decide to run an update or insert. With the third parameter omitted (or set to false), executing the following won't do anything:
db.hits.update({page: 'cricket updates'}, {$inc: {hits: 1}});
db.hits.find();
However, if we enable upserts, the results are quite different:
db.hits.update({page: 'cricket updates'}, {$inc: {hits: 1}}, true);
db.hits.find();
Since no documents exists with a field page equal to cricket updates, a new document is inserted. If we execute it a second time, the existing document is updated and hits is incremented to 2.
db.hits.update({page: 'cricket updates'}, {$inc: {hits: 1}}, true);
db.hits.find();
A non-upsert update may or may not modify an existing object. An upsert will either modify an existing object or insert a new object. The client may determine if its most recent message on a connection updated an existing object by subsequently issuing a getlasterror command ( db.runCommand( "getlasterror" ) ).
  • If the result of the getlasterror command contains an updatedExisting field, the  last message on the connection was an update request.
  • If the updatedExisting field's value is true, that update request caused an existing object to be updated;
  • If updatedExisting is false, no existing object was updated.
  • An "upserted" field will contain the new _id value if an insert is performed.
The final surprise update has to offer is that, by default, it'll update a single document. So far, for the examples we've looked at, this might seem logical. However, if you executed something like:
db.KarachiTigers.update({}, {$set: {qualified: true }});
db.KarachiTigers.find({qualified: true});
You'd likely expect to find all of your team members to be qualified. To get the behavior you desire, a fourth parameter must be set to true:
db.KarachiTigers.update({}, {$set: {qualified: true }}, false, true);
db.KarachiTigers.find({qualified: true});
We concluded our introduction to the basic CRUD operations available against a collection. We looked at update in detail and observed three interesting behaviors. First, unlike an SQL update, MongoDB's update replaces the actual document. Because of this the $set modifier is quite useful. Secondly, update supports an intuitive upsert which is particularly useful when paired with the $inc modifier. Finally, by default, update only updates the first found document. Do remember that we are looking at MongoDB from the point of view of its shell. The driver and library you use could alter these default behaviors or expose a different API.

January 31, 2012

MongoDB in C#.net

Introduction

This article explain how to communicate with MongoDB from C#.net, providing an exmaple. I was looking for such sample example for MongoDB in C#.net, but after reasonable searching I not found some real practical tutorial showing complete example to communicate with MongoDB. Therefore I wrote this article to provide a complete sample to use MongoDB from C#.net for developers community who want to start with this new technology. So I put together that scattered information I founded on serveral sites to compile into some real practical sample application.

Background

There are some drivers available for communicating with MongoDB from C#.net, I prefer to use the official driver recommended available here. So you must have download that driver and add references for the driver's essential libraries in your
project, such as :

  1. MongoDB.Bson.dll
  2. MongoDB.Driver.dll
At the time of executing this application, make sure that the MongoDB server is running.

Example

This sample application contains one form with different buttons :
  1. Create Data, Create sample data for Departments and Employees collections (keep remember, at first time you query any particular collection, mongoDb automatically create these collections if not already created).
  2. Get Departments, this will display the sample data created for departments colleciton, in the grid placed on the form.
  3. Get Employees, this will display the sample data created for employees colleciton, in the grid placed on the form.
  4. Delete Departments, this will delete all the departments available in the departments collection.
  5. Delete Employees, this will remove all the records available in the employees collection.
Let's start with the code. First define the connection string for your mongoDB server, by default its running on 27017 port, or you have to change it accordingly if you have specified something else. For example on my PC, I have server running on localhost at port 27017.

key="connectionString" value="Server=localhost:27017"

For create sample data, we use two methods CreateDepartment() and CreateEmployee(). Let first take a look at CreateDepartment method. It takes two parameters departmentName and headOfDepartmentId, which is practically should be the real head's Id, but for sampling here just any random Id is used. The core functionality of this method is :

  1. Connect to server: MongoServer.Create(ConnectionString) accepts the connection string for your server, and returns MongoServer type object, which later use to query the desired database object.
  2. Get Database: server.GetDatabase("MyCompany") this call returns MongoDatabase type object for the database used in this example MyCompany
  3. Retrieve departments collection: myCompany.GetCollection("Departments"), this method will actually retrieve our records from departments collection. It returns MongoCollection of passed generic type, BsonDocument
    in this case. At first time, definitely there will be no any departments present in the departments collection, so this collection object is empty(has 0 records).
  4. Create new department object: BsonDocument deptartment = new BsonDocument {}, this constructor syntax creates new department with the fields as you speficed in the constructor(remember MongoDB document could have different
    fields, not necessary that all documents have same fields)
  5. Insert document in departments collection: departments.Insert(deptartment), will actually insert the document in our departments collection.
private static void CreateDepartment(string departmentName, string headOfDepartmentId)
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");

 BsonDocument deptartment = new BsonDocument {
 { "DepartmentName", departmentName },
 { "HeadOfDepartmentId", headOfDepartmentId }
 };

 departments.Insert(deptartment);
}
Similarly CreateEmployee() method takes its parameters, connect to server, database, employee collection and insert employee in the collection. I follow the same flow to keep things clear for understanding.
private static void CreateEmployee(string firstName, string lastName,string address, string city, string departmentId)
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection employees = myCompany.GetCollection("Employees");
 BsonDocument employee = new BsonDocument {
 { "FirstName", firstName },
 { "LastName", lastName },
 { "Address", address },
 { "City", city },
 { "DepartmentId", departmentId }
 };

 employees.Insert(employee);
}
Next, we want to retrieve our recrods to display in the grid. We already look at retrieve code segment, just make a little changes here. Instead of BsonDocument I use my custom Department class which loaded collection of departments with my class objects. But make sure that the fields in the department collection must be exactly mapped in your Department class. Just calling GetCollection() method not actually retrieve the records, you need to call any desired method with query selectors (not covered in this aricle), so make things clear I just use simplest method FindAll() which rerieves all records from the given collection. Loop through each item and add in our temporary list which finally binds to our grid for display purpose. And I have followed the same theme to display employee records.
public static List GetDepartments()
{
 List lst = new List();
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");
 foreach (Department department in departments.FindAll())
 {
  lst.Add(department);
 }

 return lst;
}
The last thing we see here is the deletion of records. As we all know, deletion is the simplest job in most of the cases, and same here. After getting the MongoCollection object, you have to simply call its method Drop(), and it will simply delete all the records from that collection. You can also use query selectors in different methods to remove records selectively but that will be out of the scope of this article.
public static void DeleteDepartments()
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");
 departments.Drop();
}
Once you get started with MongoDB you will enjoy exploring its dimensions. I found very intesresting capabilities of MongoDB. I appreciate your feedback/comments or any improvements you want to suggest in this regard, to help in making the article much better and helpful for others.

Note: Source code for sample application could be found at my CodeProject post.

January 30, 2012

Getting started with MongoDB

Introduction

Some time ago, I heard about MongoDb and I started searching on search engines to get know its scope. I found lot of supporting material in scattered form on various websites and books. Than I thought to compile atleast some basic getting started sort of tutorial for MongoDB. So that the developers who are new to MongoDB or unfamilir with, can get to know what is it and how to initiate development with this new technology.
I must mentioned here that this article is much inspired by Karl Seguin's book on MongoDB. His blog can be found here.
This article demonstrates the introduction of MongoDB, no-sql, the document-oriented database. The developers who are unfamiliar with no-sql database, will wonder how it works. As a document-oriented database, MongoDB is a more generalized NoSQL solution. It should be viewed as an alternative to relational databases. Like relational databases, it too can benefit from being paired with some of the more specialized NoSQL solutions. Take it as simple as just any database, which stores data in some particular structure. Let's first setup your environment and enjoy the MongoDB power and start thinking to use it in your projects where you find appropriate.

Setting up the MongoDB

It's easy to set up and running with MongoDB.
  1. Go to the official download page and get the binaries of your choice.
  2. Extract the archive (any where you want) and navigate to the bin subfolder. Note that mongod is the server process and mongo is the client shell
    - these are the two executables we'll be spending most of our time with.
  3. Create a new text file in the bin subfolder named mongodb.config
  4. Add a single line to your mongodb.config: dbpath=PATH_TO_WHERE_YOU_WANT_TO_STORE_YOUR_DATABASE_FILES. For example, on Windows you might do dbpath=c:\mongodb\data
  5. Make sure the dbpath you specified exists
  6. Launch mongod with the --config /path/to/your/mongodb.config parameter. As an example, if you extracted the downloaded file to c:\mongodb\ and you created c:\mongodb\data\ then within c:\mongodb\bin\mongodb.config you would specify dbpath=c:\mongodb\data\. You could then launch mongod from a command prompt via c:\mongodb\bin\mongod --config c:\mongodb\bin\mongodb.config.
Hopefully you now have MonogDB up and running. If you get an error, read the output carefully - the server is quite good at explaining what happens wrong. You can now launch mongo which will connect a shell to your running server. Try entering db.version() to make sure everything's working as it should. Hopefully you'll see the version number you installed. Go ahead and enter db.help(), you'll get a list of commands that you can execute against the db object.

Some basic concepts

Let's start our journey by getting to know the basic mechanics of working with MongoDB. Obviously this is core to understanding MongoDB, but it will also help to give the idea about some higherlevel questions about where MongoDB fits.

To get started, there are six basic concepts we need to understand.
  1. MongoDB has the same concept of a `database' with which you are likely already familiar. Within a MongoDB instance you can have zero or more databases, each acting as high-level containers for everything else. You could be think of it as simple database object in Ms SQL Sergver just for understanding the idea more clear.
  2. A database can have zero or more `collections'. A collection shares the same concept as a traditional `table', that you can think of the two as the same thing.
  3. Collections are made up of zero or more `documents'. A document can be thought of as a `row'.
  4. A document is made up of one or more `fields', which you can guess, are like `columns'.
  5. `Indexes' in MongoDB function much like their RDBMS counterparts.
  6. `Cursors' are different than the other five concepts. When you ask MongoDB for data, it returns a cursor, which you can do your processing, such as counting or skipping ahead, without actually pulling down data.
In summary, MongoDB is made up of databases which contain collections. A collection is made up of documents. Each document is made up of fields. Collections can be indexed, which improves lookup and sorting performance. Finally, when we get data from MongoDB we do so through a cursor which is delayed to execute until necessary, might be called as lazy loading While these concepts are similar to their relational database counterparts, but they are not identical. The core difference comes from the fact that relational databases define columns at the table level whereas a document-oriented database defines its fields at the document level. Each document within a collection can have its own unique set of fields. As such, a collection is a container in comparison to a table, while a document has a lot more information than a row.

Let's start play with MongoDB

First we'll use the global use method to switch databases, go ahead and enter use mycompany. It doesn't matter that the database doesn't really exist yet. The first collection that we create will also create the actual mycompany database. Now that you are inside a database, you can start
issuing database commands, like db.getCollectionNames(). If you do so, you should get an empty array ([ ]). Since collections are schema-less, we don't explicitly need to create them. We can simply insert a document into a new collection. To do so, use the insert command, supplying it with the document to insert:
db.departments.insert({name: 'Human Resource', city: 'karachi', 
head: 'Muhammad Ibrahim'})
The above line is executing insert against the departments collection, passing it a single argument. Internally MongoDB uses a binary serialized JSON format. Externally, this means that we use JSON a lot, as is the case with our parameters. If we execute db.getCollectionNames() now, we'll actually see two collections: departments and system.indexes. system.indexes is created once per database and contains the information on our databases index. You can now use the find command against departments to return a list of documents:
db.departments.find()
Notice that, in addition to the data you specified, there's an _id field. Every document must have a unique _id field. You can either generate one yourself or let MongoDB generate an ObjectId for you. Most of the time you'll probably want to let MongoDB generate it for you. By default, the _id field is indexed - which explains why the system.indexes collection was created. You can look at system.indexes:
db.system.indexes.find()
What you're seeing is the name of the index, the database and collection it was created against and the fields included in the index.
Now, back to our discussion about schema-less collections. Insert a totally different document into departments, such as:
db.departments.insert({name: 'Development', country: 'Pakistan',
departmentManager: 'Saeed Anwar', annualBudget: 5000000})
And, again use find to list the documents. Hopefully now you are starting to understand why the more traditional terminology wasn't a good fit.
There's one practical aspect of MongoDB you need to have a good grasp of before moving to more advanced topics: query selectors. A MongoDB query selector is like the where clause of an SQL statement. As such, you use it when finding, counting, updating and removing documents from collections. A selector is a JSON object , the simplest of which is {} which matches all documents (null works too). If we want all departments in Karachi city, we could use {city:'Karachi'}.
Before delving too deeply into selectors, let's set up some data to play with. Let insert some data in Employees collection, remember although its not already exists but when you go to insert in that collection, MondoDB will create that collection in current database :
db.employees.insert({name: 'Amir Sohail', dob: new Date(1973,2,13,7,47), 
hobbies: ['cricket','reading'], city: 'Karachi', gender: 'm'});
db.employees.insert({name: 'Inzama-ul-Haq', dob: new Date(1977,2,13,7,47), 
hobbies: ['cricket','browsing'], city: 'Lahore', gender: 'm'});
db.employees.insert({name: 'Muhammad Yousuf', dob: new Date(1978, 0, 24, 13, 
0), hobbies: ['football','chatting'], city: 'Karachi', gender: 'm'});
db.employees.insert({name: 'Muhammad Younis', dob: new Date(1982, 0, 24, 13, 
0), hobbies: ['watching movies'], city: 'Peshawar', gender: 'm', 
department:'Human Resource'});
db.employees.insert({name: 'Shahid Afridi', dob: new Date(1983, 0, 24, 13, 0),
hobbies: ['basketball','chatting'], city: 'Karachi', gender: 'm', 
department:'Development'});
db.employees.insert({name: 'Moin Khan', dob: new Date(1978, 0, 24, 13, 0), 
hobbies: ['cricket','chatting', 'browsing'], city: 'Islamabad', gender: 'm'});
db.employees.insert({name: 'Afra Kareem', dob: new Date(1993, 0, 24, 13, 0), 
hobbies: ['reading','browsing'], city: 'Karachi', gender: 'f', 
department:'Development'});
db.employees.insert({name: 'Asma Khan', dob: new Date(1985, 0, 24, 13, 0), 
hobbies: ['reading','watching movies'], city: 'Lahore', gender: 'f', 
department:'Human Resource'});
db.employees.insert({name: 'Nazia Malik', dob: new Date(1984, 0, 24, 13, 0), 
hobbies: ['reading'], city: 'Karachi', gender: 'f', department:'Development'});
db.employees.insert({firstName: 'Waqar', lastName: 'Younis', 
dob: new Date(1978, 0, 24, 13, 0), hobbies: ['cricket','chatting', 
'basketball', 'browsing'], city: 'Karachi', gender: 'm'});
db.employees.insert({name: 'Waseem Akram', dob: new Date(1975, 0, 24, 13, 0), 
hobbies: ['cricket','chatting'], city: 'Rawalpindi', gender: 'm'});
db.employees.insert({name: 'Shoaib Akhtar', dob: new Date(1980, 0, 24, 13, 0),
hobbies: ['football'], city: 'Rawalpindi', gender: 'm'});
db.employees.insert({name: 'Muhammad Amir', dob: new Date(1978, 0, 24, 13, 0), 
hobbies: ['bowling'], city: 'Karachi', gender: 'm'});
db.employees.insert({name: 'Saeed Ajmal', dob: new Date(1983, 0, 24, 13, 0), 
hobbies: ['spin bowling'], city: 'Karachi', gender: 'm'});
db.employees.insert({name: 'Abdur Rehman', dob: new Date(1982, 0, 24, 13, 0), 
hobbies: ['bowling'], city: 'Lahore', gender: 'm'});
db.employees.insert({name: 'Muhammad Mushtaq', dob: new Date(1972, 0, 24, 
13, 0), hobbies: ['cricket','chatting'], city: 'Lahore', gender: 'm'});
db.employees.insert({firstName: 'Saqlain', lastName: 'Mushtaq', 
dob: new Date(1978, 0, 24, 13, 0), hobbies: ['football','chatting'], 
city: 'Karachi', gender: 'm', department:'Development'});
Now that we have data, we can master selectors. {field: value} is used to find any documents where field is equal to value. {field1: value1, field2: value2} is how we do an and statement. The special $lt, $lte, $gt, $gte and $ne are used for less than, less than or equal, greater than, greater than or equal and not equal operations. For example, to get all male employees that have city Karachi, we could do:
db.employees.find({gender: 'm', city: 'Karachi'})
The $exists operator is used for matching the presence or absence of a field, for example:
db.employees.find({firstName: {$exists: false}})
Should return a single document. If we want to OR rather than AND we use the $or operator and assign it to an array of values we want or'd:
db.employees.find({gender: 'f', $or: [{hobbies: 'reading'}, 
{hobbies: 'browsing'}, {city: 'Karachi'}]})
The above will return all female employees which either have hobbies reading or browsing or city is Karachi.
There's something pretty neat going on in our last example. You might have already noticed, but the loves field is an array. MongoDB supports arrays as first class objects. This is an incredibly handy feature. Once you start using it, you wonder how you ever lived without it. What's more interesting is how easy selecting based on an array value is: {hobbies: 'cricket'} will return any document where cricket is a value of hobbies. There are more available operators than what we've seen so far. The most flexible being $where which lets us supply JavaScript to execute on the server. These are all described in the Advanced Queries section of the MongoDB website. What we've covered so far though is the basics you'll need to get started. It's also what you'll end up using most of the time.
We've seen how these selectors can be used with the find command. They can also be
used with the remove command which we've briefly looked at, the count command, which we haven't looked at but you can probably figure out.
The ObjectId which MongoDB generated for our _id field can be selected like so:
db.employees.find({_id: ObjectId("TheObjectId")})
We have remove() command for deletion purpose. To delete all records simply you could call it on the required collection.
db.employees.remove()
Or alternatively you could place the desired query selectors to delete only the selective documents.

Points of Interest

We did get MongoDB up and running, looked briefly at the insert and remove commands. We also introduced find and saw what MongoDB selectors were all about. We've had a good start and laid a solid foundation for things to come. Believe it or not, you actually know most of what there is to know about MongoDB - it really is meant to be quick to learn and easy to use. Insert different documents, possibly in new collections, and get familiar with different selectors. Use find, count and remove. After a few tries on your own, things that might have seemed awkward at first will hopefully fall into place.
Hopefully I am planning to write another article to use MongoDB with C#.Net environment. I appreciate your feedback/comments or any improvements you want to suggest in this regard, to help in making the article much better and helpful for others.

January 2, 2012

What is the difference between Class and Structure?

Following are the differences between Class and Structure :
  • Structures are value types and classes are reference types. So structures are stored on stack and classes uses heap.
  • Garbage collector terminated objects created from classes. Structures are not destroyed using Garbage collector.
  • Structures do not require constructors while classes require. Usually classes have default parameter less constructors.
  • Since structures not allow inheritance, therefore structures members cannot be declared as protected.

What are similarities between Class and structure?

 Following are the similarities between classes and structures:

  •  Classes and structures both can have methods, properties, fields, constants, enumerations.
  •  Both can have parameterless constructors and parameterized constructors.
  •  Both can contains delegates and events.
  •  Both can implement interface.