|
|
|
| .Net 1.0 : Application Log |
Imports System.Diagnostics
Dim MyLog As New EventLog
If Not MyLog.SourceExists("MyService") Then
MyLog.CreateEventSource("MyService", "Myservice Log")
End If
MyLog.Source = "MyService"
MyLog.WriteEntry("MyService Log", "This is log on " & CStr(TimeOfDay), EventLogEntryType.Information)
|
| Jump to Top |
| .Net 1.0 : ArrayList |
Dim roles As New ArrayList()
roles.Add("Administrators")
roles.Add("ContentManagers")
Dim objItem As Object objItem = roles.Item(0)
|
| Jump to Top |
| .Net 1.0 : Background Color |
SomeControl.BackColor = Color.FromArgb(255, 252, 247)
SomeControl.BackColor = Color.Gray
SomeControl.BackColor = Color.FromArgb( &hFF, &h00, &hFF )
Dim myColor = ColorTranslator.FromHtml("#ff00ff")
SomeControl.BackColor = myColor
Dim myColor = "#ff00ff"
SomeControl.BackColor = ColorTranslator.FromHtml(myColor)
|
| Jump to Top |
| .Net 1.0 : Bitwise |
If ((m_iRole And 8) = 8) Then
' User is an admin...
Else
' Not an admin...
End If
|
| Jump to Top |
| .Net 1.0 : Cache |
| Page |
<%@OutputCache Duration="60" VaryByParam="none" %>
|
| Jump to Top |
| JavaScript : Calendar |
| PAGE |
<td valign="top">
<asp:TextBox ID="txtDate" Width="100" MaxLength="10" runat="server" />
</td>
<td>
<a href="javascript:calendar_window=window.open('Calendar.aspx?formname=Form1.txtDate','calendar_window',
'width=175,height=210');calendar_window.focus()" class="calendar"><img src="images/cal.gif"
border="0"></a>
</td>
|
| CALENDAR |
<asp:Calendar id="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"
OnDayRender="Calendar1_dayrender"
ShowTitle="true" DayNameFormat="FirstTwoLetters"
SelectionMode="Day" BackColor="#ffffff"
FirstDayOfWeek="Monday" BorderColor="#000000"
ForeColor="#00000" Height="60" Width="120">
<TitleStyle backcolor="#000080" forecolor="#ffffff" />
<NextPrevStyle backcolor="#000080" forecolor="#ffffff" />
<OtherMonthDayStyle forecolor="#c0c0c0" />
</asp:Calendar>
|
| Jump to Top |
| .Net 1.0 : Call Page |
Call GetWebPageAsStringShort2("http://results.test.com/Search.aspx?reset=true")
Function GetWebPageAsStringShort2(ByVal strURI As String) As String
With System.Net.WebRequest.Create(New Uri(strURI)).GetResponse()
With New System.IO.StreamReader(.GetResponseStream())
GetWebPageAsStringShort2 = .ReadToEnd()
End With
End With
End Function
|
| Jump to Top |
| .Net 1.0 : Collection |
Protected Function DropDownListReminder() As cDropDownList
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Populates a DropDownList from a Collection and returns the DDL.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oRetVal As New cDropDownList
Dim f_oItemCollection As New ListItemCollection
f_oItemCollection.Add(New ListItem("15 minutes before", "15"))
f_oItemCollection.Add(New ListItem("30 minutes before", "30"))
f_oItemCollection.Add(New ListItem("1 hour before", "60"))
f_oItemCollection.Add(New ListItem("2 hours before", "120"))
f_oItemCollection.Add(New ListItem("4 hours before", "240"))
f_oItemCollection.Add(New ListItem("one day before", "1440"))
f_oItemCollection.Add(New ListItem("two days before", "2880"))
f_oItemCollection.Add(New ListItem("three days before", "4320"))
f_oItemCollection.Add(New ListItem("four days before", "5760"))
f_oItemCollection.Add(New ListItem("five days before", "7200"))
f_oItemCollection.Add(New ListItem("one week before", "10080"))
f_oItemCollection.Add(New ListItem("two weeks before", "20160"))
f_oRetVal.DataSource = f_oItemCollection
f_oRetVal.DataBind()
Return f_oRetVal
End Function
|
| Jump to Top |
| .Net 1.0 : Confirm Popup |
btnDelete.Attributes.Add("OnClick", "return confirm('Are you sure you want to delete "
& Replace(DgInQueue.SelectedItem.Cells(11).Text.ToString, "'", "\'", , , CompareMethod.Text) & "?')")
|
| Jump to Top |
| .Net 1.0 : Conn String |
| Web.config - Access |
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=d:\website\my.mdb;Provider=Microsoft.Jet.OLEDB.4.0"></add>
</appSettings>
<system.web>
...
</system.web>
</configuration>
|
| Web.config - SQL |
<appSettings>
<add key="ConnectionString" value="SERVER=INTERNETDB;INITIAL CATALOG=MYDB;USER ID=sa;PASSWORD=111111" />
</appSettings>
|
| Code |
Public Function GetProductsNew() As DataSet
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Gets new products from DB.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim f_oCommand As New SqlDataAdapter("CMRC_ProductsNew", f_oConnection)
f_oCommand.SelectCommand.CommandType = CommandType.StoredProcedure
Dim f_iParameterMerchantID As SqlParameter = New SqlParameter("@MerchantID", SqlDbType.Int, 4)
f_iParameterMerchantID.Value = 1
f_oCommand.SelectCommand.Parameters.Add(f_iParameterMerchantID)
f_oConnection.Open()
Dim f_oResult As New DataSet
f_oCommand.Fill(f_oResult, "NewProductList")
f_oConnection.Close()
Return f_oResult
End Function
|
| Jump to Top |
| .Net 1.0 : Cookies |
' Separate
Response.Cookies("UserInfo_UserID").Value = txtUserID.Text
Response.Cookies("UserInfo_UserName").Value = txtUserName.Text
' Multiple values
Response.Cookies("UserInfo")("UserID") = f_oUser.UserID
Response.Cookies("UserInfo")("UserName") = f_oUser.UserName
Response.Cookies("UserInfo").Expires = DateTime.Now.AddDays(1)
' Other
Dim f_oCookie As New HttpCookie("Preferences")
f_oCookie.Values.Add("FavoriteColor", "Blue")
Response.AppendCookie(f_oCookie)
' Exists
If Not (Request.Cookies("DealID")) Is Nothing Then
f_sDealID = Request.Cookies("DealID").Value
Else
Response.Redirect("ErrorPage.aspx")
End If
' Expire
Response.Cookies("DealAppID").Expires = DateTime.Now.AddDays(-1)
|
| Jump to Top |
| .Net 1.0 : Data Providers |
The .NET Framework includes two data providers for accessing enterprise databases,
the OLE DB .NET data provider and the SQL Server .NET data provider.
(1) Create a database connection using the SqlConnection class.
(2) Select a set of records from the database using the SqlDataAdapter class.
(3) Fill a new DataSet using the SqlDataAdapter class.
(4) If you are selecting data from a database for non-interactive display only, it is
recommended that you use a read-only, forward-only SqlDataReader (or OleDbDataReader
for non-SQL databases) for best performance.
(5) Bind a server control, such as a DataGrid, to the DataSet, SqlDataReader, or DataView.
|
| Jump to Top |
| .Net 1.0 : DataGrid |
| Code Behind |
Protected WithEvents grdProducts As System.Web.UI.WebControls.DataGrid
Protected WithEvents pnlNoData As System.Web.UI.WebControls.Panel
Private Property SortField() As String
Get
Dim f_oSortField As Object = ViewState("SortField")
Dim f_sSortField As String
If f_oSortField Is Nothing Then
f_sSortField = "Name"
Else
f_sSortField = ViewState("SortField")
End If
Return f_sSortField
End Get
Set(ByVal Value As String)
ViewState("SortField") = Value
End Set
End Property
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
If Page.IsPostBack = False Then
Call FillDataGrid()
End If
End Sub
Private Sub FillDataGrid()
Dim f_oStore As 12Bravo.Store = New 12Bravo.Store
grdProducts.DataSource = f_oStore.ProductsGet(m_iUserID, Me.MerchantID, Me.SortField)
grdProducts.DataBind()
If grdProducts.Items.Count <> 0 Then
grdProducts.Visible = True
pnlNoData.Visible = False
Else
grdProducts.Visible = False
pnlNoData.Visible = True
End If
f_oStore = Nothing
End Sub
Sub ProductDelete(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) _
Handles grdProducts.DeleteCommand
Dim keyValue As String = CStr(MyList.DataKeys(e.Item.ItemIndex))
Dim f_oConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim f_oCommand As New SqlCommand("spProductDelete", f_oConnection)
f_oCommand.CommandType = CommandType.StoredProcedure
Dim retValue As SqlParameter = f_oCommand.Parameters.Add("RetValue", SqlDbType.Int)
retValue.Direction = ParameterDirection.ReturnValue
f_oCommand.Parameters.Add("@ProductID", SqlDbType.VarChar, 20).Value = keyValue
f_oConnection.Open()
f_oCommand.ExecuteNonQuery()
f_oConnection.Close()
Select Case retValue.Value
Case 0
lblMessage.Text = "Product deletion was successful."
FillDataGrid()
Case Else
lblMessage.Text = "Product deletion failed."
End Select
End Sub
Sub ProductEdit(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) _
Handles MyList.EditCommand
Dim f_skeyValue As String = CStr(MyList.DataKeys(e.Item.ItemIndex))
Response.Redirect("AddEditProduct.aspx?PID=" & f_skeyValue)
End Sub
Sub ChangePage(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
grdProducts.CurrentPageIndex = e.NewPageIndex
Call FillDataGrid()
End Sub
Sub SortResults(ByVal sender As Object, ByVal e As DataGridSortCommandEventArgs)
grdProducts.CurrentPageIndex = 0
If Me.SortField = e.SortExpression Then
Me.SortField = e.SortExpression & " DESC"
Else
Me.SortField = e.SortExpression
End If
FillDataGrid()
End Sub
|
| Page |
<asp:DataGrid id="grdProducts" Width="550" BorderColor="#999999" GridLines="Vertical" cellpadding="3"
AutoGenerateColumns="False" AllowPaging="True" PageSize="12" OnPageIndexChanged="ChangePage" AllowSorting="True"
OnSortCommand="SortResults" DataKeyField="ProductID" OnDeleteCommand="ProductDelete" OnEditCommand="ProductEdit"
runat="server">
<AlternatingItemStyle BackColor="#eff5ff" />
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" BackColor="#EEEEEE" />
<Columns>
<asp:HyperLinkColumn HeaderText="Details" DataTextField="ProductID" DataNavigateUrlField="ProductID"
DataNavigateUrlFormatString="Details.aspx?PID={0}" />
<asp:BoundColumn DataField="Name" HeaderText="Name" SortExpression="Name"></asp:BoundColumn>
<asp:BoundColumn DataField="Price" HeaderText="Price" SortExpression="Price" DataFormatString="{0:c}">
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle Wrap="False" HorizontalAlign="Right" />
</asp:BoundColumn>
<asp:BoundColumn DataField="DateAdded" HeaderText="Date Added" DataFormatString="{0:MM/dd/yyyy}" />
<asp:TemplateColumn HeaderText="Status">
<ItemTemplate>
<asp:Label id="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "Status") %>'
runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:ButtonColumn HeaderText="Edit" Text="Edit" CommandName="Edit" />
<asp:ButtonColumn HeaderText="Delete" Text="Delete" CommandName="Delete" />
</Columns>
<PagerStyle Position="TopAndBottom" Mode="NumericPages" />
</asp:DataGrid>
<asp:Panel ID="pnlNoData" Runat="server">
There are no products to display.
</asp:Panel>
|
| Jump to Top |
| .Net 1.0 : DataReader |
| Data |
Imports System.Data
Imports System.Data.SqlClient
Namespace Store
Public Class Survey
Public Function Surveys_List(ByVal vMID As Integer) As SqlDataReader
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Gets all surveys from DB related to MerchantID.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim f_oCommand As SqlCommand = New SqlCommand("sp_SurveysList", f_oConnection)
f_oCommand.CommandType = CommandType.StoredProcedure
Dim f_iMID As SqlParameter = New SqlParameter("@MID", SqlDbType.Int, 4)
f_iMID.Value = vMID
f_oCommand.Parameters.Add(f_iMID)
f_oConnection.Open()
Dim f_oResult As SqlDataReader = f_oCommand.ExecuteReader(CommandBehavior.CloseConnection)
f_oConnection = Nothing
f_oCommand = Nothing
Return f_oResult
End Function
End Class
End Namespace
|
| Code |
Dim f_oSurvey As Store.Me.Survey = New Store.Me.Survey
drpSurveys.DataSource = f_oSurvey.Surveys_List(2)
drpSurveys.DataBind()
|
| Page |
<asp:listbox id="drpSurveys" Rows="1" DataTextField="SurveyName" DataValueField="SurveyID" Runat="server" />
|
| Code - Loop Through |
Dim f_oDataReader As SqlDataReader
While f_oDataReader.Read()
f_bReturn = EmailResponseSend(f_oDataReader(1).ToString(), f_oDataReader(2).ToString())
End While
|
| Jump to Top |
| .Net 1.0 : DataSet |
Imports System.Data
Imports System.Data.SqlClient
Namespace ADC
Public Class Card
Public Function CardsGet(ByVal vUserID As Integer) As DataSet
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Get card activations for merchants associated with the user.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim f_oCommand As New SqlDataAdapter("sp_CardsGet", f_oConnection)
f_oCommand.SelectCommand.CommandType = CommandType.StoredProcedure
Dim f_iUserID As New SqlParameter("@User_ID", SqlDbType.Int, 4)
f_iUserID.Value = vUserID
f_oCommand.SelectCommand.Parameters.Add(f_iUserID)
f_oConnection.Open()
Dim f_oResult As New DataSet
f_oCommand.Fill(f_oResult, "ActivationsList")
f_oConnection.Close()
Return f_oResult
End Function
End Class
End Namespace
|
| Write to XML file |
Dim myData As New DataSet
...
myData.WriteXml("TestXML.txt")
|
| Jump to Top |
| .Net 1.0 : DataTable |
| Data |
Function SP_rpt_usp_ClientSummary_GET(ByRef RETURN_VALUE As Int32, ByVal v_iClientID As Int32) As DataTable
Dim oRetVal As DataTable
Dim oDBCommand As New cDBCommand
Dim f_sConnString As String = ConfigurationSettings.AppSettings("ConnectionString")
oDBCommand.ConnectionString = f_sConnString
With oDBCommand
.AddParam("@RETURN_VALUE", SqlDbType.Int, 0, ParameterDirection.ReturnValue, RETURN_VALUE)
.AddParam("@v_iClientID", SqlDbType.Int, 0, ParameterDirection.Input, v_iClientID)
End With
oDBCommand.ExecuteReader("rpt_usp_ClientSummary_GET", CommandType.StoredProcedure)
oRetVal = CType(oDBCommand.CreateDataTable(), DataTable)
If oDBCommand.DataReader.HasRows Then
RETURN_VALUE = 0
Else
RETURN_VALUE = CType(oDBCommand.GetParamValue("@RETURN_VALUE"), Int32)
End If
oDBCommand.Close()
oDBCommand = Nothing
Return oRetVal
End Function
|
| Code |
grdSummary.DataSource = f_oBOReport.ClientSummaryReportGet(m_iClientID)
Public Function ClientSummaryReportGet(ByRef vClientID As Integer) As DataTable
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Get summary report for a specific client.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_iReturn As Integer = -99
Dim f_oDataTable As DataTable
f_oDataTable = SP.SP_rpt_usp_ClientSummary_GET(f_iReturn, vClientID)
If f_iReturn = 0 Then
Return f_oDataTable
End If
End Function
|
| Jump to Top |
| .Net 1.0 : Dates |
| ToString |
' D - day, DD - pad day, M - month, MM - pad month, MMM - short month name,
' MMMM - full month name, YY - short year, YYYY - full year
' July
lblCurrentMonth.Text = Date.Today.ToString("MMMM")
' Hour
If DateTime.Now.ToString("HH") = 20 Then
|
| DateAdd |
' Wednesday, July 26, 2006
lblCurrentDate.Text = DateAdd("d", -1, Date.Today).ToLongDateString
|
| Jump to Top |
| .Net 1.0 : Delegate |
| More Info: 15Seconds.com |
|
A delegate is a special class that represents a method signature. They are used
to implement callbacks and events in VB.Net (EX: "Notify me when it is my turn to").
|
| Jump to Top |
| .Net 1.0 : DLL |
| Assembly Registration Tool - Register |
C:\Windows\Microsoft.NET\Framework\v1.1.4322\regasm.exe COMPANY.SelectPayment.dll /tlb:COMPANY.SelectPayment.tlb
|
| Assembly Registration Tool - Un-Register |
C:\Windows\Microsoft.NET\Framework\v1.1.4322\regasm.exe /unregister COMPANY.SelectPayment.dll
|
| Jump to Top |
| .Net 1.0 : Download |
|
Download .NET Framework Redistributable Now (21 MB)
MSDN: .NET Framework Service Pack 2
|
| Jump to Top |
| .Net 1.0 : Dropdown |
| Collection |
Protected Function DropDownListNumeric(ByVal v_iStart As Integer, ByVal v_iEnd As Integer) As cDropDownList
Dim f_oRetVal As New cDropDownList
Dim f_oItemCollection As New ListItemCollection
Dim f_oItem As ListItem
For i As Integer = v_iStart To v_iEnd
f_oItem = New ListItem(Convert.ToString(i))
f_oItemCollection.Add(f_oItem)
Next
f_oRetVal.DataSource = f_oItemCollection
f_oRetVal.DataBind()
Return f_oRetVal
End Function
|
| Create in Code Behind |
Protected Sub DropDownListReminder()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Creates a dropdown for reminders.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oDD As New DropDownList
f_oDD.Items.Add(New ListItem("15 minutes before", "15"))
Dim f_oForm As Control = FindControl("Form1")
f_oForm.Controls.Add(f_oDD)
End Sub
|
| Insert Item |
Dim f_oReport As 12Bravo.Report = New 12Bravo.Report
drpMerchantList.DataSource = f_oReport.StoresGet(m_iUserID, f_bShowAll)
drpMerchantList.DataBind()
drpMerchantList.Items.Insert(0, New ListItem("-- All Merchants --", "0"))
|
| Bind |
Dim f_oProducts As OCDE.Store.ProductsDB = New OCDE.Store.ProductsDB
CharacterId1.DataSource = f_oProducts.GetProductCharacters1()
CharacterId1.DataTextField = "CharacterName"
CharacterId1.DataValueField = "CharacterId"
CharacterId1.DataBind()
CharacterId1.Items.Insert(0, New ListItem("Property A-G", "0"))
f_oProducts = Nothing
|
| Selected - Page |
<ItemTemplate>
<asp:DropDownList ID="drpItemStatus"
SelectedIndex='<%# GetSelectedStatus(DataBinder.Eval(Container.DataItem, "ItemStatus")) %>'
Runat="server">
<asp:ListItem Value="Available">Available</asp:ListItem>
<asp:ListItem Value="Coming Soon">Coming Soon</asp:ListItem>
<asp:ListItem Value="Out of Stock">Out of Stock</asp:ListItem>
<asp:ListItem Value="New">New</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
|
| Selected - Code Behind |
Public Function GetSelectedStatus(ByVal vStatus As String) As Integer
Select Case LCase(vStatus)
Case "available"
Return = 0
Case "coming soon"
Return = 1
Case "out of stock"
Return = 2
Case "new"
Return = 3
End Select
End Function
|
| Jump to Top |
| .Net 1.0 : Email |
Imports System.Web.Mail
Dim objEmail As New MailMessage
objEmail.To = "aaa@aaa.com"
objEmail.From = "bbb@bbb.com"
objEmail.Subject = "Email Test"
objEmail.BodyFormat = MailFormat.Html
SmtpMail.SmtpServer = "127.0.0.1"
objEmail.Body = "hello"
SmtpMail.Send(objEmail)
|
| Setup |
(1) Grant IP in relay "127.0.0.1"
(2) make sure Anonymous access is allowed (and only one checked)
(3) stop/re-start SMTP service
|
| Jump to Top |
| .Net 1.0 : ErrorHandler |
Imports System.IO
Private Sub DailyEmail()
On Error GoTo ErrorHandler
' ...
Exit Sub
ErrorHandler:
' Log to error file
Dim f_sFileName As String = "e:\\ErrorLog\nws_errors.txt"
Dim f_oStreamWriter As StreamWriter
f_oStreamWriter = File.AppendText(f_sFileName)
f_oStreamWriter.WriteLine("NWS: Error sending email: " & dr.Item("email") & ": " & Now())
Resume Next
End Sub
|
| Jump to Top |
| .Net 1.0 : Files |
| Directory : DataGrid |
Imports System.IO
Private Sub FillDataGrid()
Dim f_oDirInfo As New DirectoryInfo(Server.MapPath("downloads/availability"))
MyList.DataSource = f_oDirInfo.GetFiles("*")
MyList.DataBind()
If MyList.Items.Count <> 0 Then
MyList.Visible = True
pnlNoData.Visible = False
Else
MyList.Visible = False
pnlNoData.Visible = True
End If
f_oDirInfo = Nothing
End Sub
|
<asp:DataGrid id="MyList" width="100%" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:HyperLinkColumn HeaderText="File Name" DataTextField="Name" DataNavigateUrlField="Name"
DataNavigateUrlFormatString="downloads/availability/{0}" Target="new"/>
<asp:BoundColumn HeaderText="Last Write Time" DataField="LastWriteTime" DataFormatString="{0:d}" />
<asp:BoundColumn HeaderText="File Size" DataField="Length" DataFormatString="{0:#,### bytes}" />
</Columns>
</asp:DataGrid>
<asp:Panel ID="pnlNoData" Runat="server">
<font face="Arial, Helvetica, sans-serif" size="2">
<br>
There are no files to display for this category.
</font>
</asp:Panel>
|
| Upload |
<input id="filMyFile" type="file" runat="server" name="filMyFile">
Protected WithEvents filMyFile As System.Web.UI.HtmlControls.HtmlInputFile
If Not filMyFile.PostedFile Is Nothing And filMyFile.PostedFile.ContentLength > 0 Then
Dim f_sFileName As String = System.IO.Path.GetFileName(filMyFile.PostedFile.FileName)
Dim SaveLocation As String = Server.MapPath("Files") & "\" & f_sFileName
Try
filMyFile.PostedFile.SaveAs(SaveLocation)
lblMessage.Text = "The file has been uploaded."
Catch Exc As Exception
lblMessage.Text = "Error: " & Exc.Message
End Try
Else
lblMessage.Text = "Please select a file to upload."
End If
|
| Create/Write To |
Imports System.IO
Dim f_sFileName As String = f_sFirstName & "_" & f_sLastName & ".txt"
' True = Append to existing, False = do not append
Dim objWriter As New StreamWriter(f_sFileName, False)
objWriter.WriteLine("First Name: " & txtFirstName.Text.Trim
objWriter.Close())
|
| Create/Write To |
Public Sub AddToFile(ByVal contents As String)
' Set up a filestream
Dim fs As New FileStream("c:\InterfaceTestLog.txt", FileMode.OpenOrCreate, FileAccess.Write)
' Set up a streamwriter for adding text
Dim sw As New StreamWriter(fs)
' Find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End)
' Add the text
sw.WriteLine(contents)
'add the text to the underlying filestream
sw.Flush()
' Close the writer
sw.Close()
End Sub
|
| Jump to Top |
| .Net 1.0 : Format |
| Date/Time |
<!-- DataGrid -->
<%# DataBinder.Eval(Container.DataItem, "ScheduleStartDate", "{0:d}") %>
<asp:BoundColumn HeaderText="Date" DataField="Trxn_Date" DataFormatString="{0:MM/dd/yy}" />
' 24 Hour
DataFormatString="{0:MM/dd/yy HH:mm}"
' AM/PM
DataFormatString="{0:MM/dd/yy hh:mm tt}"
' Server Controls
lblTime.Text = String.Format("{0:T}", rightNow)
lblDate.Text = String.Format("{0:d}", rightNow)
' Variable: September 20, 2005
f_dDate1.ToString("MMMM dd, yyyy")
|
| Numbers |
<!-- DataGrid -->
<%# DataBinder.Eval(Container.DataItem, "ItemCost", "{0:c}") %>
<asp:BoundColumn HeaderText="Date" DataField="Trxn_Date" DataFormatString="{0:c}" />
<asp:BoundColumn HeaderText="Date" DataField="Trxn_Date" DataFormatString="{0:c4}" />
' Server Control
lblPrice.Text = String.Format("{0:c}", price)
lblBigInt.Text = String.Format("{0:#,###}", bigNumber)
|
| Files |
<!-- File Size -->
<asp:BoundColumn DataField="Length" HeaderText="File Size" DataFormatString="{0:#,### bytes}" />
|
| Jump to Top |
| .Net 1.0 : Hashtable |
| Populate a Dropdown |
Dim myHashTable as new System.Collections.Hashtable()
myHashTable("GA") = "Georgia"
myHashTable("FL") = "Florida"
myHashTable("AL") = "Alabama"
For each Item in myHashTable
Dim newListItem as new ListItem()
newListItem.Text = Item.Value
newListItem.Value = Item.Key
DropDownList1.Items.Add(newListItem)
Next
|
| Jump to Top |
| .Net 1.0 : Hyperlink |
| DataGrid |
<asp:HyperLinkColumn HeaderText="Card #" DataTextField="CardSN" DataNavigateUrlField="CardSN"
DataNavigateUrlFormatString="CardSearch.aspx?CardSN={0}" />
<asp:HyperLinkColumn HeaderText="Details" Text="Details" DataNavigateUrlField="ScheduleID"
DataNavigateUrlFormatString="Details.aspx?ScheduleID={0}" />
<asp:TemplateColumn HeaderText="Sign-Up">
<ItemTemplate>
<div align="center">
<a href="CartAdd.aspx?PID=<%# DataBinder.Eval(Container.DataItem, "ProductID") %>">
Add To Cart
</a>
</div>
</ItemTemplate>
</asp:TemplateColumn>
|
| Jump to Top |
| .Net 1.0 : JavaScript |
| RegisterStartupScript - Window.Open |
Dim f_sNewWindow As String = "<script language='javascript'>window.open('http://results.test.com/
Search.aspx?reset=true')</script>"
RegisterStartupScript("newopen", f_sNewWindow)
|
| Jump to Top |
| .Net 1.0 : Linebreak |
Replace(txtMessage.Text.Trim, vbCrLf, "<br>")
<%# DataBinder.Eval(Container.DataItem, "Memo").Replace(Chr(13), "<br>") %>
' Display properly
<%# DataBinder.Eval(Container.DataItem, "Obituary").Replace(Chr(13), " ") %>
' Display properly in a textbox
txtDescription.Text = Replace(Trim(f_oCardDetails.Tables("CardDetailsList").Rows(0).Item("CardDescription")), "<br>", vbCrLf)
|
| Jump to Top |
| .Net 1.0 : Literal Control |
| A Literal Web Server control doesn't have any visual appearance on a Web Form but is used to insert literal text into a Web Form. This control makes it possible to add HTML code. |
Private Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnSubmit.Click
Dim i As Integer
' Get survey id
Dim f_iSurveyID As String = drpSurveys.SelectedValue
' Survey questions
Dim f_oSurveyQuestions As DataSet = f_oSurvey.SurveyQuestions_Get(CInt(f_iSurveyID))
For i = 0 To f_oSurveyQuestions.Tables("QuestionsList").Rows.Count - 1
Dim lcHTML = New LiteralControl
lcHTML.Text = "<b>" & f_oSurveyQuestions.Tables("QuestionsList").Rows(i).Item("ShortQ") & "</b><br>"
pnlQuestions.Controls.Add(lcHTML)
TempID = f_oSurveyQuestions.Tables("QuestionsList").Rows(i).Item("SurveyQuestionID")
' Spacer
Dim lcHTML2 = New LiteralControl
lcHTML3.Text = "<br><br>"
pnlQuestions.Controls.Add(lcHTML2)
Next
End Sub
|
| Jump to Top |
| .Net 1.0 : Login |
FormsAuthentication.RedirectFromLoginPage(f_iUserID, False)
' Another way...
FormsAuthentication.SetAuthCookie(f_iUserID, False)
Response.Redirect("Secure/BackOffice.aspx")
|
' Check if logged in
If Request.IsAuthenticated = True Then
lnkAdmin.Visible = True
Else
lnkAdmin.Visible = False
End If
|
| Jump to Top |
| .Net 1.0 : Logout |
FormsAuthentication.SignOut()
Response.Redirect("Login.aspx")
|
| Jump to Top |
| .Net 1.0 : NULL |
lblIssuedBy.Text = NullTerminator(f_oCardDetails.Tables("CardDetailsList").Rows(0).Item("DBA_Name"))
Function NullTerminator(ByVal vValue) As String
If vValue Is DBNull.Value Then
Return String.Empty
Else
Return vValue
End If
End Function
|
| Jump to Top |
| .Net 1.0 : Overload |
|
With VB.NET's method overloading feature, VB programmers don't have to come up
with different names for methods that basically do the same thing but differ in
their argument lists. For example, you may create a method called GetPersonInfo()
that could get a person's information based on different arguments, such as last
name, personid, and social security number. The arguments list must be different
in overloaded methods. You can't have two methods that each has an argument of the
same data type but a different argument name.
|
| More Info: Devx.com |
| More Info: Learn Visual Studio.Net Video 2103 |
Public Overloads Function GetPersonInfo(ByVal v_sFirstName As String)
End Function
Public Overloads Function GetPersonInfo(ByVal v_lPersonId As Long)
End Function
|
| Jump to Top |
| .Net 1.0 : Pagination |
| Page |
<asp:DataGrid id="MyList" AllowPaging="True" OnPageIndexChanged="ChangePage" PageSize="12">
<Columns>
</Columns>
<PagerStyle Position="Bottom" BackColor="#e6e6e6" Mode="NumericPages" />
</asp:DataGrid>
|
| Code |
Sub ChangePage(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
MyList.CurrentPageIndex = e.NewPageIndex
Call FillDataGrid()
End Sub
|
| Jump to Top |
| .Net 1.0 : .Net Remoting |
|
ASP.NET based Web services can only be accessed over HTTP. .NET
Remoting can be used across any protocol. Web services work in a
stateless environment where each request results in a new object
created to service the request. .NET Remoting supports state
management options.
|
| Jump to Top |
| .Net 1.0 : Repeater |
<asp:Repeater ID="rptContacts" runat="server">
<ItemTemplate>
<%# String.Format("{0:MMMM dd, yyyy}", DataBinder.Eval(Container.DataItem, "CreatedDate")) %>
<br>
<b><%# DataBinder.Eval(Container.DataItem, "Name") %></b>
<br>
Services: <%# String.Format("{0:MMMM dd, yyyy hh:mm tt}", DataBinder.Eval(Container.DataItem, "ServiceDate")) %>
<br><br>
</ItemTemplate>
<SeparatorTemplate>
<hr>
</SeparatorTemplate>
</asp:Repeater>
|
| Jump to Top |
| .Net 1.0 : SortedList |
Dim mySortedList as new System.Collections.SortedList
Dim Item as DictionaryEntry
mySortedList("GA") = "Georgia"
mySortedList("FL") = "Florida"
mySortedList("AL") = "Alabama"
For each Item in mySortedList
Dim newListItem as new ListItem()
newListItem.Text = Item.Value
newListItem.Value = Item.Key
DropDownList1.Items.Add(newListItem)
Next
|
| Jump to Top |
| .Net 1.0 : String |
| Substring |
' 121094754 (returns 10947)
Me.DealID = Request.Params("DID").Substring(2, 5)
' 121094754 (returns 1094754)
Me.DealID = Request.Params("DID").Substring(2)
|
| Jump to Top |
| .Net 1.0 : Style |
| Form Fields |
txtFromDate.Style.Add("width", "90px")
|
| Buttons |
<asp:Button ID="btnSubmit" Text="Submit" style="font-family:Arial, Helvetica, 'sans-serif';
font-size:11px; background:#E6E6E6" runat="server" />
|
| Jump to Top |
| .Net 1.0 : Submit to Another Page |
| Code - Page 1 |
Private m_iPaymentID As Integer
Public Property GRDPaymentID() As Integer
Get
Return m_iPaymentID
End Get
Set(ByVal Value As Integer)
m_iPaymentID = Value
End Set
End Property
Sub detailsClicked(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
If e.CommandName.ToLower = "submit" Then
Dim PIDColumn As TableCell = e.Item.Cells(7)
Dim PIDColumnText As String = PIDColumn.Text.Trim
Me.GRDPaymentID = PIDColumnText
Server.Transfer("payment_details.aspx")
End If
End Sub
|
| Page 1 |
<asp:DataGrid id="MyList" OnItemCommand="detailsClicked" runat="server">
<Columns>
<asp:BoundColumn HeaderText="Payee Name" DataField="PayeeName" />
<asp:BoundColumn HeaderText="Amount" DataField="Amount" DataFormatString="{0:c}" />
<asp:BoundColumn HeaderText="Date Added" DataField="DateAdded" DataFormatString="{0:MM/dd/yy}" />
<asp:BoundColumn HeaderText="Date Paid" DataField="DatePaid" DataFormatString="{0:MM/dd/yy}" />
<asp:ButtonColumn Text="Details" HeaderText="Details" CommandName="Redirect" />
<asp:BoundColumn DataField="PaymentID" Visible="False" />
</Columns>
</asp:DataGrid>
|
| Code - Page 2 |
Public m_oSendingPage As Payments
If Page.IsPostBack = False Then
m_oSendingPage = CType(Context.Handler, Payments)
Me.PaymentID = m_oSendingPage.GRDPaymentID
End If
|
| Jump to Top |
| .Net 1.0 : Timeout |
| Command |
f_oCommand.CommandTimeout = 3000
|
| Jump to Top |
| .Net 1.0 : Trace |
Trace.IsEnabled = True
Trace.Warn("Control Loop Begin")
|
| Jump to Top |
| .Net 1.0 : User Control |
| Page |
<%@ Register TagPrefix="Bravo" Tagname="Head" src="controls/Head.ascx" %>
<Bravo:Head ID="Head1" Name="Head1" CurrentPage="home" Runat="server" />
|
| Property - .ascx Code Behind |
Public CurrentPage As String
If Me.CurrentPage.ToLower = "home" Then
tabHome.ImageUrl = "\images\tab_home_on.gif"
End If
|
| Jump to Top |
| .Net 1.0 : Validation |
| Code Behind |
Protected WithEvents vldDOBRequired As System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents vldSummary As System.Web.UI.WebControls.ValidationSummary
Protected WithEvents vldDOB As System.Web.UI.WebControls.CompareValidator
Protected WithEvents vldEmail As System.Web.UI.WebControls.RegularExpressionValidator
|
| Page |
<asp:RequiredFieldValidator id="vldCompanyName" ControlToValidate="CompanyName" Display="dynamic"
ErrorMessage="Enter your company name." runat="server" />
<asp:ValidationSummary ID="vldSummary" HeaderText="Please correct the following error(s):"
DisplayMode="BulletList" ShowMessageBox="True" ShowSummary="False" Runat="server" />
<asp:comparevalidator id="vldFromDate" ControlToValidate="txtFromDate" ErrorMessage="'From Date' is invalid."
Display="None" Operator="DataTypeCheck" Type="Date" runat="server" />
<asp:comparevalidator id="vldToDate" ControlToValidate="txtToDate" ErrorMessage="'To Date' is invalid."
Display="None" Operator="DataTypeCheck" Type="Date" runat="server" />
<asp:comparevalidator id="vldDateCompare" ControlToValidate="txtFromDate" ErrorMessage="'From Date'
must be less than or equal to 'To date'." Display="None" Operator="LessThanEqual" Type="Date"
ControlToCompare="txtToDate" runat="server" />
<asp:RegularExpressionValidator id="vldEmail" ControlToValidate="txtEmail"
ValidationExpression="[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+" Display="None"
ErrorMessage="'Email' is invalid." runat="server" />
<asp:CompareValidator id="vldCompareEmail" ControlToValidate="txtConfirmEmail" ControlToCompare="txtEmail"
Display="Dynamic" ErrorMessage="Emails do not match." runat="server" />
<asp:CustomValidator id="ccNumCustVal" ControlToValidate="ccNum" ErrorMessage="Card Number."
clientvalidationfunction="ccClientValidate" Display="Static" runat=server />
|
| Custom - Code Behind |
Protected Sub StateValidate(ByVal source As System.Object, ByVal args As
System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles vldState.ServerValidate
args.IsValid = (args.Value.Length < 2)
End Sub
|
| Custom - Page |
<asp:CustomValidator id="vldState" OnServerValidate="StateValidate" ControlToValidate="txtState"
Display="None" ErrorMessage="State must be 2 characters." runat="server" />
|
| Client Side |
<script language="JavaScript">
function validateLength(oSrc, args){
args.IsValid = (args.Value.length = 2);
}
</script>
<asp:CustomValidator id="CustomValidator1" runat=server ControlToValidate = "text1"
ErrorMessage = "Please enter at least 2 characters." ClientValidationFunction="validateLength" />
|
| Don't Validate |
<asp:button id="btnUploadAttachment" text="Attach" CausesValidation="False" runat="server" />
|
| Jump to Top |
| .Net 1.0 : Web.Config |
| Basic |
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- application settings -->
<appSettings>
<add key="ConnectionString" value="server='SQL01'; user id='sa'; password='mypass'; database='Store'"/>
</appSettings>
<system.web>
<compilation debug="true" />
<pages validateRequest="true" />
<!-- enable Forms auth -->
<authentication mode="Forms">
<forms name="LMDAuth" loginUrl="Login.aspx" protection="All" path="/" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<!-- enable custom errors -->
<customErrors mode="Off" defaultRedirect="ErrorPage.aspx" />
<!-- disable session state -->
<sessionState mode="Off" />
<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
</configuration>
|
| Keys |
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="emailbcc" value="cjanco@emailme.com" />
</appSettings>
<system.web>
...
</system.web>
</configuration>
' Code
Imports System.Configuration
With Message
.Bcc = ConfigurationSettings.AppSettings("emailbcc")
End With
|
| Security - Deny All |
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="AuthCookie" loginUrl="login.aspx" protection="All" path="/" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
|
| Security - Deny Specific Page |
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="StoreAuth" loginUrl="login.aspx" protection="All" path="/" />
</authentication>
</system.web>
<location path="Checkout.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
|
| Security - All Secure Except One |
<configuration>
<location path="CardInquiry.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
|
| Jump to Top |
| .Net 1.0 : Web Service |
<%@ WebService Language="VB" Class="Calculator" %>
Imports System.Web.Services
Public Class Calculator : Inherits WebService
<WebMethod()> Public Function Add(intA As Integer, intB As Integer) As Integer
Return(intA + IntB)
End Function
End Class
|
| Jump to Top |
| .Net 1.0 : Windows Service |
| More Info: ASPFree.com (C#) |
Install:
C:\> cd windows\microsoft.net\framework\v1.1.4322
C:\windows\microsoft.net\framework\v1.1.4322> installutil c:\services\MyService.exe
Remove:
C:\windows\microsoft.net\framework\v1.1.4322> installutil /u c:\services\MyService.exe
Settings:
- make sure that your ServiceProcessInstaller1 Account property is set to: "LocalSystem"
|
| Jump to Top |
|
|