Thursday, October 29, 2009

Two dimensional Array (Table Array) Multiple column sorting using JavaScript

Here is a JavaScript implementation for multi-column ascending sort on a table array.

Below is the code for this.
var tempArray = new Array();
//main function
function do2DArraySort(arrayToBeSorted, sortColumnArray)
{
if (arrayToBeSorted == "undefined" || arrayToBeSorted == "null") return arrayToBeSorted;
if (arrayToBeSorted.length == 0) return arrayToBeSorted;
if (sortColumnArray.length == 0) return arrayToBeSorted;
tempArray = arrayToBeSorted; 
var totalLength = sortColumnArray.length; 
for(var m = 0; m < totalLength; m++)
{
if (m == 0)
{   
doBubbleSort(tempArray, tempArray.length, sortColumnArray[m]);         
}
else
{     
doMultipleSort(tempArray, sortColumnArray[m], sortColumnArray[m-1]);
}
} 
return tempArray;
}

//basic bubble sort implementation
function doBubbleSort(arrayName, length, element) 
{
for (var i = 0; i < (length-1); i++)
{
for (var j = i+1; j < length; j++)            
{
if (arrayName[j][element] < arrayName[i][element]) 
{
var dummy = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = dummy;
}
}
}  
}

//appends an array content to the original array
function addToArray(originalArray, addArray)
{
if (addArray.length != 0)
{
var curLength = 0;
curLength = originalArray.length;
var maxLength = 0;
maxLength = curLength + addArray.length;  
var itrerateArray = 0;
for (var r = curLength; r < maxLength; r++)
{   
originalArray[r] = addArray[itrerateArray];
itrerateArray++;
}
}
}

//check if a value exists in a single dimensional array
function checkIfExists(arrayToSearch, valueToSearch)
{
if (arrayToSearch == "undefined" || arrayToSearch == "null") return false;
if (arrayToSearch.length == 0) return false;
for (var k = 0; k < arrayToSearch.length; k++)
{
if (arrayToSearch[k] == valueToSearch)
return true;
}
return false;
}

//sorts an 2D array based on the distinct values of the previous column
function doMultipleSort(sortedArray, currentCol, prevCol)
{
var resultArray = new Array(); 
var newdistinctValuesArray = new Array();
//finding distinct previous column values 
for (var n = 0; n < sortedArray.length; n++)
{ 
if (checkIfExists(newdistinctValuesArray, sortedArray[n][prevCol]) == false)
newdistinctValuesArray.push(sortedArray[n][prevCol]);
}  
var recCursor = 0;
var newTempArray = new Array(); var toStoreArray = 0; 
//for each of the distinct values
for (var pp = 0; pp < newdistinctValuesArray.length; pp++)
{
toStoreArray = 0;
newTempArray = new Array();  
//find the rows with the same previous column value
for (var qq = recCursor; qq < sortedArray.length; qq++)
{
if (sortedArray[qq][prevCol] != newdistinctValuesArray[pp]) break;
newTempArray[toStoreArray] = sortedArray[qq];
toStoreArray++; recCursor++;
}
//sort the row based on the current column   
doBubbleSort(newTempArray, newTempArray.length, currentCol);
//append it to the result array
addToArray(resultArray, newTempArray);
}
tempArray = resultArray;
}
The above code can be stored as TableArrayMultipleSort.js for our example usage shown below:
<html>
<head>
<title>Invoking Multiple Array Sort</title>
<script language="javascript" src="TableArrayMultipleSort.js" type="text/javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function createSampleArray()
{ 
var myArr = new Array( 
new Array("Ashley","13","Male","Texas"),
new Array("Smith", "32", "Male","Colorado"),
new Array("Jane", "21", "Female","South Carolina"),
new Array("Anna", "12", "Female","Maryland"),
new Array("Ashley","13","Male","Delaware"),
new Array("Ashley","46","Male","Newyork")
); 
return myArr;
}
function showDataByRow(arrayToBeShown)
{
for(var a=0;a<arrayToBeShown.length;a++)
{
document.write(arrayToBeShown[a]+"<br>");
}
}
document.write("<b>Original Array: (Input)</b>" + "<br><br>");
showDataByRow(createSampleArray());
document.write("<br><br><br>");
var sortColumnArray = new Array('0','1','3'); 

document.write("<b>Sorted Array: (Output)</b><br>Order: First column, then by second column and then by Last Column" + "<br><br>");
showDataByRow(do2DArraySort(createSampleArray(),sortColumnArray));
</script>
</body>
</html>
When the above code is executed, this will show the input table array and output table array as shown below. Original Array: (Input)
Ashley,13,Male,Texas
Smith,32,Male,Colorado
Jane,21,Female,South Carolina
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,46,Male,Newyork
Sorted Array: (Output) Order: First column, then by second column and then by Last Column
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,13,Male,Texas
Ashley,46,Male,Newyork
Jane,21,Female,South Carolina
Smith,32,Male,Colorado
Enhancements: 1. The code can be enhanced to accomodate sort order for each of the sort columns by having a seperate array to specify that.
2. It can be relooked for performance improvements and enhanced variable handling.
3. There are few issues related to null/empty-value, if it exists in any of the columns being sorted.


Note: The objective of this article is to assist in learning the Javascript array concepts and it's usage. This code is not intended to be used for production purposes as it is not written with that aspect in mind. So, if you want to use it, use it at your own risk.

Sunday, October 25, 2009

Large Grasshopper

This big one was just sitting there having all the food that he can; finished a major portion of the plant's leaves. It's pretty colorful and is around 9.5 cm long.

If someone, who study these, is looking for a nice snap of this one, here it is. Please comment on the scientific name so that others can find this.



















































Wednesday, October 21, 2009

Threading in .net - for Beginners


Method 1: Using ThreadPool.QueueUserWorkItem

There may be scenarios, in which you want to have an asynchronous operation to be performed without the need of a handle on the function being called. For example, this can be an audit log or a process log operation which can be a background process while your main application performs the important operations. There is a simple single line code to achieve this using ThreadPool.QueueUserWorkItem call. Typical usage is as follows.


private void button1_Click(object sender, EventArgs e)
{
string argument = "Process started";
ThreadPool.QueueUserWorkItem(new WaitCallback(WriteLog), input);
}

private void WriteLog(object o)
{
string argument = o as string;
// Your code to log the argument
}

In this method:
1. With a single line code, you are getting the basic benefits of threading without having to worry about creating, managing and terminating a threaded operation.
2. QueueUserWorkItem call is in control of .net runtime. You will not be able to control the time at which it gets executed.
3. You cannot control the state and priority of the function being executed.

Method 2. Using ThreadStart, ParameterizedThreadStart and Thread

Below is another method that will give more control on your asynchronous operation.

a) Without having a Parameter

Class level decleration


private Thread t = null;


This can be used for later tracking of the thread being executed.

private void button2_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(WriteStartLog);
t = new Thread(ts);
t.IsBackground = true;
t.Priority = ThreadPriority.Normal;
t.Start();
}

private void WriteStartLog()
{
// Your code to log the process start
}


To track the thread, the thread object can be used. A sample usage is provided below:

private void button3_Click(object sender, EventArgs e)
{
if (t != null)
{
if (t.IsAlive)
t.Abort();
}
}


b) Passing parameters using ParameterizedThreadStart

When parameters are to be passed to the invoked method, this can be done using ParameterizedThreadStart using the medium as objects.



private void button2_Click(object sender, EventArgs e)
{
ParameterizedThreadStart pts = new ParameterizedThreadStart(WriteLog);
t = new Thread(pts);
t.IsBackground = true;
t.Priority = ThreadPriority.Normal;
t.Start("Process started");
}


private void WriteLog(object o)
{
string argument = o as string;
// Your code to log the argument
}

Now that we have covered the basic skeleton of our article, let’s see the other important aspects of threading.

Handling ThreadAbortException

There might be a need to abort the thread being executed at any instant of time. This can happen due to the user cancellation of the process or any other action like the primary thread being closed due to a various reason. At these scenarios (even when there is no need), it is mandatory to have a ThreadAbortException to be handled in the method which is being called. This can be as follows:



private void WriteLog()
{
try
{
// Your code to log the argument
}
catch (ThreadAbortException tae)
{
//handles the thread abort exception
//code to cleanup - let know the user that thread got cancelled, if necessary.
}
catch (Exception e)
{
//handle other exceptions
}
}


Communicating between main and background thread.

Consider, this scenario:
You are having a background thread to create thumbnails for pictures in a folder. For each thumbnail being created, you have to draw it on the form. That is, to communicate from the background thread to the parent thread with the output from the background thread. This is pretty simple using delegates. Here it is how it’s done.

Class level declarations:


private delegate void addPictureBox2Main_Delegate(PictureBox pbb);
private Thread t = null;



private void button2_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(LoadImageThumbNails);
t = new Thread(ts);
t.IsBackground = true;
t.Priority = ThreadPriority.Normal;
t.Start();
}

private void LoadImageThumbNails()
{
try
{
//for each of the thumbnails being created
//generate picturebox with thumbnail here
PictureBox pb = //function to load thumbnail
this.Invoke(new addPictureBox2Main_Delegate(addPictureBox2Main), new Object[] { pb });
}
catch (ThreadAbortException tae)
{
//handles the thread abort exception
//code to cleanup - let know the user that thread got cancelled, if necessary.
}
catch (Exception e)
{
//hanlde other exceptions
}
}


private void addPictureBox2Main(PictureBox pb)
{
//add the picture box pb to the parent control as needed
}


** Code samples are in C#**

Note: This article only covers the basic aspect of threading and it aims to help beginners understand the threading concepts. There is more to it. So, keep learning.

Saturday, March 7, 2009

Clocks showing United States (US) timings and a Meeting planner for a specific date

I've been seeing my sales and implementation colleagues in India looking at different sites to found out the current time at various US time zones. There is always confusions when daylight saving settings comes in to the picture. To help this situation, here is a page that will show a nice little map from worldatalas.com along with their current timings. These timings are pulled from worldtimeserver.com.

Here is the link:
http://sanalks.com/clocks.htm

There is also a meeting planner link at the bottom which can be used to determine the time for a time zone at a particular date. This is especially useful for scheduling meetings.

Sunday, April 6, 2008

When Windows developers became Web developers

Recently, most of the small businesses are migrating towards web development due to multiple reasons. The magnitude and the impact of the reasons behind this climate shift is not our topic of discussion here. What we are after is the effect of this changes in the development and planning area, when a significant number of small business started concentrating on web and shifted resources from windows developers towards web development.


One impact was that the developers, who were working on the windows applications, were now suddenly moved towards web. The similarities in the development environment provided by .Net acted like a catalyst for this move. Some companies even started to work collaboratively with other firms to get their products on to web, assuming that it's just the same thing as windows development. So, everybody jumped in started the ride. Well, the journey didn't turned out quite smooth as expected. What follows below is the reasons behind them and what has been told to windows developers a multitude of times which they seldom shows interest at. Hopefully, this will act as a reference for those in a similar move.

Sessions to the rescue...
Even though the client-server architecture has been here for years, for those in windows domains too, this was not exactly similar when it came to web. The inherent and important part of a code, user data, preserved in VARIABLES before,  now no longer gets retained per user throughtout the application (or in different pages). So, most of them tried to limit the variable usage within the pages. But in some places, where the concurrent data was needed, Sessions came to the rescue. Let's store whatever that was needed in there! that was the concept. Everything worked fine, until it was found that multiple tabs in the client browser will destroy/replace session variables and render them unusable. Session is unique per user/browser, not by each tab.

The whole concept of connection-less architecture started looking awfully bad and the need to store necessary information on the client browser and to use them properly throughout the application is now a big problem. But, the solution is simple. The whole application flow should be designed in such a way that the concurrent user data should be a part of the client page. There are multiple ways to do this like view state, JSON serialized data in page variables . Some might still argue that database storage is reliable when user splays with significant amount of temporary data, but is it scalable? NO!

One other important aspect is that, in web, especially over cloud environments, every page/function has to be less dependend on server sessions  as much as possible. This is a key factor that allows scalability and performance.

Let's place a button on the center. How hard that can be!
Consider this simple scenario. There is a button on the center of the screen. Clicking on it should show a welcome message. How fast we can get it done in a windows app? 1 minute? or may be 5 minutes, for some. Now, let's consider the developer from above, who just came into web, trying to do the same. The styles, scripts and the HTML codes to get it done is definitely going to take more time. When multiple browser support is also taken into consideration, this guy will go mad! As a professional web guy would know that it can be done at the same time in the approach is in the right way. However, the concern here is that the path choose by most windows developers took significant amount of time that it should and it's just because of the lack of understanding on how the whole HTML rendering and page layout works. The underlying problem is not about knowing how to center an element, but about how the web page layout and rendering is different that of windows applications.

The point here is that these guys are going to take some time to understand CSS, HTML and scripting concepts to get the task done and more importantly, it is going to take much more time to know what to be done, where!

Where is the ComboBox?
The good old Combobox, where the user can select any of the listed items OR type in a new item, is gone. Why it is difficult to be provided in Web? The web, along with ASP.net, which is said to be advanced, can't accommodate a simple control like this? Weird!

So, here is the deal. it's not about the capability what the server side technologies can provide now. It's about the capabilities that your browser has. Your browser and Server are two independent detached pieces of your application that works (or at least expected to) based on some standards. Your web server technology (Ex: ASP.net) just tries to work as a mediator that tries to make things easy for you. Look at this page, if you want to know more about this. The point is that the one-to-one user-app behaviors that you were seeing in windows app until now, does not exists anymore.

Invalid input?? Show a validation message!
Just show a message box just like we had before, for an invalid input by user. Do it! The developers tried all those ridiculous ways to make this happen. There were even implementations that does the validation in the server and come back after post back popping an alert box with the validation message.

Guys, this is not the way to do this. it has to be selectively decided what has to be done at the client at what has to be done at the server. As mentioned above, the browser and the server are detached but closely related two pieces of the puzzle. Client validations has to be done by client scripting and server will still have to validate using asp.net validation, if the client has disabled JavaScript. Again, you have to know that what has to be done, where.

Hidden control coding? That is non-standard.
In windows development, there was always a belief that "if you know how to write good code, you won't need hidden controls". It was always considered as something unethical and non-professional. If someone used a hidden control to preserver state or a variable value during code review, he would be treated as non-oops programmer.

In the web world, the whole concept is upside down. Almost every page, especially built using ASP.net, will have at least few hidden controls. They are the core part of "how ASP.net works". They are lightweight and is being heavily used to preserve state and values during a page life cycle.

It is working fine in IE, not in Firefox:
Until now, what you developed worked exactly in the client machines. You might've faced some DLL (assembly)  related problems here and there. Now, all of a sudden, you're stuck with something unique. Your output and client scripting functionality varies per browser and even within browsers for different versions.

Well, there is no quick solution for this. The web is working towards a solution and better standards and being adopted on all browsers. Until then, what you can do is to make sure that
1) Provide a doctype so that the dissimilarities are narrowed down.
2) Make sure that the methods that you use in JavaScript are checked for browser compatibility. Just because you learned about a method, doesn't mean that it is supported on all browsers. The same applies for CSS (style sheets). Typical examples are border and opacity related styles.

Why i need to worry about HTML controls?
Most of these developers started using ASP.net and started making beautiful web applications. But, when the customization needs came up, ASP.net was not good enough. They had to touch the controls and change visual properties manually. Wait a minute, i'm not seeing those same controls in the browser to change the styles as i need. They are different. Hm...

This is where basics come in to play. ASP.net is just the middle man. It works between the standard HTML controls and your server controls to make the job easier for you. Even though it does the job really well, it's not good enough when you need deeper customization. So, take a step back and learn about the standard HTML controls. You will not regret it.

OK, now the data i need is in the query string, but why the random failures?
What you are struck with, is again, an important aspect of the web. When the data contains unacceptable characters, you will see these kinds of problems. Note that they are just not limited to query strings.

The key aspect here is that once you in the web world, you have to always remember that you are dealing different entities at each locations: the database, the server and the browser. You will have to make sure that the data when flows from one place to another is compatible with the recipient. For example, if you pass any HTML data to JavasScript, you will have to HTML encode it. In a similar way, when you pass values in a query string, you will have to URL encode it. In JavsScript, you will be dealing with escape and unescape calls to deal with these concerns. It would be also nice if you can take some time learning about the most common methods of data communications between client browser and the server through HTTP protocol, GET and POST. Explaining about these are not really under the scope of this topic. Anyway, you now know what you were doing wrong!

Enough with these design time controls. Let us have some dynamic controls!
Hey, ASP.net rocks! I can just create controls dynamically at any event and add it to any parent control. It is easily working! Wait... I'm not getting the values as i desire. What's wrong?

You have controls that ASP.net does not knows about. That's what's wrong. When you create a control in design mode, ASP.net knows that there is a control under this parent and it also knows the control state information when ASP.net delivered that page to one of those million users who is accessing you page. But, once you created your own control dynamically, ASP.net does not have the information anymore at the right moment, to tie the state information to that control. There is where, you will have to know the importance of page life cycle. You will have to create these controls before ASP.net tries to attach the state information to them. Here are more information about these events and their effects.

Let the processes run.
Now, saving a form with few data were fine. Let us have a time consuming processes like Excel import or even database creation scripts or even data display from a table with large number of records, just like it happened in windows applications with threads. Most of the web implementation is this case, rendered in a timeout. There were little thought process on the concepts that
a) the web page is a single app that servers for multiple users
b) one of those users is not going to wait for 10 minutes to see my page.

Any process that is going to significant amount of time has to be moved in to separate threads, probably using windows services. You can even consider MSMQ. Whatever you choose, in-page processing is not an option to be considered. The pages can always check for the status in AJAX mode and show the status to the users at regular intervals, when the windows service updates them in the databases. if data display or processing is needed make sure that you do it in chunks.

Update Panel is AJAX!
During interviews, this was the most common misconception that these developers carried around. Without trying to know what is this beautiful concept named AJAX, most of them believed that the update panel from Microsoft is AJAX. It's not! Actually Update Panel is just mimicking asynchronous behavior and it is not efficient as using RAW AJAX. if you cannot write it by your own, use jQuery AJAX instead of an Update panel.

My web app was running until yesterday, now it's not.
Until now, whatever that you created for client went to their premises and most of them were genuine. Now, whatever you make goes to public. There are peoples with bad teeth and fingers waiting for your output. They will eat you as soon as you make it online. Just kidding. But, the story is not totally wrong. There are hackers that will take your website down, just for fun. They will use it in the ways you didn't prepared for and trust me, they will get to your application at some point. So, learn about SQL injection, need for captcha, password encryption, cross site scripting etc and implement counter measures. These small changes can make a big difference in your up time guarantees, data security and on the reputation of the web application.

Conclusion
There are lot of differences, between windows and web, to talk about. Starting from the development phase, the marketing, analytic, deployment are significantly different when compared to a windows development cycle for a web development. This article aims to guide those car manufacturers who thinks that we can create and plane or even a ship, just because they are both made of metal. They are different and working for web is both challenging and interesting, once you get a hang of it. Enjoy!