Sunday, December 28, 2008
Weird behaviour of "onchange" event of Listbox in FireFox
Suppose you have a form whose contents you would like to change based on the value selected in the listbox. For example, have different fields on the form based on whether the user is interested in Sports, Music, Dance etc. You can do this by capturing the item selected by the user in the onchange event and making the necessary changes by manipulating the DOM. However, you would have a problem with users using FireFox. To be able to capture the value every time the user makes a new selection, we need to add some javascript for the "onkeyup" event. The code needed is,
<select id="items" onchange='itemSelected();' onkeyup="this.blur();this.focus();">
</select>
All that needs to be done is to momentarily remove focus from the listbox so that the onchange event is called and then, set the focus again. Setting the focus again on the listbox is needed because, if we don't do that, the user will have the set the focus explicitly on the listbox every time he changes it's value with the keyboard - he wouldn't appreciate this if he wants to select a value which is 4-5 values further in the list from where he's currently at.
I spent nearly 2 hours trying to figure out why the onchange event wasn't getting called in FireFox. Hope this post will go some way in helping you reduce the debugging time in case you happen to come across a similar situation.
Sunday, December 7, 2008
Calling Web Services from Javascript
- Server side
On the server side, we will create a normal ASMX web service.
- Right click your project in Visual Studio and click "Add new item". In the dialog that opens up, select "Web service" and give it an appropriate name
- Once the web service has been added, open it's .cs file. At the very top, before the class declaration there will be the following commented attribute
- Add the methods you want to call from the client side and annotate them with the [WebMethod] attribute
- Test the web service and ensure that the web methods are working fine
[System.Web.Script.Services.ScriptService]
Uncomment this attribute.
- Client side
On the client side, we will need to do the following to be able to call the web service created in the above steps
- Add a ScriptManager tag at the top of your page. The script manager is required on every page that should provide AJAX functionality. It instantiates the PageRequestManager class and handles the downloading of all the necessary script and service proxy files. (If you are using master pages and the ScriptManager is present in the master page, you can add a ScriptManagerProxy tag to the current page)
- Within the ScriptManager tag, add a ServiceReference and provide the path to the web service. It should look something like this,
- Once this is done, we can call a web method from JavaScript as follows :
- The final step is to code the success and failure callbacks, syntax for which is as follows :
<asp:servicereference path="~/Sample.asmx">
</services>
</asp:scriptmanager>
Here, I am adding a reference to a web service named "Sample.asmx" which is present in the same project. What happens under the hood is that, for each service that you reference with the ServiceReference tag, a proxy is created and downloaded on the client side and this proxy is used to validate the calls from JavaScript to the web service.
WebServiceClass.WebMethod(parameters, Success Callback function, Failure callback function, context);
parameters : We can specify as many as needed, or even 0, parameters to be passed to the web method, each separated from the other by comma
Success Callback function : We specify name of the JavaScript function that will be called when the web method completes execution
Failure Callback function : We specify name of the JavaScript function which will be called in case the web method encountered some error during execution
context : This is an optional string value that we can provide. It is used in case we are using the same JavaScript function as callback for multiple web methods so that in the JavaScript function, we can determine the web method call for which the callback was invoked.
function SuccessCallback(response, context, method)
function FailureCallback(error, context, method)
Here,
response : It contains the values returned by the web method. It can be as simple as an integer or a string or as complex as JSON representation of List
error : Object representing the error that occurred in the web method. The most useful method of this object is get_message() which returns a description of the error that occurred
context : Optional value, which will have the same value as provided as the last parameter when calling the web method
method : Name of the web method from which the current JavaScript function has been invoked
Having the ability to call web services asynchronously from the client provides tremendous flexibility as well as performance advantages to the programmers and allows us to create really powerful and performant sites with ease.
Ignoring certain characters from user input in HTML Textbox
As it turns out, this is really easy to do with some simple JavaScript. We can accomplish this with the following steps :
- Identify the characters that need to be ignored (Black listing approach)
- Add an event handler for the key down event on the text box
- In the event handler, check whether the input character is one of the characters that needs to be ignored. For these characters, just return false from the event handler. This will prevent that particular character from reflecting in the text box
- Optionally, one can show an error message if one of the unwanted characters is input. This is done to avoid the user from getting confused when his inputs don't cause any changes in the contents of the text box
Here is the code for declaring text field in HTML :
<input id="'startDate'" type="'text'">
We can add the event handler in the HTML tag itself or in a Javascript function which will be called on the "onload" event of the body as follows :
document.getElementById('startDate').onkeydown = CheckNumber;
Here, we are using the "Key Down" event of the text box to check for the character input by the user. Finally, the event handler function code is as follows :
function CheckNumber(e)
{
....try
....{
........if (!e)
........{
............e = window.event;
........}
........var keynum;
........try
........{
............//IE : Get the code of the key the user pressed
............keynum = e.keyCode;
........}
........catch (err)
........{
............//Netscape/Firefox/Opera : Get the code of the key the user pressed
............keynum = e.which;
........}
/*Prevent any character not in the range 0-9 and not '/', backspace, delete or left and right arrow keys, Tab and Shift+Tab. ASCII Code : / is 191, Backspace is 8,Delete is 46, Left : 37, Right :39, Tab : 9, Shift + Tab: 16*/
........if (keynum != 191 && (keynum <> 57) && keynum != 8 && keynum != 46 && keynum != 37 && keynum != 39 && keynum != 9 && keynum != 16)
........{
............//Show error to the user to inform him that the input was invalid
............document.getElementById("dateErrorMessage").style.display = "inline";
............//Return false to prevent the character from being added to textbox
............return false;
........}
........else
........{
............//Remove error message if it's visible
............document.getElementById("dateErrorMessage").style.display = "none";
........}
....}
....catch (ex)
....{
........alert("Check number : " + ex.message);
....}
}
As can be seen from the comments, we first retrieve the ASCII code for the character typed by the user (as expected, we have 2 different ways of getting the value based on the browser type) . Then we check against the characters we will allow (I am using white listing here, one can use blacklisting also, as mentioned earlier. The right approach will depend on the number of conditions that need to be specified but generally white listing is preferred for 2 reasons. It will cause fewer problems in case you miss out on some conditions and this mistake will be easier to catch during testing. If the character doesn't fall within our white list, we show an error message on a label and then return false to prevent it from appearing in the text box. Otherwise, we do nothing so that the character appears normally in the text box.
So there you have it, a texbox that accepts restricted inputs. Customise for the type of inputs you want to allow/disallow.
Sunday, November 9, 2008
Presentation Tips
According to me, one should always try to give the presentation from his/her own laptop/desktop. This case comes into the picture when you have a long presentation which will be taken by multiple speakers in parts. The reason giving presentations on another machine can be problematic is that you don't know the locations of most files and folders, how some things work/don't work on that machine, quirks thrown up by that machine on certain user actions etc. It wouldn't be a good experience to look flummoxed in front of your audiences when you can't find a particular window or folder :-)
So, in my opinion, using your own machine is one more stepping stone towards having a successful, smooth presentation
Tuesday, October 28, 2008
Importance of sending Status Reports
I generally send out the report on Friday evenings so that the manager has an idea of what happened during the week, before that week ends. One can also send the report on Monday mornings but then, that would, theoretically at least, mean you are communicating to your manager a tad late. Status reports that I send out contain 3 main sections :
- Activities completed this week : What were the things you worked on and managed to complete this week (do not include items that you are still working on and haven't completed, those will go into the next section)
- Actions items for next week : What things are you planning to work on and/or complete in the following week
- Blocking issues : This is the most important section that you should send out to your manager. Communicate clearly issues that restrict your progress and follow up on them to get them sorted out asap
Given these sections, one can either send out a simple list of activities for each section or have multiple columns under the first 2 sections to be more elaborate. The columns that I include under the first 2 sections are :
- Activity : The activity that you completed/are going to complete in the following week
- Effort : An indication of the effort needed for completing an activity (if that activity falls under the first section) or an estimate of the effort that will be required(for activities that are part of the second section)
- Main challenges/points : Highlight the main technical issues that had to be /will need to be addressed/solved to complete the stated activity
The big question in your mind would be, why should I waste somewhere around half an hour every week in sending this to my manager, who might not even give it anything more than a cursory glance. Well, here are some of the reasons why that half an hour will be a time well invested :
- When you sit to jot down the activities, it helps you to get an idea of how much work has been done and allows you to get an understanding of how efficient you are being at what you are doing. You will be able to catch early signs when there is a need for you to pull up your socks and work harder.
- Jotting down the action items for the coming week streamlines your work and thinking
- Highlighting the blocking items gives you a better chance of getting it resolved sooner so that you can get back on track with your work
- If you organise your status reports in a separate folder (like I do using Outlook rules), you can just take a look at the status reports to get an idea of what all work you did during any given time period. This will prove priceless when you sit down at the year end to fill up your performance review.
- Finally, and probably most importantly, it's your chance to show off your efficiency and abilities to your manager. Thanks to this post for highlighting this point
I agree that some of these advantages are already inherent in software development methodologies like Scrum, but there are plenty of other reasons, as can be seen from the list above, for you to use regular status reports. Feel free to add more advantages or some of the best practices you follow when it comes to status reports. Also, share your views if and why you think that sending status reports is a waste of time.
Sunday, October 5, 2008
Dataset v/s DataReader
The Dataset is a "disconnected" data store. What this means is that the DataSet object need not maintain a connection with the database at all times, a connection is needed only at the time of fetching data and updating it. The DataSet can be populated with data using something like this ,
SqlConnection conn=new SqlConnection();
conn.ConnectionString="Data Source=.;Database=TempDB;Integrated Security=true;";
SqlDataAdapter da=new SqlDataAdapter("select * from Temp",conn);
DataSet ds=new DataSet();
da.Fill(ds);
conn.Close();
//Process data in the DataSet ds
As can be seen from the above snippet, once the data has been read into the DataSet, the connection can be closed immediately. The data can still be accessed from within the DataSet.
DataReader, on the other hand, is a "connected" data store which means that there needs to be a connection maintained to the database in order to be able to access the values in the DataReader. The DataReader can be populated with data using something like this ,
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.;Database=TempDB;Integrated Security=true;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from Temp";
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Process the data read from the DB
}
conn.Close();
Notice here that the connection is closed only after iterating through the entire record set returned by the query.
As can be seen from above, a DataSet, although providing a lot of flexibility in terms of usage scenarios, is memory intensive. Since it is a disconnected data store, it stores all the data read from the database in memory. As can be inferred, this can really slow down the application if the DataSet is populated with millions of rows of data. On the other hand, the DataSet provides "random" access : any record stored in it can be directly accessed and records can be accessed in any order desired. One can also go back and forth through the DataSet records. Another important flexibility with DataSets is that data within it can be modified and the updates will be percolated to the database automatically. Thus, a DataSet is suitable for scenarios in which data update is needed or where random access is needed but should be used cautiously when huge data is being fetched from the database.
As for the DataReader, it is almost an opposite of the DataSet. Since it maintains an open connection to the database at all times, it needn't store data in local memory. Instead records are read in chunks on a need basis. Thus, it proves to be pretty efficient in terms of memory usage. However, this efficiency comes at a cost : records within a DataReader can be traversed only forward and that too, only once. If a record needs to be read a second time, the query needs to be executed again as there is no provision to move backwards through the DataReader. Also the data read through the DataReader is read only. Thus, a DataReader lends itself to scenarios where huge amounts of data are being read without having the need to update them or have random access over that data.
Accessing return value of SPs
ADO.NET has the SqlCommand and SqlConnection objects to allow the user to invoke the SP and have access to the results returned by the SP. Specifically, there are 3 methods that can be used to execute a query or an SP on the database :
- SqlCommand.ExecuteNonQuery() : Used for queries which don't return any value, i.e. insert, update and delete queries
- SqlCommand.ExecuteScalar() : Used for queries which are guaranteed to return a single value
- SqlCommand.ExecuteReader() : Used for queries that return multi column and/or multi row result sets
There is 1 important difference in the use of these 3 methods when it comes to accessing return values. It turns out that when using ExecuteScalar() and ExecuteNonQuery(), we can access the return value immediately following this method call whereas, for the ExecuteReader() method this is not the case. If we try to access the value of the parameter object created for the return value, it will have a null value. The return value is set only after we iterate through the entire result set returned by the reader object. The reasoning behind this behaviour can be as follows. If the result set was returned successfully, it means the SP succeeded so there's no point of checking the return value. It only makes sense to check the return value in case there was no result returned. The return value will then enable us to determine whether there was actually no data in the database for the given query or there is a bug which caused incorrect results to be returned.
Do keep this slight variation in the behaviour of the ExecuteReader() the next time you use it.