Thursday, July 30, 2009

Image to Byte Array and Byte Array to Image
public byte[] imageToByteArray(System.Drawing.Image imageIn)
MemoryStream ms = new MemoryStream();
return ms.ToArray();

public Image byteArrayToImage(byte[] byteArrayIn)
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;

HttpModule Execution Sequence

An application executes events that are handled by modules or user code that is defined in the Global.asax file in the following sequence:

1. BeginRequest
2. AuthenticateRequest
3. PostAuthenticateRequest
4. AuthorizeRequest
5. PostAuthorizeRequest
6. ResolveRequestCache
7. PostResolveRequestCache

After the PostResolveRequestCache event and before the PostMapRequestHandler event, an event handler (a page corresponding to the request URL) is created.

8. PostMapRequestHandler
9. AcquireRequestState
10. PostAcquireRequestState
11. PreRequestHandlerExecute

The event handler is executed.

12. PotRequestHandlerExecute
13. ReleaseRequestState
14. PostReleaseRequestState

After the PostReleaseRequestState event, response filters, if any, filter the output.

15. UpdateRequestCache
16. PostUpdateRequestCache
17. EndRequest

Wednesday, July 29, 2009

byte array to bitmap
public static Bitmap BytesToBitmap(byte[] byteArray)
using (MemoryStream ms = new MemoryStream(byteArray))
Bitmap img = (Bitmap)Image.FromStream(ms);
return img;

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));

Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(byteArray);


ImageConverter ic = new ImageConverter();

Image img = (Image)ic.ConvertFrom(byteArray);

Bitmap bitmap1 = new Bitmap(img);

Friday, July 24, 2009


Tip #1 How to behold the power of incremental search

Command: Edit.IncrementalSearch

Shortcut: Ctrl+i

Tip #2 Ctrl+F3 to search for currently-selected word

Command: Edit.FindNextSelected

Tip #3 F3 to search for last thing you searched for

Command: Edit.FindNext

Tip #4 Customize what files to find in

Find In Files – Look in – Choose Search Folders

Tip #5 You can use a reg hack for customizing search results

HKCU\Software\Microsoft\VisualStudio\9.0\Find String Find=$f$e($l,$c):$t\r\n

Editing Tips

Tip #6 How not to accidentally copy a blank line

Tools – Options – Text Editor – All Languages – General, Uncheck Apply cut or copy to blank lines

Tip #7 How to cycle through the Clipboard ring

Command: Edit.CycleClipboardRing

Shortcut: Ctrl+Shift+v

Tip #8 How to use box/column selection in the editor

Command: Edit.LineUpColumnExtend, Edit.LineDownColumnExtend, Edit.CharRightColumnExtend, Edit.CharLeftColumnExtend

Shortcut: Shift+Alt+Arrow

Tip #9 You can copy a file’s full path / open windows explorer from the file tab channel

Command: File.CopyFullPath

Tip #10 Drag and drop code onto the toolbox’s general tab

Shortcut: Ctrl+Alt+x

Tip #11 You can use Ctrl+. to show a smart tag

Command: View.ShowSmartTag

Tip #12 You can insert a snippet by pressing Tab Tab

Type in snippet shortcut, then press Tab Tab

Customizing Tips

Tip #13 You can create temp or throw away projects

Tools - Options - Projects and Solutions - General, uncheck Save new projects when created

Tip #14 Change text editor font size via keyboard (Accessibility macros)

Command: Macros.Samples.Accessibility.DecreaseTextEditorFontSize

Command: Macros.Samples.Accessibility.IncreaseTextEditorFontSize

Tip #15 How to open a file without any UI

Ctrl+/ (or whatever Tools.GoToCommandLine is bound to)

alias fo file.openfile


Tip #16 Guidelines in the editor registry key hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor String RBG(128,0,0) 5, 20

Tip #17 You can create a macro for your import/export settings

Tools – customize – commands – macros – drag and drop macro to toolbar

Tip #18 How to not show the start page (or have the last loaded solution open)

Tools - Options - Environment - Startup, At Startup

Tip #19 File tab channel registry hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0 key, you can create a DWORD UseMRUDocOrdering = 1

Tip #20 How to show Misc Files Project to keep your files around

tools - options - environment – documents, show miscellaneous files in Solution Explorer

Tip #21 Edit project file from within IDE (unload project)

Unload project, edit project, reload project

Debugging Tips

Tip #22 You can use tracepoints to log stuff in your code

Right-click in indicator margin, select breakpoints, select Insert Tracepoint

Tip #23 How to get the find source dialog back

Solution Properties, under Common Properties - Debug Source Files, Delete Do no look for these source files edit box contents

Tip #24 You can disable the exception assistant

Tools – Options – Debugging – General, uncheck Enable the Exception Assistant


Digging Into Data Binding Expressions

The case of the "Eval" should be maintained. ie. "E" should be CAPS and remaining should be small.


'<%# Eval("ID")%>'

'<%# Eval("HotelAmenities").ToString().Replace("±","") %>'

'<%# Eval("PropertyID", "\"Map.aspx?PID={0}\")") %>'

Call a function from the aspx page when binding using "Eval"

ImageUrl ='<%# LoadImage(Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]),3) %>'

LoadImage => Function Name with two parameters starrate and imagenumber

Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]) => Convert "StarRate" to int

Concat String with "Eval"

Text='<%# "Customer Review: "+ ((System.Data.DataRowView)Container.DataItem)["CustomerRatings"].ToString()+"/5" %>'

PostBackUrl='<%# "~/HotelDetails.aspx?PropertyID=" + Eval("PropertyID") %> '

PostBackUrl="'<%# "~/HotelDetails.aspx?PID=" + Eval("PropertyID") %> '"

PostBackUrl="~/SysAdmin/modifyAnnouncement.aspx?id=<%# Eval("intAnnouncementID")%>"
PostBackUrl="~/HotelDetails.aspx?PropertyID=<%# Eval("PropertyID")%>"

PostBackUrl="~/HotelDetails.aspx?PropertyID=" + '<%# Eval("ID")%>'

PostBackUrl='<%# Eval("PropertyID", "~/HotelDetails.aspx?PropertyID={0}") %>'

DataBinder.Eval versus Explicit Casting

As a regular DataBinder.Eval() user, now I feel a little
bit guilty after reading this KB article, and I'm curious
how many ASP.NET developers use explicit casting on a regular basis.
Drop me a line and let me know.

Let's say you are binding to a DataSet. This...

<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %> significantly faster than this...

<%# DataBinder.Eval(Container.DataItem, "au_id") %>

Conditions with Eval

<%#(DataBinder.Eval(Container.DataItem, "checkedout" ) == "No"), ?"Check Out":""%>

'<%# !String.IsNullOrEmpty(Convert.ToString(((System.Data.DataRowView)Container.DataItem)["RackRate"] ).Trim()) ? "£ "+((System.Data.DataRowView)Container.DataItem)["RackRate"]:"" %>'


OnClientClick='<%# Eval("PropertyID", "Javascript:popupWin(\"Map.aspx?PID={0}\",500,400)") %>'

OnClientClick='<%# Eval("PropertyID", "\"Map.aspx?PID={0}\")") %>'


onClientClick='<%#String.Format("{0}\"{1}{2}{3}{4}\")", "","Map.aspx?PID=",Eval("PropertyID"), "&Guid=",Eval("GUID")) %>'

OnClientClick="popup(' <%# ((System.Data.DataRowView)Container.DataItem)["PropertyID"] %>');"

OnClientClick='<%# Eval("PropertyID", "\"Map.aspx?PropertyID={0}\")") %>'

OnClientClick='<%# Eval('PropertyID', "'Map.aspx?PropertyID={0}','top=200,left=350,width=425,height=350, menubar=no,status=no,location=yes,toolbar=no,scrollbars=no')") %>'

"<%# DataBinder.Eval(Container.DataItem,"PropertyID","'Map.aspx?PID={0}'") %>,'question','scrollbars=yes,width=630,height=480,location=no,menubar=no,status=no,toolbar=no');"

Thursday, July 23, 2009

Char to String to Byte Conversion

// C# to convert a string to a char array.
static public char[] convertStringToCharArray(string str)
return str.ToCharArray();

// C# to convert a string to a byte array.
static public byte[] convertStringToByteArray(string str)
byte[] arrByte = new byte[str.ToCharArray().Length];
int i = 0;
foreach (char ch in str.ToCharArray())
arrByte[i] = (byte)ch;
return arrByte;

// C# to convert a string to a byte array.
public static byte[] convertStringToByteArray1(string str)
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);

// C# to convert a string to a byte array.
public static byte[] convertStringToByteArray2(string str)
return (new System.Text.UnicodeEncoding()).GetBytes(str);

// C# to convert a char array to a byte array.
static public byte[] convertCharArrayToByteArray(char[] ca)
byte[] arrByte = new byte[ca.Length];
int i = 0;
foreach (char ch in ca)
arrByte[i] = (byte)ch;
return arrByte;

// C# to convert a char array to a string.
static public string convertCharArrayToString(char[] ca)
string str;
str = ca.ToString(); //Or
str = new string(ca);
return str;

// C# to convert a byte array to a char array.
static public char[] convertByteArrayToCharArray(byte[] by)
//byte[] by = { 0x01, 0x02, 0x03 };
char[] chararray = new char[by.Length];
Array.Copy(by, chararray, by.Length);
return chararray;

// C# Convert a byte array to a string
public static string ConvertByteArrayToString(byte[] byteArray)
byte[] dBytes = byteArray;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(dBytes);
return str;

// C# Convert a byte array to a string
public static string ConvertByteArrayToString1(byte[] byteArray)
return (new System.Text.UnicodeEncoding()).GetString(byteArray);

// C# Convert a byte array to a string
public static string ConvertByteArrayToString2()
System.Net.WebClient webdata = new System.Net.WebClient();
const string sampleurl = "";

//the below statement assigns byte[]
byte[] byteArray = webdata.DownloadData(sampleurl);

//the below code converts byte[] type string type
string txt = System.Text.Encoding.GetEncoding("utf-8").GetString(byteArray);
return txt;

Friday, July 10, 2009

http to https conversion

protected void Page_Init(object sender, EventArgs e)
string fileName = System.IO.Path.GetFileName(HttpContext.Current.Request.FilePath);
//File name that you want to give Scheme Http to Https
if (fileName == "Register.aspx" || fileName == "MyAccount.aspx")
HttpToHttpsConvertor(HttpContext.Current.Request.Url, true);
else if (System.IO.Path.GetExtension(HttpContext.Current.Request.Path) == ".aspx")
//Remove Scheme Https to Http
HttpToHttpsConvertor(HttpContext.Current.Request.Url, false);

protected static void HttpToHttpsConvertor(Uri uri, Boolean isHttps)
UriBuilder secureUriBuilder = new UriBuilder(uri);

if (isHttps)
if (!HttpContext.Current.Request.IsLocal)
if (secureUriBuilder.Scheme == Uri.UriSchemeHttp)
secureUriBuilder.Scheme = Uri.UriSchemeHttps;
HttpContext.Current.Response.Status = "301 Moved Permanently";
secureUriBuilder.Port = 443;
HttpContext.Current.Response.AddHeader("Location", secureUriBuilder.ToString());

if (!HttpContext.Current.Request.IsLocal)
if (secureUriBuilder.Scheme == Uri.UriSchemeHttps)
secureUriBuilder.Scheme = Uri.UriSchemeHttp;
secureUriBuilder.Port = 80;
HttpContext.Current.Response.AddHeader("Location", secureUriBuilder.ToString());

Error 1

Data Transfer Interrupted

The connection to was interrupted while the page was loading.

The browser connected successfully, but the connection was interrupted while transferring information. Please try again.
  • Are you unable to browse other sites? Check the computer's network connection.
  • Still having trouble? Consult your network administrator or Internet provider for assistance.


Godaddy will provide a port address for SSL.
secureUriBuilder.Port = 443;


We can get all the status code

Error 2

XML Parsing Error: no element found
Line Number 1, Column 1:


Check whether you gave another port address for unsecure form like this.
secureUriBuilder.Port = 80;

Monday, July 6, 2009

Check whether we are in local machine or in Server

if (!httpContext.Request.IsLocal)
//If false then we are in server

Saturday, July 4, 2009

IE6 prompts to remember password

1. Navigate to Internet Explorer -> Tools menu -> Internet Options ->
Content tab | Personal Information section | AutoComplete button.
2. Under "Use AutoComplete for", de-select the 'User names and passwords on
forms' checkbox.
3. Click Ok to apply the setting.

The following method will clear the credentials already cached in Windows
XP joins a workgroup:
1. Open Control Panel and go into User Accounts.
2. Select the account and then choose "Manage my network passwords".
3. A "Store User Names and Passwords" dialog will appear.
4. Click Remove button to clear any passwords (for the affected sites.)

How to use the AutoComplete feature in Internet Explorer 5 and 6