Wednesday, July 15, 2009

Log File


In this article, we will adopt a simple mechanism to log errors and exceptions in website,
The error will get logged in a text file on the server.
The error file will be created on a daily basis, whenever the error is encountered

Public Shared Sub WriteErrorLog(ByVal errorMessage As String, ByVal errorStack As String, ByVal methodName As String)
Dim path As String = "~/LOG/" & DateTime.Today.ToString("dd-MM-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log DateTime : " & DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture))
w.WriteLine("Page :- " & System.Web.HttpContext.Current.Request.Url.AbsolutePath.ToString.Trim)
w.WriteLine("Function Name :- " & methodName)
w.WriteLine("Message :- " & errorMessage)
w.WriteLine("Stack Trace :- " & errorStack)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
End Sub
Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
Catch ex As Exception
WriteErrorLog(ex.Message, ex.StackTrace.ToString.Trim, ex.TargetSite.Name)
End Try
End Sub

OutPut
__________________________

Log DateTime : 07/15/2009 15:25:20
Page :- /Default.aspx
Function Name :- btnTest_Click
Message :- Attempted to divide by zero.
Stack Trace :- at Default.aspx.btnTest_Click(Object sender, EventArgs e) in D:\Test\Default.aspx.vb:line 107
__________________________


Same thing you can do in Globa.asax, at Application_Error event. You can get an Server last error by Server.GetLastError()

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()

'Function Name not be correct at application level error
WriteErrorLog(objErr .Message, objErr .StackTrace.ToString.Trim, "")

'IF you want you can redirect to user after log into log file here
' Response.Redirect("Error.aspx")
End Sub

Tuesday, July 14, 2009

Showing Total in GridView

'Declare Variable
Dim Total As Double


Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Select Case e.Row.RowType
Case DataControlRowType.DataRow, ListItemType.Item
'Calculate total for the field of each row and alternating row, Cell number change according to your field place
Total += CDbl(e.Row.Cells(0).Text)
Case DataControlRowType.Footer
'Use the footer to display the summary row.
e.Row.Cells(0).Text = Total.ToString("#,###.00")
End Select
End Sub

Sunday, July 12, 2009

Calculations in Gridview






  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
  2. DataKeyNames="ItemID" DataSourceID="sqlDataSource1"
  3. onrowdatabound="GridView1_RowDataBound">
  4. <Columns>
  5. <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
  6. <asp:BoundField DataField="ItemID" HeaderText="ItemID" InsertVisible="False"
  7. ReadOnly="True" SortExpression="ItemID" />
  8. <asp:TemplateField HeaderText="quantity" SortExpression="quantity">
  9. <EditItemTemplate>
  10. <asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
  11. </EditItemTemplate>
  12. <ItemTemplate>
  13. <asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. <asp:TemplateField HeaderText="price" SortExpression="price">
  17. <EditItemTemplate>
  18. <asp:TextBox ID="txtPrice" runat="server" Text='<%# Bind("price") %>'></asp:TextBox>
  19. </EditItemTemplate>
  20. <ItemTemplate>
  21. <asp:Label ID="Label2" runat="server" Text='<%# Bind("price") %>'></asp:Label>
  22. </ItemTemplate>
  23. </asp:TemplateField>
  24. <asp:TemplateField HeaderText="amount" SortExpression="amount">
  25. <EditItemTemplate>
  26. <asp:TextBox ID="txtAmount" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
  27. </EditItemTemplate>
  28. <ItemTemplate>
  29. <asp:Label ID="Label3" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
  30. </ItemTemplate>
  31. </asp:TemplateField>
  32. </Columns>
  33. </asp:GridView>


and the RowDataBound event is


  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  2. {
  3. if (e.Row.RowType == DataControlRowType.DataRow)
  4. {
  5. TextBox txtQuantity = (TextBox)e.Row.FindControl("txtQuantity");
  6. TextBox txtPrice = (TextBox)e.Row.FindControl("txtPrice");
  7. TextBox txtAmount = (TextBox)e.Row.FindControl("txtAmount");
  8. if (txtQuantity != null)
  9. {
  10. txtQuantity.Attributes.Add("onkeyup", "CalcAmount('" + txtQuantity.ClientID + "','" + txtPrice.ClientID + "','" + txtAmount.ClientID + "')");
  11. txtPrice.Attributes.Add("onkeyup", "CalcAmount('" + txtQuantity.ClientID + "','" + txtPrice.ClientID + "','" + txtAmount.ClientID + "')");
  12. }
  13. }
  14. }


and the javascript method will look like this


  1. <script type="text/javascript">
  2. function CalcAmount(quantity, price, amount) {
  3. document.getElementById(amount).value = parseFloat(document.getElementById(quantity).value) * parseFloat(document.getElementById(price).value);
  4. }
  5. </script>

This way when the values are changed in the quantity and price textboxes,

the corresponding amount textbox updates automatically.

Thursday, July 9, 2009

icon on the tab of a website in a web broswer

how to make an icon on the tab of a website in a web broswer
Create an .ico file and add in Header section <link rel="shortcut icon" href="favicon.ico">
You can create an .ico image using this link http://www.chami.com/html-kit/services/favicon/

Getting week of the month from a Date

Getting week of the month from a DateTime variable
 // ---- GetWeekOfMonth ---------------------------
 //
 // Assuming Sunday starts a new week, get the ordinal
 // week a date is in...of the date's month
 // using Microsoft.VisualBasic;

 int GetWeekOfMonth(DateTime Date)
 {
 long Week;

 // get first day of month
 DateTime BaseDate = new DateTime(Date.Year, Date.Month, 1);

 // get difference, in weeks, between the date and first day of month
 Week = DateAndTime.DateDiff(DateInterval.WeekOfYear, 
 BaseDate, 
 Date, 
 Microsoft.VisualBasic.FirstDayOfWeek.Sunday, 
 FirstWeekOfYear.Jan1);
 
 // want it one, not zero based
 return (int)Week + 1;
 }

 // test it
 protected void Button1_Click(object sender, EventArgs e)
 {
 DateTime Date = new DateTime(2007, 3, 1);

 while (Date.Month == 3)
 {
 int Week = GetWeekOfMonth(Date);

 Response.Write(String.Format("{0:d} : {1} <BR>", Date, Week));
 Date = Date.AddDays(1);
 }
 }

RequiredFiledValidator For CheckBoxList

RequiredFiledValidator For CheckBoxList
function checkTemp(sender,args)
{
     for(var i=0;i<=document.getElementById("CheckBoxList1").firstChild.children.length-1;i++)
     {
          if(document.getElementById("CheckBoxList1").firstChild.children(i).cells(0).children(0).checked)=='true'
          args.IsValid=true
          return                    
     }
     args.IsValid=false
}
<asp:CustomValidator id="valcheckBoxTemp" runat="server" ClientValidationFunction="checkTemp" 
ErrorMessage="This is required control "></asp:CustomValidator>  


Disable Copy Command

Disable Copy Command

oncopy="return false;" onpaste="return false;" oncut="return false;"


Alternate image when the orginal image is missing

How to provide an alternate image when the orginal image is missing?

<img border=0 src='<%# (Eval("Image").ToString() != null) ? "http://www.mynewsite.com/Images/thumb/" + Eval("Image") : "path_of_dummy_image" %>' />

Finding Particular Controls in Page

Finding Particular Controls in Page
private Control FindNestedControl(Control parent, string controlid)
        {
            Control c = parent.FindControl(controlid);
            if (c != null)
                return c;
            else
            {
                foreach (Control child in parent.Controls)
                {
                    c = FindNestedControl(child, controlid);
                    if (c != null)
                        return c;
                }
            }
            return null;
        }
Eg :- DropDownList ddlMyList = FindNestedControl(this.Page," ddlMyList") as DropDownList;


EncryptString & DecryptString

EncryptString

private string EnryptString (string strEncrypted)

{

  

    byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);

    string encryptedConnectionString = Convert.ToBase64String(b);

    return encryptedConnectionString;

  

}

 

DecryptString

private string DecryptString (string encrString)

{

  

    byte[] b = Convert.FromBase64String(encrString);

  

    string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);

  

    return decryptedConnectionString;

  

}