Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

Weekly Poll Added to GridViewGuy

Yesterday, I added the weekly poll feature to GridViewGuy. This allows me to have a better understanding of what the users desire and want to see on the website. You can visit GridViewGuy.com and vote using the Weekly Polling Control on the right hand side of the screen. The result of the poll will be published on my blog next week.

Current poll question is:

What features would you prefer in GridViewGuy?

Podcasts

More Videos

Live Consultation (This means Meebo Widget Chat)

 

GridViewGuy.com

Sponsor

Posted Friday, October 19, 2007 9:49 AM by azamsharp | 0 Comments

SharpCacheSessionManager Updated With New Features!

I have just updated the SharpCacheSessionManager with few new features. Now, for Cache you can view the DateCreated and DateExpire of the item inside the Cache. You can also view the file dependencies of the cache item. Take a look at the screen shot below:

CacheSessionManager2

 

For my previous posting about SharpCacheSessionManager you can visit the following URL:

SharpCacheSessionManager

Download SharpCacheSessionManager
Sponsor

Posted Wednesday, October 17, 2007 12:59 PM by azamsharp | 0 Comments

SharpExport Button Control (GridView Export to Excel)

I know I have worked on this control before but I wanted to make it much better. So, here is the new Export Button Control. I have attached a new property to the control which is ExportCompleteGridViewWhilePaging. ExportCompleteGridViewWhilePaging property indicates whether you want to export the complete GridView or only the current page of the GridView control. For this feature to work you must set the GridViewDataSource of the ExportButton control to the collection that implements IListSource or IEnumerable interface.

SharpExport1.GridViewDataSource = ds;  // DataSet used here!

The SharpExportButton also replaces the LinkButtons, TextBoxes, DropDownLists and ListBoxes with their selected value. For LinkButtons, Buttons and TextBoxes the Text property is extracted. For DropDownList and ListBox the SelectedItem's Text property is extracted.

Page Level Settings:

You will also need to do some minor settings in your ASP.NET page. You must override the VerifyRenderingInServerForm method as shown below:

public override void VerifyRenderingInServerForm(Control control)

{

 

}

And you must disable event validation in the page directive.

EnableEventValidation="false"

I will try to find a way to work without having to disable event validation.

After that you can simply add the control to your toolbox. When needed simply drag and drop the control on the form, set some properties and you are good to go!

[Download SharpExportButton]

Sponsor

Posted Monday, October 15, 2007 11:57 PM by azamsharp | 2 Comments

Session.SessionId is Unique on Every Page Request If....

Session.SessionId is unique on every page request if you are not inserting anything in the Session object. This means that if you are not inserting any object into the Session you are not idenfied by the Session and will be considered a new user hence generating a new Session ID on each request.

Sponsor

Posted Friday, October 12, 2007 4:45 PM by azamsharp | 0 Comments

SharpCacheSessionManager

The SharpCacheSessionManager is a HttpHandler that allows to display the entries stored in the Cache, Session and Application object. You can view the data stored inside the objects and you can also remove the objects from the corresponding storage. You can download the SharpCacheSessionManager using the following link:

[Download SharpCacheSessionManager]

Sponsor

Posted Thursday, October 11, 2007 7:41 PM by azamsharp | 9 Comments

NCover to Cover Your A@#!

NCover is a code coverage tool that helps to point out how much code is covered under the unit tests. The idol code coverage is 100% which means all the method used in the domain layer are being covered in the test. Lets create a small sample to see NCover in action.

I have a simple Customer class as shown below:

public class Customer

{

private int _id;

private string _firstName;

private string _lastName;

 

public int Id

{

get { return _id; }

set { _id = value; }

}

public string FirstName

{

get { return _firstName; }

set { _firstName = value; }

}

public string LastName

{

get { return _lastName; }

set { _lastName = value; }

}

}

And the CustomerService class:

public class CustomerService

{

public const string connectionString = "Server=localhost;Database=School;Trusted_Connection=true";

public static void AddCustomer(Customer customer)

{

SqlConnection myConnection = new SqlConnection(connectionString);

SqlCommand myCommand = new SqlCommand("usp_InsertCustomer", myConnection);

myCommand.CommandType = CommandType.StoredProcedure;

myCommand.Parameters.AddWithValue("@FirstName", customer.FirstName);

myCommand.Parameters.AddWithValue("@LastName", customer.LastName);

myCommand.Parameters.Add("@ReturnValue", SqlDbType.Int, 4);

myCommand.Parameters["@ReturnValue"].Direction = ParameterDirection.ReturnValue;

myConnection.Open();

myCommand.ExecuteNonQuery();

myConnection.Close();

customer.Id = (int) myCommand.Parameters["@ReturnValue"].Value;

}

public static Customer GetCustomerById(int id)

{

Customer customer = null;

SqlConnection myConnection = new SqlConnection(connectionString);

SqlCommand myCommand = new SqlCommand("SELECT CustomerID, FirstName,LastName FROM Customers WHERE CustomerID = @Id", myConnection);

myCommand.Parameters.AddWithValue("@Id", id);

myConnection.Open();

SqlDataReader reader = myCommand.ExecuteReader();

while (reader.Read())

{

customer = new Customer();

customer.Id = (int) reader["CustomerID"];

customer.FirstName = (string)reader["FirstName"];

customer.LastName = (string)reader["LastName"];

}

reader.Close();

myConnection.Close();

return customer;

}

}

 

Finally here is the CustomerFixture class which includes a CanAddCustomer test.

[Test]

[RollBack]

public void CanAddCustomer()

{

Customer customer = new Customer();

customer.FirstName = "John";

customer.LastName = "Doe";

// Add a new customer

CustomerService.AddCustomer(customer);

Customer cVerify = CustomerService.GetCustomerById(customer.Id);

Assert.IsTrue(cVerify.Id != 0,"Id is not correct");

Assert.AreEqual(cVerify.FirstName, customer.FirstName);

Assert.AreEqual(cVerify.LastName, customer.LastName);

}

 

Now, if I run NCover on my application I get the 100% coverage since both of my methods in CustomerService as well as the properties of the Customer class are being used in the tests.

 

NCover100PercentCoverage

 

Off course, you can fool NCover by just including the methods in the test and not doing anything with the method. But, hey NCover did make you to include the methods. That is the first step in become Agile Developer.

Sponsor

Posted Wednesday, October 10, 2007 4:45 PM by azamsharp | 0 Comments

MbUnit is Freaking Awesome!

I just downloaded MbUnit for creating and running unit tests and all I can say is it is "Freaking Awesome!". I have not got into the details of this product but here are some of the very cool features.

1) RowTest and Row Attributes: Row attributes represents the input data you would like to send to the test method. You can have multiple Row attributes on a method which means you can run your unit test multiple times with different data. How cool is that? The RowTest attributes just tells the MbUnit that we are going to use Row attribute on the method or basically we are going to call the test method multiple times.

2) Rollback: This is a much needed feature for any unit testing tool. The Rollback attribute when set on the method will rollback any changes made to the database hence keeping your database clean from the testing data.

   [Row(2,2)]
        [Row(1,2)]
        [RowTest]
        public void CanCompare(int a, int b)
        {
            Assert.AreEqual(a, b);
        }

        [Test]
        [RollBack]
        public void CanAddCustomer()
        {
            Customer customer = new Customer();
            customer.FirstName = "John";
            customer.LastName = "Doe";

            CustomerService.AddCustomer(customer);
        }
 

Awesome!

Sponsor

Posted Wednesday, October 10, 2007 1:24 PM by azamsharp | 0 Comments

Display Please Wait While the Page Refreshes

A few days ago my colleague asked me how can he display "Please wait" message on the Button text while the page is loaded or processing the request. This can easily be achieved by using the ClientScript.GetPostBackEventReference method.

this.Btn_Upload.Attributes.Add("onclick", "this.value='Please wait..'; this.disabled=true;" + ClientScript.GetPostBackEventReference(this.Btn_Upload,""));

The GetPostBackEventReference injects the __doPostBack method and also the hidden fields that hold the event target and event arguments.

This is a useful technique when uploading large files and during the process disabling the button control.

Sponsor

Posted Sunday, October 07, 2007 12:11 AM by azamsharp | 2 Comments

Failed to Initialized Lazy Collection Resulting in NHibernate Exception

This is the error I am getting when I try to access a collection which is setup as lazy="true". I searched on the web for 2-3 hours but it seems like no one has found a solution. NHibernate forum members are as usual lazy = "true" and they don't really want to answer any questions or post any possible solution.

Here is my mapping file:

<bag name="Users" access="nosetter.camelcase-underscore" inverse="true" lazy="true" cascade="save-update" table="UserExams" >

<key column="ExamID" />

<many-to-many class="User" column="UserID" />

</bag>

And here is the line that throws the error:

Exam exam = ExamManager.GetById(55);

Console.WriteLine(exam.Users.Count);    <----------

I even tried to initialize the collection manually but no avail:

using (ISession session = sessionFactory.OpenSession())

{

exam = session.Get<Exam>(id);

NHibernateUtil.Initialize(exam.Users);

 

 

}

My message to NHibernate team is that if this is a freaking bug then tell the users that this is a BUG.

Sponsor

Posted Thursday, October 04, 2007 5:48 PM by azamsharp | 2 Comments

My Thoughts on NHibernate

I have been using NHibernate for about a month. During this one month I had some good times and some bad times using NHibernate. Here are some of my thoughts regarding NHibernate.

Pros:

1) You are free from writing stored procedures for every little fetch or CRUD operation. This saves a lot of code.

2)  NHibernate allows you to focus on the domain model of the application.

3) NHibernate allows you to write better tests which can be rollback using ITransaction interface.

Cons:

1) Very steep learning curve.

2) If you miss a small setting your application will fail as a whole.

3) Complex configuration settings .

4) Lack of support from the NHibernate community. I have posted various questions on the NHibernate forums unfortunately none of them were ever answered.

With DLINQ comming out in few months I see a dark future for NHibernate. All in all NHibernate is a great piece of software build by great developers.

Sponsor

Posted Thursday, October 04, 2007 12:24 PM by azamsharp | 5 Comments

Check If the JavaScript is Enabled on the Client's Browser

If our application is JavaScript intensive then it is always a good idea to check that if the client's machine has JavaScript enabled. When checking for JavaScript you might try some code like the following.

bool isJavaScriptEnabled = Request.Browser.JavaScript

The code above will only confirm that the browser is able to handle the JavaScript or not. This has nothing to do with whether the user has enabled or disabled the JavaScript or not. Actually, Request.Browser.JavaScript has been deprecated in ASP.NET 2.0. You can use the Request.Browser.EcmaScriptVersion.Major >= 1 to check whether the browser supports the JavaScript or not.

So, the question is how do we check if the user has JavaScript enabled?

We will use JavaScript to solve this problem. The part of the idea discussed here was proposed by Paul Weston (http://forums.asp.net/t/1164454.aspx). Create two divs just like shown below:

<div id="jsEnabled" style="visibility:hidden">

JavaScript is enabled

</div>

<div id="jsDisabled">

JavaScript is disabled

</div>

The first div contains the text "JavaScript is enabled" while the second one says "JavaScript is disabled". The first div is also made hidden. Now, we attach the checkJavaScriptValidity function to the onload event of the page.

<body onload="checkJavaScriptValidity()">

checkJavaScriptValidity hides the second div and make the first one active. If JavaScript is enabled you will see the first div which says "JavaScript is enabled". If JavaScript is disabled you will see the second div which says "JavaScript is disabled".

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

function checkJavaScriptValidity()

{

document.getElementById("jsEnabled").style.visibility = 'visible';

document.getElementById("jsDisabled").style.visibility = 'hidden';

}

</script>

 

Sponsor

Posted Sunday, September 30, 2007 6:07 PM by azamsharp | 0 Comments

Meebo Widget on GridViewGuy

I have just added the Meebo Widget on the GridViewGuy. This will allow me to interact with the visitors and answer any questions they have regarding GridView control or .NET in general. Hopefully, visitors and readers of GridViewGuy will find this feature beneficial and informative.

meeboongridviewguy

Sponsor

Posted Wednesday, September 26, 2007 6:51 PM by azamsharp | 0 Comments

AJAX and User Connectivity

I was working on a project that involved AJAX calls to the server method to update the database. The whole page was AJAX based and hence there were no postbacks. I found a very interesting problem in the application. The problem was caused by the user's disconnectivity from the internet. Since, AJAX did not caused any postbacks there was no way for the user to know that if he is still connected to the internet or not. Offcourse, there are solutions that revolve around accessing the database and if the access was not successful then throw an error. These solutions work but in our application we needed something to notify the user that if he is connected or disconnected from the internet.

I am using a polling mechanism to check for the client's internet connectivity. Every 5-6 seconds a call is made to the server side using AJAX which tries to download data from a dummy page. You can use an empty page with a single letter written in it. If the download is successful then the client is connected to the internet else he is not.

Here is the JavaScript code that is used to start polling.

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

startPolling();

function startPolling()

{

window.setInterval("CallServer('','')",5000);

}

function ReceiveServerData(response)

{

if(response == 'Connected')

{

document.getElementById("divStatus").style.display = 'block';

document.getElementById("divStatus").innerHTML = 'You are connected to the internet';

}

else if(response == 'Not Connected')

{

document.getElementById("divStatus").style.display = 'block';

document.getElementById("divStatus").innerHTML = 'You are not connected to the internet';

}

}

</script>

And here is the DownloadData method of the WebClient class.

public string GetCallbackResult()

{

if (CanDownloadData())

return "Connected";

else return "Not Connected";

}

private bool CanDownloadData()

{

WebClient client = new WebClient();

byte[] data = null;

try

{

data = client.DownloadData("http://www.google.com");

}

catch (Exception ex)

{

}

if (data != null && data.Length > 0) return true;

else return false;

}

 

internetconnected

 

 

Sponsor

Posted Wednesday, September 26, 2007 6:45 PM by azamsharp | 0 Comments

48 New Video Tutorials Added on GridViewGuy

This is a great news for users who enjoy watching video tutorials. I have just added 48 new video tutorials on GridViewGuy. These tutorials target different aspects of the .NET framework. Visit the link below to see the complete list.

GridViewGuy Video Tutorials

Enjoy!

Sponsor

Posted Saturday, September 22, 2007 5:26 PM by azamsharp | 1 Comments

Creating Multiple Choice Exam Application Part 1

I have just published a new article "Creating Multiple Choice Exam Application Part 1" on GridViewGuy. In this article I talked about the design of the domain layer, Unit Tests and NHibernate mapping for the application. You can view the article using the link below:

http://gridviewguy.com/ArticleDetails.aspx?articleID=303

Enjoy the article!

Sponsor

Posted Saturday, September 22, 2007 5:20 PM by azamsharp | 0 Comments