Saturday, May 5, 2012

Check/UnCheck all checkboxes in a div through JQuery

This is very common functionality in any application where we have to give user the option to select or deselect all checkboxes.
So here is the code to do it in a very simple and easy way, I have put all the checkboxes in dvMain div and loop through each checkbox with JQuery each loop and then check or uncheck that paricular checkbox accordingly.

CODE

<head runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 
   <script type="text/javascript" language="javascript">

        function CheckAll() {
            $('#dvMain :checkbox').each(function () {     //loop all checkbox in dvMain div
                $(this).attr('checked', true);                    //This will check the current checkbox
            });
        }

        function UnCheckAll() {
            $('#dvMain :checkbox').each(function () {     //loop all checkbox in dvMain div
                $(this).attr('checked', false);                   //This will uncheck the current checkbox
            });
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="dvMain">

        <a href="javascript:" onclick="CheckAll()">Check All</a>
        <a href="javascript:" onclick="UnCheckAll()">Un Check All</a>
        <br />
        <asp:CheckBox ID="CheckBox0" runat="server" Text="BlackBerry" /><br />
        <asp:CheckBox ID="CheckBox1" runat="server" Text="iPhone" /><br />
        <asp:CheckBox ID="CheckBox2" runat="server" Text="Android" /><br />
        <asp:CheckBox ID="CheckBox3" runat="server" Text="Windows Phone" /><br />
        <asp:CheckBox ID="CheckBox4" runat="server" Text="Mego" /><br /><br />

        </div>
    </form>
</body>

I have used jquery-1.4.1 but other versions can also be used.

Thursday, May 3, 2012

Fetch Asp.Net Listbox control selected items without looping

Many people wants to retrieve Asp.net Listbox controls selected item values without looping through the whole items collection.
So here is the solution for it basically you can either use LINQ or Lambda Expressions to select the selected items from the control.

Aspx Code

<asp:ListBox ID="lstBox" runat="server"  SelectionMode="Multiple">
    <asp:ListItem Text="WindowsPhone" Value="WindowsPhone"></asp:ListItem>
    <asp:ListItem Text="Android" Value="Android"></asp:ListItem>
    <asp:ListItem Text="iPhone" Value="iPhone"></asp:ListItem>
    <asp:ListItem Text="BlackBerry" Value="BlackBerry"></asp:ListItem>
</asp:ListBox>
<br />
<asp:Button ID="btnRetrieve" runat="server" Text="Get" onclick="btnRetrieve_Click" />

Aspx.cs Code

First we will use LINQ method to retrieve selected items of lstBox control

protected void btnRetrieve_Click(object sender, EventArgs e)
{
        var selecteditems = from li in lstBox.Items.Cast<ListItem>()
                                      where li.Selected == true
                                       select li;      
}

Secondly now we will retrieve selected items of lstBox control through Lambda expression

protected void btnRetrieve_Click(object sender, EventArgs e)
{
       var selecteditems = lstBox.Items.Cast<ListItem>().Where(ee => ee.Selected == true);     
}

Tuesday, August 23, 2011

Lookup function in SQL Server 2008 Reporting Services


These days I'm exploring SQL Server 2008 R2 Reporting Services and one thing where i stuck is to combine two dataset fields in one table. After some research i found a very nice way of doing it using Lookup Function. Lookup function is a new feature in SQL Server 2008 R2 Reporting Services.

Syntax
=Lookup(Fields!CustomerId.Value,Fields!CustomerId.Value,Fields!TotalOrders.Value,"DataSetB")

Parameters Description
Parameter 1: Field of first dataset to be matched as criteria
Parameter 2: Field of second dataset to be matched as criteria
Parameter 3: Field to show in that column where parameter1 and parameter2 matches.
Parameter 4: Name of dataset from where you want to select new field

Example
Ill try to explain it by an example. We have two datasets having customer data, DatasetA have customer personal details and DatasetB have TotalOrders that customer have. Here is the schema of our Datasets.


















In my Report DataSetA is what the default table showing customer details and now i just want a new column in my report for TotalOrders for every customer. If i try to drag TotalOrders column in this table it would not let me do. To do so now ill add a new column in that table then right click on that field i have just added and select expression. Write a new expression like this

=Lookup(Fields!CustomerId.Value,Fields!CustomerId.Value,Fields!TotalOrders.Value,"DataSetB")

and click ok. It will show TotalOrders for every customer that matches CustomerId column in both Datasets. The resultant Dataset will look like this




Friday, July 29, 2011

Routing in Asp.Net 4

Routing basically is a way of making simple SEO (Search Engine Optimization) friendly easy to remember URLs, with routing your request is not mapped to physical files like www.mysite.com/About.aspx.
Routing is not new in Asp.Net 4 its first introduced in Asp.Net 3.5 SP1.

Why we need routing
Problem 1.
If you see a URL like
www.mysite.com/Product/ProductCategory.aspx?category=134324
when next time you want to access this page you will definitely open some other random category.

Problem 2.
If your URL is
www.mysite.com/Product/ProductCategory.aspx?category=134324
by watching this i knew this page is in some Product folder having ProductCategory.aspx page which hacker love to know.

Problem 3.
If your page is now move to some other hierarchy or its renamed and user request that some page he will not find that page.

How to solve these issues
Problem 1.
If you see a URL like
www.mysite.com/Category/laptops
you will definitely remember and will find it next time you try to visit it. This solves our Problem 1.

Problem 2.
If you see a URL like
www.mysite.com/Category/laptops
Nobody knows what is the physical hierarchy by watching this URL. This solves our Problem 2.


Problem 3.
If you see a URL like
www.mysite.com/Category/laptops
Because it is not mapped to a physical page, moving or changing its name doesn't affect the user. This solves our Problem 3.

Demo

1. We start from File -- New Project then choose Asp.Net Web Application and select .Net Framework 4 and click Ok.

2. Define Route setting in Global.asax file.

a. First we have to add a System.Web.Routing namespace, which provide all the classes used in URL routing

b. Make a method for RegisterRoutes that accepts a RouteCollection parameter and define route for our request. RouteTable.Routes.MapPageRoute function have 5 overloaded methods, we are using the first and the basic one which accepts three paramters.


private void RegisterRoutes(RouteCollection collection)
{            
RouteTable.Routes.MapPageRoute("ProductRoute",  //Name of route
"Product/{Name}",                                                   //How request map the url ex Product/laptops
"~/Product.aspx");                                                   //Physical page that handles these requests
}


c. Call RegisterRoutes in Application_Start event and pass RouteTable.Routes as object in it. RouteTable.Routes get a collection of objects that derive from the System.Web.Routing.RouteBase class.

void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}


Global.asax work complete.


3. On Default.aspx page make a link to redirect to Product page.
<a href="/Product/All">Show all Products</a>

4. Add a new Product page on the root, In Product page we will print the product categories name in a label as a heading and some text description. 
Just for showing demo i have made 3 hyperlinks of product categories and after selecting them we will display its name in heading and some text description for it.

<asp:HyperLink ID="Hyplaptops" runat="server" NavigateUrl='<%$RouteUrl:Name=Laptops %>' Text="Laptops"></asp:HyperLink><br />
<asp:HyperLink ID="HypMobile" runat="server" NavigateUrl='<%$RouteUrl:Name=Mobile %>' Text="Mobile"></asp:HyperLink><br />
<asp:HyperLink ID="HypTablets" runat="server" NavigateUrl='<%$RouteUrl:Name=Tablets %>' Text="Tablets"></asp:HyperLink><br />
<asp:Label ID="lblProductTitle" runat="server" Font-Size="X-Large"><%: RouteData.Values["Name"] %></asp:Label><br />
<asp:Label ID="ProductInfo" runat="server" ></asp:Label>


In code behind of Product page, set the label text according to route conditions


if (RouteData.Values["Name"].ToString().Equals("All"))
            {
                ProductInfo.Text = "Show All Products";
            }
            else if (RouteData.Values["Name"].ToString().Equals("Laptops"))
            {
                ProductInfo.Text = "Show All Laptops";
            }
            else if (RouteData.Values["Name"].ToString().Equals("Mobile"))
            {
                ProductInfo.Text = "Show All MobilePhones";
            }
            else
            {
                ProductInfo.Text = "Show All Tablets";
            }


In just four easy steps we configure routing in Asp.Net 4. 
Now run Default.aspx page and click Show All Products hyperlink and you can see the clean URL showing Product/All means show all Product categories. 
Now click on Laptops hyperlink and URL will change to Product/Laptops.


Wednesday, June 8, 2011

Dell Streak 5 launched in Pakistan

On 4th of June, I attended a Dell-Mobilink-Google event in which Dell Streak 5 launched in Pakistan with Price tag of Rs. 49,999. So i thought to write a short overview of the device.

Dell Streak 5 is one of the pocket friendly tablet having GSM network capabilities.

Features

Andriod Version
Android Froyo 2.2

Display
5 inch Gorilla Glass display having WVGA resolution 480 * 800

Dimension & Size
Dimension are 153 x 79 x 10 mm
Size is 220g

Camera
5 mega pixel auto focus rear camera with dual-LED flash and VGA front facing camera
HD video recording

Video Formats
H.263 / H.264, .3GP, MPEG4, WMV

Audio Formats
MP3, WMA, AAC, AAC+, eAAC+, AMR, Midi, WAV

Memory
MicroSD card slot with 16GB pre-installed

Battery
Li-Ion 1530 mAh battery

Other 
Wifi
GPS
Proximity sensor for auto turn-off
Multi-touch input method
Ambient Light Sensor
Accelerometer
Capacitive sensor keys

Official Pictures




Missing Features
Couple of things which i really wish this device should have
DivX or Xvid support
FM Radio

Last words
Dell Streak 5 is really a great tablet for Pakistani market as not many tablets are available here in this price range with capabilities like Dell Streak5 have. 

* Pictures taken from gsmarena.com

Saturday, May 14, 2011

Samsung Wave S8500 Review

After 5 months of using Samsung S8500 wave phone i thought about writing a review on it. Ill try to cover as many points as i could but this phone has lots of great features which may not be used by me yet.

Whats in the box
Samsung wave Phone
1500 mAh battery
Stereo headset with 3.5mm jack
2GB micro SD card
Micro USB to USB cable
Starndard microUSB charger
User Guides
Software CD

Features I Like
Super AMOLED Display
HD video recording and Playback
Great 5 megaPixel camera with flash
Great Sound quality
Playing Games
TV Out
Take picture and share it on Facebook, Flickr, MySpace etc

Features I Dont Like
Navigation software
10MB Limit on PDF file
Not many apps as compare to Android

Photos
Few pictures taken from this phone



Video
Video quality really impress me because it captures video in HD resolution 720p. Below video captured outside heathrow airport, London.



Last Words
Samsung S8500 is the first phone to run Samsung newly created Operation System called Bada. But this phone is very stable and responsive. Having all the features in this price tag is remarkable.

Sunday, March 13, 2011

Understand and Implement jQuery getJSON

getJSON function is used to get JSON data from server using an AJAX HTTP GET request.
What is JSON, JSON is JavaScript Object Notation which is an open standard designed for data interchange. JSON is a collection of key value pairs.

Syntax

$.getJSON(url, data, success(data, status, xhr)) { 
//code to be executed when request succeeds
});


Description of Parameters
ParameterParameter TypeDescription
url Mandatory Requested url to call. It can be an api or url or a javascript file
data Optional Data to send with request. Its a key value pair
success(data, status, xhr) Optional Code to run if request succeeds.
data value that return with the request
success contains a string containing request status that can be success, notmodified, error, timeout or parsererror
xhr have XMLHttpRequest object

Implementation

I will show you two examples of getJSON function first one will call Flickr api and second will be used in ASP.NET MVC

1. Using getJSON get Flickr images
Below example will get 5 images from Flickr using getJSON function and append them in a div having id divid also it sends two parameters with the request one is tags and other one is format.
jQuery Code
$(document).ready(function () {
 $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?  jsoncallback=?",
 {
 tags: "cat",format: "json"},
 function (data) {
  $.each(data.items, function (i, item) {
  $("<img/>").attr("src", item.media.m).appendTo("#divid");
  if (i == 4) return false;
  });
 });
});



2. Using getJSON in ASP.Net MVC
Because i use getJSON in Asp.net MVC ill show you how to implement in it using C#.
jQuery Code
$(document).ready(function () {
 $.getJSON("/Json/GetJson", { }, function (data) {
  $.each(data, function (key, value) {
   $("#content").append(key + ": " + value + "<br/>");
   });

  });
 });
});


Controller Code
public JsonResult GetJson()
{
 Dictionary objDic = new Dictionary();
 objDic.Add("First Name", "Fraz");
 objDic.Add("Last Name", "Sundal");
 objDic.Add("Job Description", "Web Engineer");
 return Json(objDic, JsonRequestBehavior.AllowGet);
}


It calls a controller action name GetJson and resultant is a key value pair having keys First Name, Job Description and Last Name which is then embedded in to a div named content. When returning Json in controller you have to specify JsonRequestBehavior.AllowGet otherwise it will display an error which says This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
To watch getJSON request process you can use Firefox popular add-on Firebug. It takes 1.09 sec and Status code is 200.

Firebug Screen Shot