Coding notes in my daily works (ASP.NET 1.1)
Here is some notes that recorded by myself when I work daily. They are about ASP.NET 1.1, maybe some of them can be re-used in ASP.NET 2.0 too.
1: Using "New ListItem" to Feed DropDownList Controller
dt = dbDA.DB_GetTitle("TREASURERTITLE")
If (Not dt Is Nothing) And (dt.Rows.Count > 0) Then With dt For intCounter = 0 To .Rows.Count - 1 Me.ddlTreasurerTitle.Items.Add(New ListItem(.Rows(intCounter).Item("StatusShortDesc").ToString, .Rows(intCounter).Item("StatusCode"))) Next 'Me.ddlTreasurerTitle.Items.FindByText("Treasurer").Selected = True End With End If
2: Finding a appSettings key in web.config file
If Array.IndexOf(ConfigurationSettings.AppSettings.AllKeys, "DocTemplatesPath") > -1 Then strTemplateFileNameWithPath = ConfigurationSettings.AppSettings("DocTemplatesPath") & strTemplateFileName If Not (File.Exists(strTemplateFileNameWithPath)) Then Me.lblError.Text = "No template found for selected document!" Me.lblError.ForeColor = Color.Red Return End If Else Me.lblError.Text = "Can not find the configration of template file path!" Me.lblError.ForeColor = Color.Red Return End If
3: Using Memory to save a file:
Dim memStreamTargetFile As MemoryStream = New MemoryStream Dim dbDocObj As New DocGenXML.WordXMLGen
If dbDocObj.ReplaceTextDueToDataArray_Stream(dataArray, strTemplateFileNameWithPath, nameSpaceURI, memStreamTargetFile) = True Then Response.Clear() Response.AddHeader("Content-Disposition", "attachment; filename=" & tmpTargetFileName) Response.AddHeader("Content-Length", memStreamTargetFile.Length.ToString()) Response.ContentType = "application/octet-stream"
Dim byt As Byte() = memStreamTargetFile.ToArray()
If Not IsNothing(memStreamTargetFile) Then memStreamTargetFile.Close() End If
Response.OutputStream.Write(byt, 0, byt.Length) 'Response.Flush()
Response.End() Else lblError.Text = "Error: " + "Generating document failed!" lblError.ForeColor = Color.Red End If
4: Enable or Disable all child controllers in a panel:
Private Sub ChangeChildrenControlsStatus(ByVal pnl As System.Web.UI.WebControls.Panel, ByVal enableStatus As Boolean) Dim childControl As Control 'Dim childControl As WebControl
Try For Each childControl In pnl.Controls 'CType(childControl, WebControl).Enabled = True Select Case childControl.GetType().ToString() Case GetType(System.Web.UI.WebControls.TextBox).ToString() CType(childControl, System.Web.UI.WebControls.TextBox).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.Button).ToString() CType(childControl, System.Web.UI.WebControls.Button).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.DropDownList).ToString() CType(childControl, System.Web.UI.WebControls.DropDownList).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.RequiredFieldValidator).ToString() CType(childControl, System.Web.UI.WebControls.RequiredFieldValidator).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.RegularExpressionValidator).ToString() CType(childControl, System.Web.UI.WebControls.RegularExpressionValidator).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.RangeValidator).ToString() CType(childControl, System.Web.UI.WebControls.RangeValidator).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.CompareValidator).ToString() CType(childControl, System.Web.UI.WebControls.CompareValidator).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.Label).ToString() CType(childControl, System.Web.UI.WebControls.Label).Enabled = enableStatus Case GetType(System.Web.UI.WebControls.CheckBox).ToString() CType(childControl, System.Web.UI.WebControls.CheckBox).Enabled = enableStatus
End Select Next
pnl.Enabled = True Catch ex As Threading.ThreadAbortException Catch ex As Exception Try cnnstr = conn.GetConnectionString(DBTypes.LMS) exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), "LoansODR", "DebentureDocsGen.aspx.vb", "ChangeChildrenControlsStatus", "System", "1", ex.StackTrace, ex.Message) Catch End Try
5: Getting a date in its words format
for example: the 1st day of July, 2007
Public Function GetDateInWords(ByVal inDateTime As DateTime) As String Dim strDaySuffix As String Try
Select Case inDateTime.Day Case 1, 21, 31 strDaySuffix = "st" Case 2, 22 strDaySuffix = "nd" Case 3, 23 strDaySuffix = "rd" Case Else strDaySuffix = "th" End Select
Return ("the " & inDateTime.Day.ToString() & strDaySuffix & " day of " & inDateTime.ToString("MMMM, yyyy"))
Catch ex As Threading.ThreadAbortException Catch ex As Exception Try cnnstr = conn.GetConnectionString(DBTypes.LMS) exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), "LoansODR", "DebentureDocsGen.aspx.vb", "GetDateInWords", "System", "1", ex.StackTrace, ex.Message) Catch End Try Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), "DebentureDocsGen.GetDateInWords") End Try End Function Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), "DebentureDocsGen.ChangeChildrenControlsStatus") End Try End Sub
6: if the day < 15, return date 1, else, return date 15
Public Function Get1stOr15thDate(ByVal inDateTime As DateTime, ByVal months As Integer) As Date Try If inDateTime.Day > 0 And inDateTime.Day < 15 Then Return inDateTime.AddMonths(months).AddDays(0 - inDateTime.Day + 1) Else Return inDateTime.AddMonths(months).AddDays(0 - inDateTime.Day + 15) End If Catch ex As Threading.ThreadAbortException Catch ex As Exception Try cnnstr = conn.GetConnectionString(DBTypes.LMS) exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), "LoansODR", "DebentureDocsGen.aspx.vb", "Get1stOr15thDate", "System", "1", ex.StackTrace, ex.Message) Catch End Try Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), "DebentureDocsGen.Get1stOr15thDate") End Try End Function
Public Function Get1stOr15thDayString(ByVal inDateTime As DateTime, ByVal months As Integer) As String Try If inDateTime.Day > 0 And inDateTime.Day < 15 Then Return inDateTime.AddMonths(months).AddDays(0 - inDateTime.Day + 1).Day.ToString + "st" Else Return inDateTime.AddMonths(months).AddDays(0 - inDateTime.Day + 15).Day.ToString + "th" End If Catch ex As Threading.ThreadAbortException Catch ex As Exception Try cnnstr = conn.GetConnectionString(DBTypes.LMS) exHandler.ER_InsertError(cnnstr, System.Environment.UserName(), "LoansODR", "DebentureDocsGen.aspx.vb", "Get1stOr15thDayString", "System", "1", ex.StackTrace, ex.Message) Catch End Try Me.PublishException(New Ofa.Framework.Exceptions.GlobalException(ex.Message, ex), "DebentureDocsGen.Get1stOr15thDayString") End Try End Function
7: Using IndexOf to find a substring in a string:
strSelectedTemplateFileName = Me.lbDocList.SelectedItem.Value.Substring(Me.lbDocList.SelectedItem.Value.IndexOf("", 0) + 1) strSelectedTemplateFileName = strSelectedTemplateFileName.Substring(strSelectedTemplateFileName.IndexOf("", 0) + 1)
8: Getting the next N business days, N > 0 , N = 0, N < 0 :
Because holidays is always variable due to different country and different new policy. so we have to create a data table to store holidays, but , we don't need to store weekends.
then I check the datatable to determine whether the day is in the holidays datable, and then, I caculate them using the following functions:
public static DateTime GetBusinessDate(DateTime StartDate, double DurationBusinessDays) { int c = 0;
DateTime resultBusinessDate;
if(DurationBusinessDays == 0) resultBusinessDate = StartDate; else { //theNextBusinessDate = StartDate.AddDays(DurationBusinessDays);
//resultBusinessDate = StartDate;
if(DurationBusinessDays > 0) { do { resultBusinessDate = StartDate.AddDays(1); if(IsBusinessDay(resultBusinessDate)) c++; StartDate = resultBusinessDate; } while (c < (int)(Math.Abs(DurationBusinessDays))); } else { do { resultBusinessDate = StartDate.AddDays(-1); if(IsBusinessDay(resultBusinessDate)) c++; StartDate = resultBusinessDate; } while (c < (int)(Math.Abs(DurationBusinessDays))); }
}
return resultBusinessDate; }
public static bool IsBusinessDay(DateTime dt) { if ((dt.DayOfWeek == DayOfWeek.Saturday) || (dt.DayOfWeek == DayOfWeek.Sunday) || (IsHoliday(dt))) { return false; } else { return true; } }
public static bool IsHoliday(DateTime dt) { LMSDataAccess.DataConnection oConn = null; string strConString; SqlConnection conn = null; SqlCommand sqlCmd = null; SqlDataAdapter sqlDA = null; DataSet sqlDS = null; //int i; bool retV = false; //DataRow[] drs = null;
try { oConn = new LMSDataAccess.DataConnection(); strConString = oConn.GetConnectionString((int)LMSDataAccess.DBTypes.LMS); conn = new SqlConnection(strConString); sqlCmd = new SqlCommand("procGetHolidayList", conn); sqlCmd.CommandType = CommandType.StoredProcedure; //sqlCmd.Parameters.Add("@InDate", InDate); sqlCmd.Parameters.Add("@CountryShortName1", "CA"); conn.Open(); sqlDS = new DataSet(); sqlDA = new SqlDataAdapter(sqlCmd); sqlDA.Fill(sqlDS);
//for debug //dt = new DateTime(2007,1,1);
if(sqlDS.Tables[0].Rows.Count > 0) { /* for(i=0; i<sqlDS.Tables[0].Rows.Count; i++) { if(dt == (DateTime)sqlDS.Tables[0].Rows[i][0]) { retV = true; //Is holiday break; } } */ //drs = sqlDS.Tables[0].Select("Author = 'Name'"); sqlDS.Tables[0].DefaultView.Sort=sqlDS.Tables[0].Columns[0].ColumnName+" asc"; if(sqlDS.Tables[0].DefaultView.Find(dt) > 0) retV = true; //Is holiday
} else retV = false; } catch(System.Exception objexc) { throw objexc; } finally { sqlDS.Dispose(); sqlDA.Dispose(); sqlCmd.Dispose(); conn.Close(); conn.Dispose(); conn = null; oConn = null;
}
return retV; }
**Store Procedure: **
procGetHolidayList:
SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO
/=============================================================== -- Creation Date: 22 Jan 2007 -- Author: -- Description: Get the holidays list due to Country -- Tables: CalDates -- Last Update: Revisions: ===============================================================/ ALTER PROCEDURE dbo.procGetHolidayList @CountryShortName1 varchar(2)= null AS SET NOCOUNT ON
select CD.CalDate from CalDates CD join CalLongNames CLN on CD.CalID = CLN.CalKey where Deleted = 0 and ( CLN.CalShortName = @CountryShortName1 )
GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
9: 2 small functions about data storing
Public Function ReturnDBNullWhenNonNumeric(ByVal Input As String) As Object If IsNumeric(Input) Then Return CType(Input, Decimal) Else Return (DBNull.Value) End If End Function
Public Function ReturnZeroWhenNonNumeric(ByVal Input As String) As Decimal If IsNumeric(Input) Then Return CType(Input, Decimal) Else Return (0) End If End Function