Monday, December 1, 2008

Launch an external application

Dim MyProcess As New System.Diagnostics.Process  
   MyProcess.StartInfo.CreateNoWindow = True  
   MyProcess.StartInfo.UseShellExecute = True  
   MyProcess.StartInfo.WorkingDirectory = "C:\MyDirectory"  
   MyProcess.StartInfo.FileName = "MyApplication.exe"  
   MyProcess.StartInfo.Arguments = "MyArgument"  
   MyProcess.Start()

ASP.NET: Redirect the page when the session ends

Here's a simple method, without using javascript, to redirect the user to a certain page once their session ends:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Response.AppendHeader("Refresh", (Session.Timeout * 60) + 5 & "; Url=SessionEnded.aspx")
End If
End Sub

Friday, October 17, 2008

Regex match html content without screwing up the tags

When needing to highlight words in a string containing HTML we found we soon ran into problems when the word we were searching for appeared in the middle of a tag..

Imagine the example: 


If I wanted to bold all occurances of geekzilla, I'd usually do this:

unfortunately, when dealing with HTML rather than just text, this will screw my tag and produce the following



We did a lot of googling and found loads of people discussing ways to ignore the tags. Suggetions rainged from sax parsers to character by character loops (nasty).

Armed with an excellent regex for matching an entire HTML tag we came up with the following solution
Our Solution

Use a custom Regex match evaluator to ignore any tags. This works well and is very fast. There may be a slicker way to do this, I hope someone is inspired enough to figure it out and post a comment


private string replaceString = "";
public string Parse(string content)
{
const string regTagName = @"<.[^>]*>";

Regex reg = new Regex(@"(" + regTagName + ")|(geekzilla)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);

// this is what I'd like to replace the match with
replaceString = "$1";

// do the replace
content = reg.Replace(content, new MatchEvaluator(MatchEval));

return content;
}

protected string MatchEval(Match match)
{
if (match.Groups[1].Success)
{
// the tag
return match.ToString();
}
if (match.Groups[2].Success)
{
// the text we're interested in
return Regex.Replace(match.ToString(), "(.+)", replaceString);
}
// everything else
return match.ToString();
}

Highlighting keywords in text using Regex.Replace

Why

I needed to take some text and bold certain keywords before returning the data to the web browser to enhance my Search Engine Optimization

Example

The following example shows how I achieved this although it does contain dummy data. I created a new C# 2005 Console App and added the following to the Main method:

string keywords = "Cat, rabbit, dog,hound, fox";
string text = "The cat spoke to the dog and told him what the rabbit did to the fox while the hound was sleeping.";

Console.WriteLine(HighlightKeywords(keywords, text));
Console.ReadLine();


Then added the follwoing static methods:

private static string HighlightKeywords(string keywords, string text)
{
// Swap out the , for pipes and add the braces
Regex r = new Regex(@", ?");
keywords = "(" + r.Replace(keywords, @"|") + ")";

// Get ready to replace the keywords
r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);

// Do the replace
return r.Replace(text, new MatchEvaluator(MatchEval));
}

private static string MatchEval(Match match)
{
if (match.Groups[1].Success)
{
return "" + match.ToString() + "";

}

return ""; //no match
}

Cleaning a string using a regular expression ready for placing in a URL


public static string CleanForUrl(string text)
{
return Regex.Replace(text, @"[^a-z^A-Z^0-9^-]", "-");
}

Thursday, October 16, 2008

Enabling HttpGet and HttpPost for web services

If your web application needs to accept incoming webservice method requests based on the GET and POST protocols then add the following lines to your web.config file.


Select a row in an asp:GridView without using a Select Command

ASP.Net's GridViews can be quite useful, but beware of binding them to huge datasets as this has an overhead on the ViewState.
Often you'll want to display a number of columns on each line and row space becomes an issue. What's worse is you then have to create a SELECT command button to be able to access that line's data.



Use the following code on the event OnRowDataBound to eliminate the need for the SELECT command field and save yourself some valuable space.
Here is the HTML to create a GridView, I'm displaying a list of people, and the key for each record is the PERSON_ID.


The key event to note is the OnRowDataBound, use the following code to create SELECT functionality on the row.


protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.PeopleGridView, "Select$" + e.Row.RowIndex);
        }
    }

Each row will then behave like a link, and when you select one it can drive the behavior of another control(s) on your page, possibly a DetailsView allowing you to INSERT a complete record to the database.

Perform actions before a row is deleted from a GridView or a DetailsView

I'm a big fan of caching objects on the web server, really saves loads of unneccessary trips to SQL Server and those precious resources.
In a recent project I built some administration screens to change the configuration of my site, as it happens this data was cached on the server for 8 hours at a time.
Rather than let the cache expire for the changes to be picked up I leveraged a feature of the GridView and DetailsView controls I was using, to clear the cache on a DELETE or INSERT by simply using the RowDeleting Event on the GridView and the ItemInserting on the DetailsView.
Here's the code:

protected void ProductCategoriesGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string categoryID =((HiddenField)ProductCategoriesGridView.Rows[e.RowIndex].FindControl("CATEGORY_ID")).Value;
try
{
Cache.Remove("PRODUCTS_" + categoryID);
}
catch (Exception)
{
}
}



Using the RowIndex property of the GridViewDeleteEventArgs, you can then access the row that you're just about to delete. Here I have a hidden field that holds a key suffix to a cached object. This isn't a key in my GridView or I would have used the DataKeys property.
When I need to insert some data via the DetailsView I used the following code on the ItemInserting event.


protected void ProductCategoryDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
    string categoryID = ((DropDownList)ProductCategoryDetailsView.Rows[0].FindControl("CategoryDropDownList")).SelectedValue;
  try
    {
         Cache.Remove("PRODUCTS_" + categoryID);
    }
    catch (Exception)
    {
    }
}


Here I'm grabbing the key suffix from a dropdown list in the DetailsView. I clear the cache and perform the INSERT to the database. This will ensure that the latest data is loaded and cached for the next request.

Rendering a Control to a String

This is a really handy little function for rendering a control to a string. Really handy if you want to pass back rendered HTML from a StaticPageMethod or WebService.

private static string GetRenderedControl(Control control)
{
HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
control.RenderControl(writer);
return writer.InnerWriter.ToString();
}

Monday, October 13, 2008

Call ServerSide function from Javascript

aspx file:
aspx.cs file:
private void Page_Load(object sender, System.EventArgs e)
{
 if ( this.IsPostBack )
 {
  string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
  if ( eventArgument == "CallServerSideFunction1" )
   ServerSideFunction1();
 
 }
}
private void ServerSideFunction1()
{
 this.Response.Write("ServerSideFunction1 called");
}

Thursday, October 9, 2008

Generating Sequence Number in DataGrid with Paging

In my previous article(  Generating Sequence Number in DataGrid) , i have explained how to generate sequence number (row number) in a DataGrid. This method can be easily implemented in DataGrid if there is no paging involved in that DataGrid. But same wont work in DataGrid, if paging is also there in DataGrid. To know how to do paging in DataGrid, refer this article Paging in DataGrid
If you implement this method, in the all the pages Sequence number will start from one only. But our requirement is not that, sequence number has to continue in all the pages.
For example if i am going to second page with Pagesize 10, then sequence number  should start from 11. To achieve this result we need to slightly tweak our previous method. Code snippet for implementing this method is,  

     
                  
                                     
                        <%# (DataGrid1.PageSize*DataGrid1.CurrentPageIndex)+ Container.ItemIndex+1%>
                
                 
           
           
                                
           
                 
                       
            
        
   


Tweak in the code is very simple, instead of only using container.itemindex to get the sequence number. You need to use Pagesize and currentpageindex to find out the starting number of that page and then add container.itemindex to that.

Avoid Using Count(*)

If you need to return the total table's row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table's row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*):

SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2

you can improve the speed of such queries in several times.

Wednesday, October 8, 2008

Password Hashing in C#

In normal circumstances when you store passwords in a database in clear text, you simply authenticate a user by finding the password associated with the username supplied and comparing the inputted password with the database value. Authentication with hashed passwords is obviously a little different than the traditional approach. You will create a hash value of the user inputted password and compare it with the already hashed value in your database. If the two hashed strings are equal, go ahead and authenticate the user. For example:
string strUserInputtedHashedPassword = 
             FormsAuthentication.HashPasswordForStoringInConfigFile(
                                      tbPassword.Text, "sha1");
if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text))
{
   // sign-in successfull
}
else
{
   // sign-in failed
}
 
protected TextBox tbPassword;
  protected Literal liHashedPassword;

  
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
  }
  public void btnHash_Click(object sender, EventArgs e)
  {
   if(tbPassword.Text.Length > 0)
   {
    string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1");
    liHashedPassword.Text = "Hashed Password is: " + strHashedPassword;    
   }
  }

Convert hex color to .net Color object

Convert hex color to .net Color object
The syntax for using the ColorTranslator to convert a hex value:
Color black = ColorTranslator.FromHtml("#000000");
Because it took me more than a minute to find, I decided to post it for future reference…

Monday, October 6, 2008

Embed text in Image using ASP.NET

Sometimes, it is nice to have a text caption embedded into an image, rather than display the caption in HTML. Fortunately, this is fairly straightforward in ASP.NET.

image_text.aspx

<%@ Page Language="c#"%>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

private void Page_Load(object sender, System.EventArgs e)
{
  Bitmap bmp= new Bitmap(Server.MapPath(Request.QueryString["i"]));
  Graphics g=Graphics.FromImage(bmp);
  g.SmoothingMode = SmoothingMode.AntiAlias ;
  g.DrawString(Request.QueryString["t"],
  new Font("verdana",12),SystemBrushes.WindowText, 1, 1);
  Response.ContentType="image/jpeg";
  bmp.Save(Response.OutputStream, bmp.RawFormat) ;
}

Get Host by IP adress

Get Host by IP adress

 string IPAdress = "127.0.0.1";
IPHostEntry IPHostEntryObject = Dns.GetHostEntry(IPAdress);
Console.WriteLine(IPHostEntryObject.HostName)

Make C# Application Wait Amount of Time

Stalling for Time

C#.Net programs sometimes need to wait a certain amount of time before carrying out the rest of the code. For example, an application that reminds users every 15 minutes to do something has to stall for 15 minutes.
While you can do time-measuring algorithms in C# with the Timer class, let's try to use a simpler way...

DateTime vs StopWatch

If you remember the code speed test utility, there are two C# classes (not including Timer) that can measure time, the DateTime class and the System.Diagnostics.StopWatch class.
The DateTime class is good if you want to work with loose amounts of time, meaning that 14.98 seconds would be okay if you were aiming for 15.
The StopWatch class on the other hand is as precise as you can get with only C# code.
Whichever one you use is up to you...

How to Stall for Time

The basic way to stall for time in C# will be to use a while loop. In theory, we just need the loop to run in circles until enough time has passed. The example uses DateTime, but the StopWatch object would work too...
DateTime start = DateTime.Now;

while (DateTime.Now.Subtract(start).Seconds < 15)
{
}
That source code will work, but it is not elegant just yet. The problem is it freezes the C# program until the 15 seconds are over. Even worse, it eats up the CPU attention.
To keep the application responsive, you need to add the following C# line inside the loop:
Application.DoEvents();
That makes the applicaiton process its messages even while the loop is running. Thus normal UI interaction is kept running.
To prevent the CPU from going insane:
System.Threading.Thread.Sleep(1);
Technically that C# code can reduce how accurate the stalling time is, but giving the loop a 1 millisecond break per iteration, frees up the CPU.
Remember, both of those lines go inside the loop. And with that, you now have an elegant way to stall for time with simple C# code.

Sunday, October 5, 2008

Optimizing C# Application

Optimizing C# Application

7 Ways To Optimize C# Code

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder

You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings

In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:
str1.ToLower() == str2.ToLower()
However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:
string.Compare(str1, str2, true) == 0 //Ignoring cases
 
The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty

This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:
if (str == "")
with:
if (str == string.Empty)
 
This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>

ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:
ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;
 
Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:
List<int> intList = new List<int>();

intList.add(10)

return intList[0] + 20;
There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators

When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:
if (object1 != null && object1.runMethod())
 
If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch

Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions

C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.

 

C# Unique Hardware ID

C# Unique Hardware ID

Obtaining the Computer's Unique ID

Each computer has certain hardware pieces that carry serial numbers. Using these serial numbers it is possible to obtain a hardware ID in C# that is unique to a certain computer only.
Keep in mind there are some serial numbers that are not true hardware serials, as in they change when the harddrive is formatted.
We are going to use the first CPU's ID and the first Harddrive's actual serial, neither of which change upon formatting. Using C# code, you can combine those serials into a unique hardware ID

Hardware IDs

Both ID's will require the System.Management.dll reference. If you create a New Project the reference will not be added automatically.
Add it manually by right-clicking on "References" (in the Solution Explorer) and hit "Add Reference...". Scroll down to System.Management (in the .Net tab) and add it...

CPU ID

Note that finding the CPU unique hardware ID is a bit different than normal C# programming. We'll be accessing the property through string expressions rather than strong-typed properties.
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();

foreach (ManagementObject mo in moc)
{
     if (cpuInfo == "")
     {
          //Get only the first CPU's ID
          cpuInfo = mo.Properties["processorID"].Value.ToString();
          break;
     }
}
return cpuInfo;
The function runs with a bit of a delay, but nothing too terrible.

Hard Drive ID (Volume Serial)

Finding a unique volume serial works very similarly and luckily a bit simplier:
ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");
dsk.Get();
string volumeSerial = dsk["VolumeSerialNumber"].ToString();

Deriving a Unique ID

The two serials can be combined in any way you wish. Use simple C# string functions or complex one. For example, after testing it across several systems, I decided to truncated serveral 0's from the Volume Serial.
A quick note. What is the point of a unique hardware ID? The most common use for such information is for licensing software that is tailored to a specific computer of set of computers. With a bit of C# encryption functions, it can be an effective method.
Download the C# project files to see for yourself the speed of the combined functions and the complexity of the serial number...

Wednesday, September 24, 2008

Upload a file only using browse button

Convert a string to Proper Case

Use the namespace System.Globalization
VB.NET

Dim myString As String = "syncFusion deVeloPer sUppOrt"
' Creates a TextInfo based on the "en-US" culture.
Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfo
Response.Write(TI.ToTitleCase(myString))


C#

string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

Wednesday, September 17, 2008

Website ScreenShot ( Website Thumbnail)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Windows.Forms;

public partial class snapshot : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = ((string.IsNullOrEmpty(Request.Params["site"])) ? "www.microsoft.com":Request.Params["site"]);
        int width = ((string.IsNullOrEmpty(Request.Params["width"])) ? 200 : int.Parse(Request.Params["width"]));
        int height = ((string.IsNullOrEmpty(Request.Params["height"])) ? 140 : int.Parse(Request.Params["height"]));
        int capWidth = ((string.IsNullOrEmpty(Request.Params["capWidth"])) ? 1024 : int.Parse(Request.Params["capWidth"]));
        int capHeight = ((string.IsNullOrEmpty(Request.Params["capHeight"])) ? 768 : int.Parse(Request.Params["capHeight"]));
        bool fullHeight = ((string.IsNullOrEmpty(Request.Params["fullHeight"])) ? true : bool.Parse(Request.Params["fullHeight"]));
      
        string address = "http://" + url.Replace("hhtp://","");
        Bitmap thumbnail = WebsiteThumbnailImageGenerator.GetWebSiteThumbnail(address, capWidth, capHeight, width, height,fullHeight);
  
        Response.ContentType = "image/jpeg";
        thumbnail.Save (Response.OutputStream, ImageFormat.Jpeg);
    }
}

public class WebsiteThumbnailImageGenerator
{
    public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight, bool FullHeight)
    {
        WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight,FullHeight);
        return thumbnailGenerator.GenerateWebSiteThumbnailImage();
    }

    private class WebsiteThumbnailImage
    {
      
        private WebBrowser _blankBrowser = null;

        public WebsiteThumbnailImage(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight, bool FullHeight)
        {
            this.m_Url = Url;
            this.m_BrowserWidth = BrowserWidth;
            this.m_BrowserHeight = BrowserHeight;
            this.m_ThumbnailHeight = ThumbnailHeight;
            this.m_ThumbnailWidth = ThumbnailWidth;
            this.m_fullHeight = FullHeight;
            //_blankBrowser = new WebBrowser();
        }

        private string m_Url = null;
        public string Url
        {
            get
            {
                return m_Url;
            }
            set
            {
                m_Url = value;
            }
        }

        private Bitmap m_Bitmap = null;
        public Bitmap ThumbnailImage
        {
            get
            {
                return m_Bitmap;
            }
        }

        private int m_ThumbnailWidth;
        public int ThumbnailWidth
        {
            get
            {
                return m_ThumbnailWidth;
            }
            set
            {
                m_ThumbnailWidth = value;
            }
        }

        private int m_ThumbnailHeight;
        public int ThumbnailHeight
        {
            get
            {
                return m_ThumbnailHeight;
            }
            set
            {
                m_ThumbnailHeight = value;
            }
        }

        private int m_BrowserWidth;
        public int BrowserWidth
        {
            get
            {
                return m_BrowserWidth;
            }
            set
            {
                m_BrowserWidth = value;
            }
        }

        private int m_BrowserHeight;
        public int BrowserHeight
        {
            get
            {
                return m_BrowserHeight;
            }
            set
            {
                m_BrowserHeight = value;
            }
        }

        private bool m_fullHeight;

public bool FullHeight
{
get { return m_fullHeight;}
set { m_fullHeight = value;}
}


        public Bitmap GenerateWebSiteThumbnailImage()
        {
            Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join();
            return m_Bitmap;
        }

        private void _GenerateWebSiteThumbnailImage()
        {
            WebBrowser m_WebBrowser = new WebBrowser();
            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate(m_Url);
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
            m_WebBrowser.Dispose();
        }

        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser m_WebBrowser = (WebBrowser)sender;

            int _height = this.m_BrowserHeight;
            int _width = this.m_BrowserWidth;
            Size sz = m_WebBrowser.Size;

            if (this.FullHeight)
            {
                _height = m_WebBrowser.Document.Body.ScrollRectangle.Height;
                _width = m_WebBrowser.Document.Body.ScrollRectangle.Width;
            }
            if (_width < this.BrowserWidth)
                _width = this.BrowserWidth;

            if (_height < sz.Height)
                _height = sz.Height;

            if (_width != m_WebBrowser.Width)
            {
                m_WebBrowser.Size = new Size(_width, _height);
                //_blankBrowser.Size = new Size(_width, _height);
                m_WebBrowser.Refresh(WebBrowserRefreshOption.Completely);

                if (this.FullHeight)
                {
                    _height = m_WebBrowser.Document.Body.ScrollRectangle.Height + SystemInformation.VerticalScrollBarWidth;
                }
                if (_height < sz.Height)
                    _height = sz.Height;
            }

            m_Bitmap = new Bitmap(_width, _height);
            m_WebBrowser.DrawToBitmap(m_Bitmap, new Rectangle(m_WebBrowser.Location.X, m_WebBrowser.Location.Y, m_WebBrowser.Width, m_WebBrowser.Height));

          
            PrepareThumbNailSize(_height, _width);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
        }
        private void PrepareThumbNailSize(int OriginalHeight, int OriginalWidth)
        {
          
            if (this.FullHeight)
            {
                double factor = Convert.ToDouble(OriginalHeight) / Convert.ToDouble(OriginalWidth);
                double calc = Convert.ToDouble(this.m_ThumbnailWidth) * factor;
                int thumbHeight = Convert.ToInt32(calc);
                this.m_ThumbnailHeight = thumbHeight;
            }
        }
    }
}

Friday, August 1, 2008

Autocomplete Text Box using Ajax

  1. Example 1 
  2. Example 2 
  3. ASP.NET AJAX AutoComplete Control Demonstration
  4. Google Suggest Style Filter with the AutoComplete Control 
  5. AutoCompleter Tutorial - jQuery(Ajax)/PHP/MySQL

Password Strength meter

the password strength meters available on the web. Using prototype/scriptaculous, I stole some code from ZeBadger (thanks!) and created a new meter which dynamically changes while typing your password.
Preview
Click here to see the demo
If you want to use this script, feel free to download the source and use it on your website.

Pretty Checkboxes & Radiobutton

This script is for people who wants to have a consistent look for checkboxes across browser or those who simply want them to look better. By using this script you wont loose any of the regular inputs usability. If you have any comment/suggestion please post them in the main script post.

Demo

Custom checkboxes
Custom radio buttons
Inline radio buttons

Browser support

This plugin has been tested and is known to work in the following browsers
  • Firefox 3.0 (Mac/PC/Linux)
  • Firefox 2.0 (Mac/PC/Linux)
  • Opera 9.5 (Mac/PC)
  • Safari 3.1.1 (Mac)
  • Internet Explorer 6.0 (PC)
  • Internet Explorer 7.0 (PC)

Copyright

This script is licensed under Creative Commons Attribution 2.5. So you can use it in all you projects even commercial ones. Donations are always welcome.

Download

Uncompressed version (Script: 2.2kb)
Compressed version (Script: 1.8kb)

Version history

  • 1.0: Initial release of prettyCheckboxes.

How to use

Nothing is easier to use. First include the jQuery library then include the prettyCheckboxes javascript in the head of the page(s) where you want to use prettyCheckboxes.
jQuery can be download here
IMPORTANT: For the script to work properly EVERY labels need to have a "for" attribute linking to the ID of their corresponding checkbox/radio
				


				
			
Then you need to initalize prettyCheckboxes.
				
$(document).ready(function(){
	$('input[type=checkbox],input[type=radio]').prettyCheckboxes();
});
				
			
If you want prettyComments to be initialized on specific inputs, you can specify which element by using a CSS selector, like so:
				
$(document).ready(function(){
	$('input.myCheckbox').prettyCheckboxes();
});
				
			
You can provide several parameters to the function if you want to customize it a bit further
				
$(document).ready(function(){
	$('input[type=checkbox],input[type=radio]').prettyCheckboxes({
		checkboxWidth: 17, // The width of your custom checkbox
		checkboxHeight: 17, // The height of your custom checkbox
		className : 'prettyCheckbox', // The classname of your custom checkbox
		display: 'list' // The style you want it to be display (inline or list)
	});
});
				
			
If you can to customize the look of the inputs, you can customize those image
Please note that you have the hover and selected state in the same image and that the inputs should be at the same position, unless you want/can modify the CSS yourself.
That's it, now your inputs should behave the same as in the demo on this page





jquery Hover Sub Tag Cloud

Tag clouds When, used properly, they can provide visitors with an instant illustration of the main topics of the site’s content. And although we don’t have that much choice in designing them, we can still find our way to come up with new design approaches and solutions.
Here is a new approach: Using jQuery  to reduce the size of the tag cloud that you have on your sites, so our demo will introduce "Hover Sub Tags" under each main Tag, for example if you have Ajax as a tag, you can have jquery, mootools, etc… as sub-tags.  A Sub Tag  Cloud will appear when hovering over the main Tag links.
Check out the link below to see it in action.
[LIVE EXAMPLE]


[Download the code here]

Monday, July 28, 2008

Export to Excel Using Styles

Saturday, July 19, 2008

Encrypting QueryStrings with .NET

Introduction:

Once upon a time in the tech world, obscurity was security - this being most true in the early years of the industry, when there were gaping holes in privacy policies and confidential client information was bandied about from site to site without a care as to who actually could read the information.

With the new Cryptography classes in .NET, there's absolutely no excuse for not hiding even the most innocuous user data. If you ever need to 'piggy-back' information from one web page to another, whether it is within a POST or a GET parameter, you're passing clear information that anyone can sniff - and that's a bad thing.

If you're not going to use a session variable for storing end user information, you're most likely going to keep some sort of State by passing the information to a cookie or push it around with GET/POST parameters. If you're passing around any sort of ID or user information like their name, it's better to err on the side of caution and encrypt the information.

GET Vs. POST

A POST parameter keeps the information out of the URL, but it can still be sniffed quite easily as it passes in clear text across your network or the Internet. Using POST will keep the mere curious at bay, as the information is not contained in the URL - but this will not stop someone determined to snag out your data.

A QueryString parameter passes information within the site's URL. Why would you even use a QueryString? Well, maybe you need to let your user bookmark a particular page, or maybe you have to refer directly to a page in a URL via a link - you can't do either if you're using POST. A QueryString puts data in the URL for the entire world to see, so if you don't know if the end user is malicious, I'd think hard about using a QueryString for anything but site-related information.
Be smart and encrypt any and all data you're moving around from page to page, especially if that information could be used maliciously. You may trust your users, but you still need that extra level of security that clear text GET/POST data doesn't provide.

Imagine this scenario - you've been passing the customer's ID in the database around in a QueryString, in a URL that looks like this:
http://mysite.com?cust_id=29

You know what a user is going to do? Switch that 29 to a 30 or 12 or some other number, and if you're not checking for invalid requests, you'll be dishing up some other customer's data.

Enter Encryption

What I was looking for was a quick way to encrypt and decrypt parts of a QueryString - it had to be on the fly, quick and dirty.
I chose Base64 because it wouldn't throw bizarre characters in my QueryString that I couldn't pass around… Little did I know that I'd hit a snag while passing around my encrypted QueryString - Apparently, the Request.QueryString object interprets the '+' sign as a space! So, with a quick Replace function slapped on my decrypt string, no harm, no foul.

Symmetric Key

The whole trick to this working is that the QueryString is encrypted and decrypted with the same private key. This is the secret key - if anyone gets a hold of your key, they can decrypt the data themselves, so keep it a secret!
We're going to use a hard-to-crack 8 byte key, !#$a54?3, to keep parts of our QueryString secret. Let's Walk through the C# portion of the code:

Notice our two functions that abstract the dirty work that our Encryption64 class. The first, encryptQueryString, is used to encrypt the value of a QueryString. The second, decryptQueryString, is used to decrypt the value of an encrypted QueryString.

public string encryptQueryString(string strQueryString) {
ExtractAndSerialize.Encryption64 oES =
new ExtractAndSerialize.Encryption64();
return oES.Encrypt(strQueryString,"!#$a54?3");
}

public string decryptQueryString(string strQueryString) {
ExtractAndSerialize.Encryption64 oES =
new ExtractAndSerialize.Encryption64();
return oES.Decrypt(strQueryString,"!#$a54?3");
}

If we wanted to encrypt our QueryString on our first page, we could do something like this:
string strValues = "search term";
string strURL = "http://mysite.com?search="
+ encryptQueryString(strValues);
Response.Redirect(strURL);

Inside our code-behind in our second page, we pass the contents our QueryString to a variable named strScramble. After that, we replace the '+' signs that our wonderful Request.QueryString has replaced with a space. We pass that string into our function, decryptQueryString, and retrieve the decrypted string.

string strScramble = Request.QueryString["search"];
string strdeCrypt = decryptQueryString(
strScramble.Replace(" ", "+"));

Now we've decrypted the value of the QueryString, 'search', and we can do whatever we want with it. The end user is going to see a URL that looks like:
http://yoursite.com?search=da00992Lo39+343dw

They'll never be able guess what's going on in your QueryString, and if they try to fool around with it, there's no way to crack the code without knowing the Symmetric key.

C#.NET
1. using System;
2. using System.IO;
3. using System.Xml;
4. using System.Text;
5. using System.Security.Cryptography;
6.
7. public class Encryption64
8. {
9. private byte[] key = {};
10. private byte[] IV = {18, 52, 86, 120, 144, 171, 205, 239};
11.
12. public string Decrypt(string stringToDecrypt, string sEncryptionKey)
13. {
14. byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
15. try {
16. key = System.Text.Encoding.UTF8.GetBytes(Strings.Left(sEncryptionKey, 8));
17. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
18. inputByteArray = Convert.FromBase64String(stringToDecrypt);
19. MemoryStream ms = new MemoryStream();
20. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
21. cs.Write(inputByteArray, 0, inputByteArray.Length);
22. cs.FlushFinalBlock();
23. System.Text.Encoding encoding = System.Text.Encoding.UTF8;
24. return encoding.GetString(ms.ToArray());
25. }
26. catch (Exception e) {
27. return e.Message;
28. }
29. }
30.
31. public string Encrypt(string stringToEncrypt, string SEncryptionKey)
32. {
33. try {
34. key = System.Text.Encoding.UTF8.GetBytes(Strings.Left(SEncryptionKey, 8));
35. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
36. byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
37. MemoryStream ms = new MemoryStream();
38. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
39. cs.Write(inputByteArray, 0, inputByteArray.Length);
40. cs.FlushFinalBlock();
41. return Convert.ToBase64String(ms.ToArray());
42. }
43. catch (Exception e) {
44. return e.Message;
45. }
46. }
47.
48. }
49.

Friday, July 18, 2008

Finding If the Url Exists

Introduction:
Hyperlinks are the linking blocks of all web applications. You can link one webpage to the other by using hyperlinks. Sometimes when a website contains hundreds of links it is hard to locate that which links are working and which are not. In this article I will demonstrate that how you can find out that if the hyperlink of a webpage is exists or not.
Getting all the urls of the Page:
Our first task is to get all the urls (hyperlinks) on the page. Once, we have all the hyperlinks contained in a webpage we can iterate through the links and find out which of them exists. Check out the code below which demonstrates that how you can extract the HTML of a page.
 List badUrlList = new List();
        WebRequest req = WebRequest.Create("http://

localhost:2640/BadUrls/UrlList.aspx");
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        Stream stream = res.GetResponseStream();
        ArrayList badUrls = 
new ArrayList();

        StreamReader reader = 
new StreamReader(stream);
        
string html = reader.ReadToEnd();
 

 The WebRequest class contains the Create method which makes the request to provided url. The GetResponse method is used to get the response from the web server. After getting the response we read the ResponseStream in the string format and save the output in a string variable called "html".
The string variable "html" will contain all the HTML tags of the requested page. At this point we need to extract the links out of the HTML. For this we will need a regular expression. Check out the code below which uses a regular expression to extract all the links out of the HTML of the page.
 // Get the links
        
string pattern = @"((http|ftp|https):\/\/w{3}[\d]*.|

(http|ftp|https):\/\/|w{3}[\d]*.)([\w\d\._\-#\(\)\[\]\\,;:]
+@[\w\d\._\-#\(\)\[\]\\,;:])?([a-z0-9]+.)*[a-z\-0-9]+.([a-z]
{2,3})?[a-z]{2,6}(:[0-9]+)?(\/[\/a-z0-9\._\-,]+)*[a-z0-9\-_\
.\s\%]+(\?[a-z0-9=%&\.\-,#]+)?";

        Regex r = 
new Regex(pattern);
        MatchCollection mC = r.Matches(html);

The MatchCollection variable "mC" will contain all the matches of the regular expression. In this case mC will be filled with all the hyperlinks. Now, we can check the hyperlinks one by one and find out that if it exists or not.
Making Sure that the Hyperlink Exists:
First, I must admit that the method that I am going to use is not the best method. Second, the method when executed takes awful amount of time and can result in a timeout. Also, this method will not work if your ISP is redirecting you to a custom page when the page not found exception is thrown.
 private bool DoesUrlExists(string url)
    {
        
bool urlExists = false;
    

        
try
        
{

            WebRequest req = WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            urlExists = 
true;
        }
        
catch (System.Net.WebException ex)
        {
       
        }

        
return urlExists;
    }

 As, you can see from the code above that the whole logic is based on the exceptions. If the exception is thrown then it will be assumed that the url does not exists else the url exists.
I made a simple test file to make sure that the application works as expected. Take a look at the file below which have some real urls and some dummy urls.
UrlList.aspx:



     My Url
    My Url
    My Url
    My Url
    


I have also made the interface a little better so that the user will have a better idea of what is happening.
 
The urls which are highlighted in dark pink are the urls that does not exists and the ones in the light green are the ones which exists. As, you can see that the application shows that the urls www.jhasd.aspx and www.bhbbagsdns.aspx exists but in reality they do not exist. The reason the dummy links are showing as exist is that the ISP is redirecting the page not found requests to a custom page which exists. My suggestion is that when you are running this application make sure that the page not found requests are not redirected to the custom ISP page.
I have included the download samples files which can be downloaded at the end of this article.
I hope you liked the article, happy coding!

Prevent Caching of WebPage in Asp.net

Prevent Caching of .aspx page

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);
}
}

URL Mapping in asp.net 2.0

URL Mapping is a mechanism by which you can change the displayed url in address bar.
Example:
Your asp.net application is developed from years, with convention frm as prefix to webform.
Now to change already assigned name to legacy system which is maintained for past few years and to avoid risk we can make use of URL Mapping.

For URL Mapping
Step1: Add Mapping URL in web.config file.
<system.web>
<
urlMappings enabled="true">
<add url="~/Department.aspx" mappedUrl=" oldforms/frmDept.aspx"/>
<add url="~/Employee.aspx" mappedUrl=" oldforms/frmEmployee.aspx"/>
<add url="~/Product.aspx" mappedUrl=" oldforms/frmProduct.aspx"/>
urlMappings>
system.web>

Step2: Change the URL in .aspx file
<a href="Department.aspx">Departmenta><br />
<a href="Product.aspx">Producta><br />
<a href="Employee.aspx">Employeea>