Posts RSS Comments RSS 137 Posts and 271 Comments till now

Archive for the 'Programming' Category

Sorting Words by Their Length

Don’t ask why I come up with this post :) Let’s just say it has something to do with Regular Expression.

 

The first method that immediately come up to mind (and usually the worst :) ) is as follows:

struct Res
{
   //To Record the Result
   public String words;
   public int wordcount;
}

public static Res WorstWordByLengthSort(string raw)
{
   Res myresult = new Res();
   myresult.wordcount = 0;
   string[] words = raw.Split("n".ToCharArray());
   raw = "";
   foreach (string word in words)
      raw += word + " ";

   words = raw.Split(" ".ToCharArray());
   ArrayList ar = new ArrayList();

   foreach (string word in words)
   {
      string tstr = word.Trim();
      if (tstr == "")
         continue;
      myresult.wordcount++;
      if (ar.Count == 0)
      {
         ar.Add(tstr);
      }
      else
      {
          int count = ar.Count;
          bool inserted = false;
          for (int i = 0; i < count; i++)
          {
              if (ar[i].ToString().Length <= tstr.Length)
              {
                  if (!ar.Contains(tstr))
                  {
                      ar.Insert(i, tstr);
                      inserted = true;
                   }
              }
          }
          if (!inserted && !ar.Contains(tstr))
             ar.Add(tstr);
      }
   }
   StringBuilder sb = new StringBuilder();
   foreach (object o in ar)
       sb.AppendLine(o.ToString());
    myresult.words= sb.ToString();
    return myresult;
}

 

It will work flawlessly (sort of .. :) ), but it will not allow duplication of word. After tinkering for a while, I came up with an idea to improve its performance. A better solution would be to use a dictionary where the length of the word becomes the key. If a key is already exist in the dictionary, we just simply append the word into the value of that particular key. The idea is implemented as follows:

struct Res
{
   //To Record the Result
   public String words;
   public int wordcount;
}

public static Res BetterWordByLengthSort(string raw)
{
   Res myresult = new Res();
   myresult.wordcount = 0;
   myresult.words = "";
   StringBuilder result = new StringBuilder();
   Dictionary myDict = new Dictionary();
   ArrayList keys = new ArrayList();
   string[] words = raw.Split(”n”.ToCharArray());

   raw = “”;
   foreach (string word in words)
   {
      string tword = word.Trim();
      raw += tword + ” “;
   }
   words = null;
   words = raw.Split(” “.ToCharArray());

   foreach (string word in words)
   {
      string tempWord = word.Trim();
      if (tempWord == “”)
         continue;
      int tlength = tempWord.Length;
      if (myDict.ContainsKey(tlength))
      {
         myDict[tlength] = myDict[tlength] + “n” + tempWord;
      }
      else
      {
          keys.Add(tlength);
          myDict.Add(tlength, tempWord);
      }
      myresult.wordcount++;
   }
   //Sort the keys ASC
   keys.Sort();
   for (int i=keys.Count-1; i>=0; i–)
   {
      result.AppendLine(myDict[(int)keys[i]]);
   }
   myresult.words = result.ToString();
   return myresult;
}

I created a GUI project to compare their performance. With same input of 1443 words, the Worst method took 734 ms, while the Better method took only 15 ms. And yes, if you remember your Big O complexity, the Better method is definitely much more efficient compared to the Worst method :)

SQL String Formatter (Part 1)

I am looking for a code (or command line software) that able to format/tidy-up SQL string to make it readable and doesn’t irritate the eyes. So far I have found:

  1. SQLinForm
    It’s quite handy, you can run it on your browser and download the offline version which is packaged into one single Java Jar file. Unfortunately, I’m looking for something with with command line or open source. At least with command line support I can invoke it from my .NET program to process the temporary file.
  2. SQL Online Formatter
    Still without the programmability support.
  3. SQL Review
    With command line support. Unfortunately It’s throwing error on one of my stored procedure, but it still gives you the output.
  4. Pl/Sql Tidy
    This program is only available in command line. Unfortunately, it never able to process my stored procedure. I not so sure whether it’s still maintained.
  5. Using Flex Script.
    This page is pure inspirational. It immediately opened up my eyes for the possibility of using Flex or Regular Expression. I think will stick to this solution.

Although I have made up my mind, I will provide the output of each program in the next posting. Hopefully once I am be able to port VS. Babu’s lex script (or make my own regular expression code), I will share it with you all.

Credits:

1. Carson McDonald

Apparently no Optimization is needed for DataTable.Select()

Almost losing sleep because of my colleague’s question, I posted the question in .NET Groups where I frequently hang out.

 

One contributor suggested me to use DataTable.Rows.Find(), especially when we are searching by the Index column of that DataTable. I never heard of this, so I keep it noted as an additional advise to my colleague.

 

After much thinking, I somehow became doubting that DataTable.Select() is the actual source of the bottleneck. So this morning I asked her to run the profiler to check the performance of her program. The profiler’s result proven my doubt. The bottleneck was caused by multiple calling of Web Services.

 

All this time I already have a little discomfort with Web Service. I thought the overhead of transmitting data by text XML is too much, especially when you have thousands of records transmitted at an instance. So I spent a little time to googling for opinions that against Web Service (Web Service here refers to those web services that commonly implemented using SOAP). Eventually, I stumbled to this page. I highly recommend it. It’s funny, it’s witty and you might want to use it as an argument when debating against SOAP proponents :)

 

Talking about Profiler, she is using ANTS Profiler. It’s not free :) But you could download the 14-days trial. And of course you can always ask Google for a help.

DataTable.Select Optimization

Today one colleague of mine asking me for tips on improving the DataTable.Select() performance. Apparently she has a data table which contains tens of thousands of records which some of the rows need to be processed together.

This particular question left me dumbfounded and baffled. The only thing that I can suggest were:

  1. Make sure when populating the data table from the database, the data are already sorted
  2. Make sure the filter parameter of the Select() method is selecting by integer data

Come to think of it, I don’t really know how actually the Select() method is done. Is it using Binary Search, Linear Search, Interpolation Seach or any other search method that I never come across with.

If the case is when the data was fetched from database already in order of an ID, let say CustomerID and the DataTable.Select() is using “CustomerID=1001″, is there any way to optimize this further?

I’ll get back to you when I found the answer. Or maybe you have the answer?

Printing The Content of GridView

Printing from a Web programmer perspective is a quite tricky task. Because what we really able to control is on the server side, while the printing is done on the client side.

Unless you create some sort of cool Java applet or custom COM control to help you interface with the printer, you will stuck with Javascript’s Window.print() function.

For those who are stuck without the cool Java applet or the super cool COM control, hopefully this article will help you.

Let’s assume you have the following GridView in your aspx page:


      

To make this GridView printable, you need to share the clientID to your Javascript printing function. You could either do it by:

  1. previewing the page, copy the ID of the table generated and put it into a variable inside Javascript
  2. Or, you can create a protected variable and put the classic ASP <%= VarName %> inside Javascript

Next, we need to create the print button and the Javascript code to handle the printing.

function Print()
{
	var grid_ID = gvCustomersGridView; //assuming that this is the generated ID
	var grid_obj = document.getElementById(grid_ID);
	if (grid_obj != null)
	{
		var new_window = window.open('print.html'); //print.html is just a dummy page with no content in it.
		new_window.document.write(grid_obj.outerHTML);
		new_window.print();
		new_window.close();
	}
}

You could also comment out the print() and close(), this way user will have a ‘print preview’ and has the chance to set margin, header/footer of the print out.

I hope you find it useful :)

Pages (8): « First ... « 1 2 3 [4] 5 6 7 » ... Last »

Close
E-mail It
Socialized through Gregarious 42