Select All CheckBoxes in GridView Using JQuery


Selecting checkboxes inside the GridView control is a very common operation and that is why I have several articles and videos dedicated to this subject.

Selecting CheckBoxes Inside GridView With a Twist

VIDEO: Selecting CheckBoxes Inside GridView

Recently, I was playing around with JQuery library and thought of implementing the same scenario using the library. Here is the code used to perform the SelectAll and DeSelectAll function.

<script language="javascript" type="text/javascript">

$(document).ready(function()
{
    $("#chkAll").click(function()
    {
        // I don't like this line!    
        this.checked = !(this.checked == true);
   
        $("#gvCategories input:checkbox").attr("checked",function()
        {
            this.checked = !(this.checked == true);
        });
       
    });
});
</script>

Yup! that's all the code you need to perform this operation. If you think you can even refactor this out then please post your refactorings at Selecting CheckBoxes Inside the Table.

author: Mohammad Azam | posted @ Saturday, May 10, 2008 10:52 AM | Feedback (0)

Two New Features to www.RefactorCode.com


I just added few more features to www.RefactorCode.com. These features include the following:

1) My Refactorings Page: The "My Refactorings" page simply displays the posts that the user has made and the posts that user has participated in.

2) Categories Menu Updated. The Categories menu have been updated and now it displays the number of posts in the particular category.

 

There are many different features that I am currently working on which includes rating the refactored code, option to follow the thread using email etc.

Come on let's refactor!

author: Mohammad Azam | posted @ Friday, May 09, 2008 3:33 PM | Feedback (0)

ASP.NET MVC Framework Videos on ASPALLIANCE


ASP.NET MVC is going pretty HOT these days so I thought I should post some links to the ASP.NET MVC Videos which are hosted on www.AspAlliance.com.

Video: Introduction to the ASP.NET MVC Framework

Video: ASP.NET MVC Framework Unit Testing

Video: Passing Parameters Across Pages Using ASP.NET MVC Framework

Video: Url Rewriting Using ASP.NET MVC Framework

Video: Introduction to the MVC Toolkit

Video: Using JavaScript with the ASP.NET MVC Framework

Video: Implementing Controller Action Authentication in the ASP.NET MVC Framework

Video: Caching ASP.NET MVC Controller Actions

Video: Authenticating Controller Actions Using Custom Role Filter

Video: Compressing HttpResponse Using ASP.NET MVC Framework

All the videos are totally FREE the only thing you need to do is to set up an account on AspAlliance and that's it. There are more than 90 videos hosted on AspAlliance covering different aspects of the .NET technology.

Enjoy!

author: Mohammad Azam | posted @ Thursday, May 08, 2008 5:17 AM | Feedback (0)

UrlRewrite Using RewritePath Article Published


I have just published an article on www.gridviewguy.com. The article explores the workings of URL Rewriting mechanism using RewritePath. You can check out the article using the link below:

Url Rewriting Using RewritePath

author: Mohammad Azam | posted @ Tuesday, May 06, 2008 2:36 PM | Feedback (1)

UrlRewriting Pains and Fixes!!!


When developing www.RefactorCode.com I was advised to create friendly URLS so that search engines like Google, Yahoo, Live Search etc would be able to index it. Ben Sheirman suggested that I should try out IRouteHandler interface which was originally part of the ASP.NET MVC Framework. I implemented the URL-Rewriting solution which worked on my local machine but failed on the production. The web host guys told me that currently they don't support ASP.NET 3.5 Extensions Preview (I don't think that was the problem.)

My next solution involved using the RewritePath method of ASP.NET. For that I created a small class called "Route" which will hold the new routes.

 public class Route
    {
        private string _key;
        private string _url;

        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }

        public string Url
        {
            get { return _url; }
            set { _url = value; }
        }
    }

The routes are setup in the Application_Start event in the Global.asax file.

public class Global : System.Web.HttpApplication
    {
        private static List<Route> routes = null;

        protected void Application_Start(object sender, EventArgs e)
        {
            // initialize the routes
            routes = new List<Route>()
            { new Route() { Key = "Categories", Url = "~/ProductsByCategory.aspx?id=" },
                 new Route() { Key = "Refactorings", Url = "~/SubmissionDetails.aspx?id=" }
            };
        }

    public static List<Route> GetRoutes()
        {
            return routes;
        }

In the above code I am setting up two routes one for the Categories key and the other for the Refactorings key. The HttpModule "UrlRewrite" is used to forward the route to the correct address.

public class UrlRewrite : IHttpModule
    {      

        public void Dispose()
        {
                  
        }

        public void Init(HttpApplication httpApplication)
        {
            // attach the begin request!
            httpApplication.BeginRequest += new EventHandler(httpApplication_BeginRequest);        
        }

        void httpApplication_BeginRequest(object sender, EventArgs e)
        {
            RegisterRoutes();
        }

      
        // Register the routes!       
        private static void RegisterRoutes()
        {
            HttpContext context = HttpContext.Current;
            string oldPath = context.Request.Url.ToString();

            var newRoute = (from route in Global.GetRoutes()
                            where oldPath.IndexOf(route.Key) > -1
                            select route).SingleOrDefault();

            if (newRoute == null) return;

            int i = oldPath.IndexOf(newRoute.Key);
          
                if (i > -1)
                {
                    int underScoreIndex = oldPath.IndexOf("_");
                    int startIndex = (i + newRoute.Key.Length + 1);
                    int numberOfCharacters = underScoreIndex - startIndex;

                    int id = Int32.Parse(oldPath.Substring(startIndex, numberOfCharacters));
                    context.RewritePath(newRoute.Url + id, false);
                }                                 
        }       
    }

Now, I need to display list of items with a custom URL. Here is the implementation of the CreateFriendlyUrlsForCategories method which is used to create custom URLS:

 public static string CreateFriendlyUrlsForCategories(int id, string title)
        {
            return String.Format("Categories/{0}_{1}", id, title.Replace(" ","_"));
        }

This will generate the following URL:

This is much cleaner than http://localhost:1688/ProductsByCategory?id=10. This will work fine on your local machine but as soon as you deploy it to the production it will result in a "404 Page Not Found" error. After much research and hair pulling I concluded that IIS6 is not capable of handling URLS with no file extensions (Please correct me if my assumption is wrong). So, to fix this problem I made a small change in my CreateFriendlyUrlsForCategories method.

 public static string CreateFriendlyUrlsForCategories(int id, string title)
        {
            return String.Format("Categories/{0}_{1}.aspx", id, title.Replace(" ","_"));
        }

Now, the requests for the pages will succeed and they will be routed correctly. I am pretty sure that you can also use the IRouteHandler for UrlRewriting with this change it will work correctly. Now the URLS will be generated like this:

One other thing that you must be careful with is using the ResolveUrl method when creating friendly URLs. Check out the code below:

<asp:Repeater ID="repCategories" runat="server">

<ItemTemplate>

<div>

<asp:HyperLink ID="hlCategoryName" NavigateUrl='<%# ResolveUrl(UrlRewritingDemo.Helpers.SiteHelper.CreateFriendlyUrlsForCategories((int)Eval("id"),(string)Eval("CategoryName"))) %>'
 runat="server" Text='<%# Eval("CategoryName") %>' />

</div>

</ItemTemplate>

</asp:Repeater>

The ResolveUrl will make sure that the URL you are referring is correct even though you are inside sub directories.

I will write an article on this topic and publish a link to that article on this post.

author: Mohammad Azam | posted @ Tuesday, May 06, 2008 5:01 AM | Feedback (0)

RefactorCode Released!!! ..... BETA :)


For the past couple of days I have been working on a new website called www.RefactorCode.com. The purpose of the website is that user's can submit their code and other users can help to improve the existing code hence, refactoring the code. Below you can read the "About" section of the RefactorCode website.

Refactoring is a technique to change the existing ugly code and make it beautiful without changing the workings of the code.
In short, making the code suck less!

Our website RefactorCode is developed to help developers refactor the code, therefore improving programming skills and overcome many challenges one faces when coding. You can submit your ugly code and other developers can find ways to improve it.

Presenting to you, your very own refractor code station!

The website is currently in BETA version but you will still be able to post your code and get refactorings. I would like to thank Steven Smith for his help in coming up with a nice logo and Ben Scheirman for his help and contributions.

 

author: Mohammad Azam | posted @ Saturday, May 03, 2008 9:40 AM | Feedback (0)

Silverlight BETA 1 Installation Messed Up!!!!!!


It seems like the installation part of this product is totally messed up. Take a look at the image below in which the left window is running a game created in Silverlight BETA 1 and the right window is displaying the message saying "Install Silverlight". The installation part of the Silverlight is completely messed up!!!!!

author: Mohammad Azam | posted @ Tuesday, April 29, 2008 8:54 AM | Feedback (0)

PODCAST: Introduction to the ASP.NET MVC Framework


I just published a new podcast on www.gridviewguy.com. In the podcast I talk about the new ASP.NET MVC Framework. You can download the podcast using the link below:

Introduction to the ASP.NET MVC Framework

author: Mohammad Azam | posted @ Monday, April 28, 2008 3:27 PM | Feedback (0)

Creating Bar Chart Using .NET Graphics API => Article Published


I just published an article on www.gridviewguy.com. The article demonstrates how to create simple bar charts using the graphics API provided by the .NET API. You can check out the article using the following link:

Creating Bar Charts Using .NET Graphics API

author: Mohammad Azam | posted @ Sunday, April 27, 2008 3:13 PM | Feedback (1)

Understanding Mock Objects


Mock object is basically a mirage of the real object as they posses the same qualities by don't do anything. Mock objects really shines when working with some entity that continuously changes like time, temperature, air speed etc. In this post I will introduce mock objects and how can they be useful when unit testing such entities.

I took the idea from a great article published on AspAlliance. The article "Beginning to Mock Using Rhino Mocks and MbUnit" is written by Ben Hall. The idea is that we are testing that your method returns the correct image. The correctness of the image depends on the time of the day. So, if it is day time then "sun.jpg" is returned and if it is night time then "moon.jpg" is returned. Let's first see the implementation without using the Mock objects.

 [Test]
        public void should_return_sun_image_when_it_is_day_time()
        {
            string imageName = ImageOfTheDayService.GetImage(DateTime.Now);
            Assert.AreEqual(imageName, "sun.jpg");
        }

The above method is used to test for the image during the day time. Let's check out the implementation of the ImageOfTheDayService.GetImage method.

  public static string GetImage(DateTime dt)
        {
            int hour = dt.Hour;

            if (hour > 6 && hour < 21) return "sun.jpg";

            return "moon.jpg";      
        }

The problem is that you can only test the day time result during the day and the night time result during night. This is inconvenient. You can hack the implementation of your tests and force the day time and night time to happen. Check out the implementation below:

 [Test]
        public void should_return_sun_image_when_it_is_day_time()
        {
            DateTime dt = DateTime.Parse("02/02/02 5:00 AM");           

            int hour = dt.Hour;                      

            int lessHour = 0;

            if (hour < 6)
                lessHour = 15 - hour;

            if (hour > 21)
                lessHour = 15 - hour;

            string imageName = ImageOfTheDayService.GetImage(dt.AddHours(lessHour));
            Assert.AreEqual(imageName, "sun.jpg");
        }

        [Test]
        public void should_return_night_image_when_it_is_night_time()
        {
            int hour = DateTime.Now.Hour;
            int lessHour = 0;

            if (hour < 21)
            {
                lessHour = 21 - hour;
            }

            string imageName = ImageOfTheDayService.GetImage(DateTime.Now.AddHours(lessHour));
            Assert.AreEqual(imageName, "moon.jpg");
        }

In the should_return_sun_image_when_it_is_day_time test I am using 5:00 AM as the start time. The problem is that 5:00 AM is still night (according to the demo application). In order to a successful test I need to provide the day time. So, I do some funky stuff and crank the time to 3:00 PM which is the time during the day. Now, I test my GetImage method using the new fake time.

The funky hack makes the test pass but leaves behind ugliness in the test methods. Now, let's introduce the Mock objects to clear out this mess. I am using Moq framework to create my mock objects but you can use any framework you like. First, I need to create an interface for the DateTime which I can feed to the Moq framework to return me a mocked object.

 public interface IDateTime
    {
        int GetHour();
    }

Now, the GetImage method of the ImageOfTheDayService will take the IDateTime as the parameter instead of the DateTime.

 public static string GetImage(IDateTime mock)
        {
            int hour = mock.GetHour();

            if (hour > 6 && hour < 21) return "sun.jpg";

            return "moon.jpg";           
        }

Now, let's check out the test using mock objects.

 [Test]
        public void MOCKING_should_return_sun_image_when_it_is_day_time()
        {           
            var mock = new Mock<IDateTime>();                      
            mock.Expect(e => e.GetHour()).Returns(15); // 3:00 PM

            Assert.AreEqual("sun.jpg", ImageOfTheDayService.GetImage(mock.Object));
        }

        [Test]
        public void MOCKING_should_return_night_image_when_it_is_night_time()
        {
            var mock = new Mock<IDateTime>();
            mock.Expect(e => e.GetHour()).Returns(21); // 9:00 PM

            Assert.AreEqual("moon.jpg", ImageOfTheDayService.GetImage(mock.Object));
        }

The test becomes much simpler now. All we are saying is that we expect a call on the "GetHour()" method of the IDateTime interface. The method will return "15" (day test). We are not concerned about what is the current time of the day since we are putting expectations and results. Finally, we pass the IDateTime to the GetImage method and compares the output with our expected results.

author: Mohammad Azam | posted @ Sunday, April 27, 2008 11:08 AM | Feedback (10)