Raihan Iqbal
Life is codetastic!

How to add a tooltip to an ASP.NET DropdownList item

If you want to set a common tooltip for all the items in a DropDownList then you can just set the Title attribute for each item like so:

foreach(ListItem item in ddlScorecards.Items)
    item.Attributes.Add("Title", "YOUR TOOLTIP TEXT");

But if you want to set unique tooltips for each item then you have wrap the text value of the items in a DIV.

foreach(ListItem item in ddlScorecards.Items)
  item.Text = String.Format("<div title='{0}'>{1}</div>", "YOUR_TOOLTIP", item.Text);

Happy Programming!

Share

Posted in Uncategorized | 2,155 views | 1 Comment

Programmatically extract body of a web page

The technique used in this article can be used to display the contents of an HTML page inside your ASP.NET pages instead of using IFRAMES.

System.Net.WebRequest req = System.Net.WebRequest.Create(Request.QueryString["url"]);
System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
System.IO.Stream respStream = resp.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(respStream);
string responseFromServer = sr.ReadToEnd();
System.Text.RegularExpressions.Regex bodyRegex = new System.Text.RegularExpressions.Regex(@"(]*>[\u0000-\uFFFF]+?)");
System.Text.RegularExpressions.Match bodyMatch = bodyRegex.Match(responseFromServer);
Literal1.Text = bodyMatch.Result("$0");
sr.Close();
respStream.Close();
resp.Close();

Thanks to ClayCo at the ASP.NET Forums for his help. Here is the link to the original thread http://forums.asp.net/t/1023144.aspx

Share

Posted in .net, asp.net, c# | 1,839 views | No Comments

Perform Batch Inserts/Updates in SQL Server 2005 using XML

My current project requires me to download huge amounts of data from a remote server in the form of XML and save them to our local database. Lets see if we can do this using just one simple T-SQL stored procedure. Lets first create our table. For the purpose of this demonstration I will use a simple schema with the following signature

   1:  CREATE TABLE [dbo].[Employee](
   2:      [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
   3:      [Name] [nvarchar](50) NOT NULL,
   4:      [Gender] [varchar](1) NOT NULL,
   5:      [DateOfBirth] [datetime] NOT NULL,
   6:   CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
   7:  (
   8:      [EmployeeID] ASC
   9:  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  10:  ) ON [PRIMARY]

Next, we need to create the stored procedure that will do the batch insert for us.

CREATE PROCEDURE [dbo].[spr_Employee_ProcessXmlData](@employees xml)
AS
BEGIN
    DECLARE @TempTable TABLE
    (
        [Name] [nvarchar](50),
        [Gender] [varchar](1),
        [DateOfBirth] [datetime]
    );

    -- Populate the Temporary table from the XML
    INSERT INTO @TempTable (Name, Gender, DateOfBirth)
        SELECT
                ParamValues.Data.value('Name[1]','nvarchar(50)'),
                ParamValues.Data.value('Gender[1]','varchar(1)'),
                ParamValues.Data.value('DateOfBirth[1]','datetime')
        FROM
            @employees.nodes('NewDataSet/Employee') as ParamValues(Data);

    INSERT INTO Employee(Name, Gender, DateOfBirth)
        SELECT T.* FROM @TempTable T WHERE T.Name NOT IN (SELECT Name FROM Employee)
END

I won’t go into details about the XML programming – this great article are among several others that provide a good start for those unfamiliar with this feature of T-SQL. The stored procedure first creates a temporary in-memory table which will hold the data from the XML. Each node is read from the XML and mapped to the appropriate column of the temporary table. The temporary table is merely used to prevent duplicate data from being inserted into our actual table. If you are certain that your XML will never contain redundant data, then you can skip this step and directly insert the data to the Employee table.

We are now ready to perform batch inserts! The following SQL script demonstrates how.

EXEC    [dbo].[spr_Employee_ProcessXmlData]
        @employees = '<NewDataSet>
                        <Employee>
                            <Name>Raihan Iqbal</Name>
                            <Gender>M</Gender>
                            <DateOfBirth>11-05-1983</DateOfBirth>
                        </Employee>
                        <Employee>
                            <Name>John Doe</Name>
                            <Gender>M</Gender>
                            <DateOfBirth>10-05-1972</DateOfBirth>
                        </Employee>
                    </NewDataSet>'

It is needless to say that we can generate the XML and execute the stored procedure using any .NET language.

Happy programming!

Share

Posted in Development, T-SQL | 3,197 views | 1 Comment

Look Before You Leap – Episode 1

As-salamu-alaikum brothers/sisters

Many of us Alhamdulillah are muslims by birth and thus we "tend" to learn Islam through our peers. But before we do something under the tag of Islam we never ask ourselves the following questions:

  1. What????
  2. Did our prophet PBUH do it? Did any of the prophets do it?!?!
  3. If others are doing it? Why are they doing it?

I’ve decided that I’m going to discuss with my fellow Muslims about one such topic in each episode and I would appreciate if I get some feedback.

One such interesting practice is Arba’een (Arabic: اربعين‎, means "forty") or Chehlum or Chaliswa or Chollisha
I asked myself the above three questions and found the following:

What??
————–
Lets see what the Encyclopedia has to say. This is a quotation from Wikipedia:

Arba’een (Arabic: اربعين‎, means "forty"), or Chehlum, as it is known by Urdu-speaking Muslims, is a Shi’a Muslim religious observation that occurs 40 days after the Day of Ashura, the commemoration of the martyrdom of Husayn bin Ali, the grandson of the Prophet Muhammad which falls on the 20th day of the month of Safar.

To read more follow this link – http://en.wikipedia.org/wiki/Chehlum

Did our prophet PBUH do it? Did any of the prophets do it?!?!
—————————————————————————————–
I couldn’t find anything from Qur’an/Hadith that supports this and this is what the scholars have to say:
http://www.islamweb.net/ver2/Fatwa/ShowFatwa.php?Option=FatwaId&lang=E&Id=83604
http://www.islam-qa.com/en/ref/5871/40%20days

If others are doing it? Why are they doing it?
————————————————————

Culture, tradition, ignorance and the list goes on. What do you think? Please feel free to leave your comments and suggestions below. I hope we can create a platform where we can discuss such “ignored” yet serious topics. As Muslims we cannot afford to turn a blind eye to this otherwise we will be held accounted for. Once again don’t take everything in this post for granted. Do your own research, ask the scholars around you and when you finally find the truth, share it with us and your family members.

Allah knows best

Share

Posted in Islam | 884 views | No Comments

Generating Tree-like UI structures

In many of my projects I have had to generate non-binary trees using information from the database and then display them in a “tree-like” structure as shown below.

blog

My algorithm is very simple and it makes use of Dan Vanderboom’s excellent Generic Tree Collection but frankly I’m not satisfied with certain aspects of my algorithm. The main issue – the data can never be retrieved in the same order as shown above from the database.

Code

Now that we have a collection ready, we can generate the tree structure

Code

Finally, I add the items to my drop-down control by calling 

GenerateDropDownList(rootCategory, 0);

Let’s have a look at the function

blog4

I know I could have used LINQ but many of my projects are running in .NET 2.0 so I had to go old-school! I’m looking forward to your valuable comments as to how YOU would do this and why your solution is more efficient than mine.

Happy Programming!

kick it on DotNetKicks.com

Share

Posted in .net, c#, Development | 1,118 views | No Comments

The Controls collection cannot be modified because the control contains code blocks

I’m pretty much sure many of you have encountered this error if you have been using Code blocks inside your ASP.NET master pages for example,

   1:  <img src='<%= Page.ResolveUrl("~/image/top-mnu-agents.jpg") %>' alt="Agents" name="agents"
   2:                                                  width="109" height="42" border="0" id="agents" /></a>

Let’s say you want to use code blocks inside your JavaScript code, for example

   1:  function PreloadImages()
   2:  {
   3:         /*MM_preloadImages('<%= Page.ResolveUrl("~/image/top-mnu-property.jpg") %>',
   4:                           '<%= Page.ResolveUrl("~/image/top-mnu-agents.jpg") %>',
   5:                           '<%= Page.ResolveUrl("~/image/top-mnu-company.jpg") %>',
   6:                           '<%= Page.ResolveUrl("~/image/top-mnu-contact.jpg") %>');*/
   7:  }

Is this going to work? Make a guess! No, its not! Bump! Even though the code block is inside a comment block! How’s that! If you are curious why, ask the guys at Microsoft ;)

The workaround to this problem is Data Biding Expressions. Milan Negovan has discussed this in greater detail in this article.

Happy Programming!

Share

Posted in .net, asp.net, Development | 2,594 views | No Comments

Cheap Web Hosting

Looking for cheap web hosting?? Our cheap price and support make us the obvious choice for web masters.

You look good if your site is fast and always available. We been successfully focusing on Super Fast and Highly Reliable Hosting and the only Bangladeshi provider to offer not just a unique package of features but a philosophy for extracting the best value out of your Internet presence. With us you get the best in high availability hosting using the finest quality hardware and facilities, backing it up with a local personal and highly effective extended hours support service. These, together with performance-guarantees at a competitive price, make us the professional’s choice.

Hosting Features:

  • 99.9% Web Server Uptime guarantee
  • Extensive Data Backup
  • 24 x 7 x 365 Server Monitoring
  • Optional control panel for hands on access
  • Reliable email service
  • Quality visitor monitoring statistics
  • Good server response times
  • Secure servers for confidential transactions
  • Choice of web hosting with a Linux & Windows Server
  • Reliable 24 hour operation, 365 days a year
  • Flexible bandwidth to cope with your peak traffic
  • Sufficient storage space for your site files and databases

For further inquiries, please send us an email with your specs to sales@raihaniqbal.net

Share

Posted in Uncategorized | 691 views | No Comments

Resizing Images In ASP.NET

I’m sure there are plenty of similar topics out there but this is my two cents. Lets say you have the following code in your ASP.NET page:

    1 Upload a File: &nbsp;<asp:FileUpload ID="pictureUpload" runat="server" /><br />

    2 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnCommand="handle_ButtonClick" CommandName="Upload" />

Let’s look at the event handler code that uploads the image to the server and resizes it.

    1     protected void handle_ButtonClick(object sender, CommandEventArgs e)

    2     {

    3         if (e.CommandName == "Upload")

    4         {

    5             if (pictureUpload.HasFile)

    6             {

    7                 string FilePath = HttpContext.Current.Server.MapPath(PATH_FILESFOLDER) + pictureUpload.FileName;

    8                 pictureUpload.SaveAs(FilePath);

    9                 ResizeImageAndSave(FilePath, 90);

   10             }

   11         }

   12     }

   13 

   14     public void ResizeImageAndSave(string FilePath, int Width)

   15     {

   16         Bitmap loBMP = new Bitmap(FilePath);

   17         ImageFormat loFormat = loBMP.RawFormat;

   18 

   19         //*** If the image is smaller than a thumbnail just return it

   20         if (loBMP.Width < Width) return;

   21 

   22         decimal lnRatio = Convert.ToDecimal(Width) / loBMP.Width;

   23         int lnNewWidth = Width;

   24         int lnNewHeight = Convert.ToInt32(loBMP.Height * lnRatio);

   25 

   26         Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

   27         Graphics g = Graphics.FromImage(bmpOut);

   28         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

   29         g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);

   30         g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

   31 

   32         //Dispose old  BMP object

   33         loBMP.Dispose();

   34 

   35         bmpOut.Save(FilePath);

   36         bmpOut.Dispose();

   37     }

The code is pretty obvious – save the file to the specified path, resize the image, dispose the old image and finally save the new image.

Happy Programming!

Share

Posted in .net, asp.net, c#, Development | 611 views | No Comments

Simulate network delay

Sometimes developers need to simulate network delay during development and testing for various reasons. Sloppy is a tool that does just that. You will need the latest java runtime installed for it to work. Just go the link above and follow the instructions.

sshot-1

Share

Posted in Development, Tools | 893 views | No Comments

ASP.NET ImageButton not supported in Firefox 2.0

I recently discovered that the ImageButton and LinkButton ASP.NET controls do not function properly in Firefox 2.0. I wasted almost two days trying to figure out what was wrong with my code. Apparently, I was chasing a ghost! For more information on this problem can be found here. Unfortunately, the only workaround for this problem is to either upgrade to Firefox 3, which ROCKS by the way, or use a standard ASP.NET button and style it using CSS.

Share

Posted in Uncategorized | 1,756 views | No Comments