Monday, August 16, 2010

Catch StreamWriter Exception

Stream writer is used to write characters to a stream in a particular encoding. By default, a StreamWriter is not thread safe and use an instance of UTF8Encoding. You can specify it if you want to.

Example
string fileName = @"c:\text.txt";

try
{
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
sw.WriteLine("Hello world");
sw.Close();
fs.Close();
}
}
catch (IOException)
{
MessageBox.Show("No enough disk space or drive is readonly");
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Access deny");
}
catch (SecurityException)
{
MessageBox.Show("You don't have enough required permission");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
There are more exception you should use when you using StreamWriter
Exception TypeCondition
IOException A general I/O exception occurred, such as trying to access a CD-ROM drive whose tray is open.
DirectoryNotFoundException The directory information specified in path was not found.
UnauthorizedAccessException Access is denied. The caller does not have the required permission.
ArgumentException path is a zero-length string, contains only white space, or contains one or more implementation-specific invalid characters.
ArgumentNullException path or encoding is null
NotSupportedException path is in an implementation-specific invalid format.
PathTooLongException The length of path or the absolute path information for path exceeds the implementation-specific maximum length.
SecurityException The caller does not have the required permission.

Sunday, August 15, 2010

String vs StringBuilder

1- String
System.string is immutable in .Net Framework. That means that any change to a string cause the runtime to create a new string address in memory and abandon the old one.

Example:

string s = "Hello"; //(1)
s += "World"; //(2)
s += "Programming"; //(3)


After running this code, only the last string has reference (3); the other are disposed during garbage collection.


There are several ways to avoid temporary strings:
  • Using Concat, Join, Format methods
  • Using StringBuilder


2- StringBuilder
System.StringBuilder is mutable string, which create only one reference address in memory during the running application. By default, the constructor creates a 16-byte buffer. You can also specify an initial size and a maximum size if you like.

Example:

StringBuilder sb = new StringBuilder(50);
sb.Append("Hello");
sb.Append("World");
sb.Append("Programming");


Monday, August 9, 2010

Set value to FileUpload Control programmatically

When you use asp.net FileUpload Control, you are not able to set any values to its TextBox Property. The following code demonstrate how to hack around this problem.

Note: it works only when you use tage <form runat="server">

Design Page (Default.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txbImageFile" runat="server"
Enabled="False" Width="430px"></asp:TextBox>
<asp:FileUpload ID="fileImageUpload" runat="server" Width="70px"
Enabled="True" EnableTheming="False"
onchange="this.form.txbImageFile.value=this.value" />
<br />
</form>
</body>
</html>


Code Behind (Default.aspx.cs)

public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txbImageFile.Text = @"C:\text.txt";
}
}

Tuesday, August 3, 2010

The grid view fired event which wasn't handled

You may experience this error when you are handling the ItemCommand instead of handing the RowEditing event.

This happens to me when I name my CommandName "Edit". The following is the message I got when run my web application and click on any Edit Button.

My Solution
  • Do not use word "Edit" as a CommandName
My GUI:

Id Name Address
Edit 1 Jonh NY
Edit 2 Nanny NY
Edit 3 Bob NY

Message Error

The GridView 'dg' fired event RowEditing which wasn't handled.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The GridView 'dg' fired event RowEditing which wasn't handled.

Source Error:

An unhandled exception was generated during the execution of the current
web request. Information regarding the origin and location of the exception
can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): The GridView 'dg' fired event RowEditing which wasn't handled.]
System.Web.UI.WebControls.GridView.OnRowEditing(GridViewEditEventArgs e) +1463273
System.Web.UI.WebControls.GridView.HandleEdit(Int32 rowIndex) +43
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +589
System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +121
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +125
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +169
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

My Code