Add Double Quotes to a C# String

Keywords: C#, double quotes, string
HPImage = @"<img src=""images/events/hpp_vio_240x180.jpg"" width=""240"" height=""180"" />";

Ajax Control Toolkit: Install

Keywords: .Net, Ajax Control Toolkit, install

(1) Download: http://ajaxcontroltoolkit.codeplex.com/

(2) Add AjaxControlToolkit.dll to your bin directory.

AJAX Control Toolkit: Samples

Keywords: .Net, AJAX Control Toolkit, 3.0, samples, examples
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/

AJAX: Calendar

Keywords: .Net, AJAX, calendar
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ACT" %>

<asp:TextBox ID="txtPeakDate" MaxLength="10" runat="server" />
<ACT:CalendarExtender ID="calPeakDate" TargetControlID="txtPeakDate" runat="server" />

Ajax: Tab Control

Keywords: .Net, Ajax, tab control, ScriptManager, TabContainer, TabPanel, AjaxControlToolkit
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<head runat="server">
</head>

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<cc1:TabContainer ID="TabContainer1" runat="server">
	<cc1:TabPanel runat="server" ID="Tabpanel1" NAME="Tabpanel1">
		<HeaderTemplate>General</HeaderTemplate>
		<ContentTemplate>
			' Place content here for first tab...
		</ContentTemplate>
	</cc1:TabPanel>
	<cc1:TabPanel runat="server" ID="Tabpanel2" NAME="Tabpanel1">
		<HeaderTemplate>Equipment</HeaderTemplate>
		<ContentTemplate>
			' Place content here for second tab...
		</ContentTemplate>
	</cc1:TabPanel>
</cc1:TabContainer>

AJAX: UpdatePanel

Keywords: AJAX, UpdatePanel, AjaxControlToolkit, ScriptManager, ContentTemplate, AsyncPostBackTrigger
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ACT" %>

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="updVersion" runat="server" UpdateMode="Conditional"> 
	<ContentTemplate>
		<asp:DropDownList ID="drpVersion" runat="server" AutoPostBack="True" 
			DataSourceID="sdsVersionsTier1" DataTextField="VERSION" DataValueField="VERSION" />
	</ContentTemplate>
	<Triggers>
		<asp:AsyncPostBackTrigger ControlID="drpProgramName" EventName="SelectedIndexChanged" />
	</Triggers> 
</asp:UpdatePanel>

Alert: C#: .Net 1.1

Keywords: alert, .net, c#
<script language="C#" runat="server">
protected  void Page_Load(object sender, EventArgs e){
   //Set the button's client-side onmouseover event
   btnClick.Attributes.Add("onClick", "alert('You clicked me!');");
}
</script>

<form runat="server" ID="Form2">
<asp:button runat="server" Text="Click Me!" id="btnClick" />
</form>

Alert: C#: .Net 2

Keywords: alert, C#, .net 2
<asp:Button ID=button1 runat=server
OnClientClick="return('Are you sure you want to delete this record')"
Text="Delete Record" />

Application Log

Keywords: .Net 1.1, application log, system.diagnostics, event 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)

Array

Keywords: .Net, array
Public Function GetFirstNames() As Array
	Dim firstName() As String = {"Adam", "Bravo", "Charlie", "Echo"}

	Return firstName
End Function

ArrayList

Keywords: .Net 1.1, array, roles
Dim roles As New ArrayList()

roles.Add("Administrators")
roles.Add("ContentManagers")

Dim objItem As Object
objItem = roles.Item(0)

Automatic Properties

Keywords: properties, automatic
public String FirstName { get; set; }

Base Page

Keywords: .Net, base page, sitemap, title

' BASE PAGE

Public Class MyBasePage
Inherits System.Web.UI.Page
 Sub New()
 
 End Sub

 Protected Overrides Sub Onload(ByVal e As System.EventArgs)
  MyBase.OnLoad(e)
  SetTittle()
 End Sub

 Protected Sub SetTitle()
  If SiteMap.CurrentNode IsNot Nothing Then
   Me.Title = SiteMap.CurrentNode.Title.ToString()
  End If
 End Sub
End Class

 

' CODE

Partial Class Contact
Inherits MyBasePage

BitVector32

Keywords: BitVector32, bit, bitwise, bitarray
http://www.nayyeri.net/bitvector32-in-net

It’s important to emphasize on the fact that unlike BitArray that is a class, BitVector32 is a structure and is built based on another structure, System.Collections.Specialized.Bitvector32.Section. BitVector32 has a better efficiency than BitArray as the latter one can grow as much as needed (as I described before) but the former one has a constant 32 bits storage.

A BitVector32 can be set up in two different ways: using sections for small integers or bit flags for Booleans.

private static void BitFlags()
02.{
03.    // Initialize the vector to 2: 00000000 00000000 00000000 00000010
04.    BitVector32 bitVector = new BitVector32(2);
05.  
06.    Console.WriteLine("Initially, the value of vector is {0} represented as \n {1}",
07.       bitVector.Data, bitVector.ToString());
08.  
09.    int bit1 = BitVector32.CreateMask();
10.    int bit2 = BitVector32.CreateMask(bit1);
11.    int bit3 = BitVector32.CreateMask(bit2);
12.  
13.    // Set the first bit to true: 00000000 00000000 00000000 00000011
14.    bitVector[bit1] = true;
15.    Console.WriteLine("Setting the first bit to true, the value of vector is {0} represented as \n {1}",
16.   &nbs

Bookmark

Keywords: .Net, bookmark
Ctrl+K, Ctrl+K - Create/Remove Bookmark
Ctrl+K, Ctrl+N  - Move to next bookmark
Ctrl+K, Ctrl+P -  Move to previous bookmark
Ctrl+K, Ctrl+L - Clear all bookmarks

Button: Click Event: DataKey

Keywords: .Net, button, click event, DataKey
' PAGE
<asp:Button ID="btnMarkOk" Text="Mark Ok" Runat="server" />

' CODE
Protected Sub btnMarkOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMarkOk.Click
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after a button outside of the GridView is clicked.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' DataKey
	Dim f_sCustomerId As String = String.Empty
	f_sCustomerId = grdContacts.DataKeys(i).Values("CUSTOMER_ID").ToString()
End Sub

Button: Don't Validate

Keywords: .Net, button, CausesValidation, don't validate
<asp:button id="btnUploadAttachment" text="Attach" CausesValidation="False" runat="server" />

Button: ImageButton

Keywords: .Net, ImageButton, ImageClickEventArgs
' PAGE
<asp:ImageButton  ID="btnAdminApprove" Text="Approve" Runat="server" />

' CODE
Sub btnAdminApprove_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
	Label1.Text = "You clicked the ImageButton control at the coordinates: (" & _
		e.X.ToString() & ", " & e.Y.ToString() & ")"
End Sub

Button: LinkButton

Keywords: .Net, button, LinkButton, OnCommand, e.CommandName
The CommandArgument property complements the CommandName property by allowing you to provide additional information about the command to perform. For example, if you set the CommandName property to Approve and the CommandArgument property to Manager, you can pass the value "Manager" to the method.

' Page
<asp:LinkButton id="btnManager" Text="Manager Approval" CommandName="Approve" CommandArgument="Manager"
OnCommand="CommandBtn_Click" runat="server"/>

' Code Behind
Sub CommandBtn_Click(sender As Object, e As CommandEventArgs)
Select e.CommandName
Case "Approve"
' Call the method to approve the record.
Sort_List(CType(e.CommandArgument, String))
Case "Void"
' Call the method to void the record.
End Select
End Sub

Button: LinkButton: Delete Confirm

Keywords: .Net, button, delete confirm, OnClientClick
<asp:TemplateField>
	<ItemTemplate>
		<asp:LinkButton ID="btnDelete" runat="server" OnClientClick="return confirm('Are you sure 
			you want to delete this product?');" CommandName="Delete">delete</asp:LinkButton>
	</ItemTemplate>
</asp:TemplateField> 

Button: UseSubmitBehavior

Keywords: .Net, Button, CommandArgument, CommandName, UseSubmitBehavior, enter key

' Ignore Enter Key

 

<asp:Button ID="cmdDis" runat="server" CommandArgument='<%# Eval( "iReminderID" ) %>' CommandName="Dismiss" UseSubmitBehavior="false" />

Cache: Page

Keywords: .Net 1.1, page, cache, OutputCache
<%@OutputCache Duration="60" VaryByParam="none" %>

Calendar: JavaScript Popup

Keywords: calendar, popup, javascript, .Net 1.1

' 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.ASPX

 

<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>

CallPage

Keywords: .Net 1.1, WebRequest, GetResponse, GetResponseStream, StreamReader, .ReadToEnd
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

Cascading Dropdowns

Keywords: cascading, dorpdowns
<asp:DropDownList ID="drpOffice" runat="server" DataTextField="OfficeName" DataValueField="OfficeId" DataSourceID="sdsOfficesNew" AutoPostBack="true" AppendDataBoundItems="true"></asp:DropDownList>
 
<asp:SqlDataSource ID="sdsOfficesNew" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT OfficeId, OfficeName FROM [Offices] WHERE OfficeStatus NOT IN ('Withdrawn') AND OfficeStatus = 'Active' ORDER BY [OfficeName] ASC"></asp:SqlDataSource>

<asp:UpdatePanel ID="updVersion" runat="server" UpdateMode="Conditional">
<ContentTemplate>
        <asp:DropDownList ID="drpSalesRep" runat="server" DataTextField="FullName" DataValueField="Username" DataSourceID="sdsAgentsNew" AutoPostBack="true"></asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="drpOffice" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
                                                                
<asp:SqlDataSource ID="sdsAgentsNew" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT A.Office, A.FirstName + ' ' + A.LastName AS FullName, A.UserId, U.Username FROM Agents A INNER JOIN aspnet_Users U ON A.UserId = U.UserId WHERE A.Office = @OfficeId ORDER BY A.FirstName">
<SelectParameters>
<asp:ControlParameter Name="OfficeID" ControlID="drpOffice" />
</SelectParameters>
</asp:SqlDataSource>

Checkbox: GridView

Keywords: .Net, checkbox, GridView, DataKeys, .Rows(i).FindControl, mark ok, TableAdapter
' PAGE
<asp:GridView ID="grdCharges" runat="server" AllowPaging="True" AutoGenerateColumns="False"  
DataKeyNames="BILL_CUST_ID,START_PERIOD,END_PERIOD" DataSourceID="odsCharges"
Width="800px" CellPadding="3" BorderWidth="0px" EmptyDataText="No records to display.">                  
	<Columns>
		<asp:TemplateField HeaderText="Mark Ok">
			<ItemTemplate>
				<asp:CheckBox ID="chkMarkOk" runat="server" />
			</ItemTemplate>
		</asp:TemplateField>
		<asp:BoundField DataField="BILL_CUST_ID" HeaderText="Agency" />
		<asp:BoundField DataField="START_PERIOD" HeaderText="Start Period" />
		<asp:BoundField DataField="END_PERIOD" HeaderText="End Period" />
	</Columns>
	<HeaderStyle BackColor="#D5DFF3" Font-Bold="True" Font-Names="Verdana" />
	<AlternatingRowStyle BackColor="#EEEEEE" />
</asp:GridView>
' CODE
Protected Sub btnMarkOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMarkOk.Click
	Dim f_sKey1 As String = String.Empty
	Dim f_sKey2 As String = String.Empty
	Dim f_sKey3 As String = String.Empty
	Dim cbMarkOk As System.Web.UI.WebControls.CheckBox
	Dim i As Integer
	Dim f_oTableAdapter As New InvoiceInfoTableAdapters.12B_CHG_CRCTableAdapter
	Dim f_sReturn As String

	For i = 0 To grdCharges.Rows.Count - 1

		cbMarkOk = grdCharges.Rows(i).FindControl("chkMarkOk")

		If (cbMarkOk.Checked) Then
			f_sKey1 = grdCharges.DataKeys(i).Values("BILL_CUST_ID").ToString()
			f_sKey2 = grdCharges.DataKeys(i).Values("START_PERIOD").ToString()
			f_sKey3 = grdCharges.DataKeys(i).Values("END_PERIOD").ToString()
		
			'Mark Ok Method
			f_sReturn = f_oTableAdapter.UpdateOK(drpAgencies.SelectedValue, f_sKey2, f_sKey3,
			Date.Today, My.User.Name, My.User.Name)
		End If
	Next

	If f_sReturn.ToLower = "record updated" Then
		lblMessage.Text = "Records marked Ok have been updated."
	Else
		lblMessage.Text = "An error occured. Please contact support and report the following: " & f_sReturn
	End If

	Me.grdCharges.DataBind()

	f_oTableAdapter.Dispose()
End Sub

Class: C#

Keywords: .net, C#, class
// Class
using System;

namespace WAB.Conexis
{
	/// <summary>
	/// Summary description for User.
	/// </summary>
	public class User
	{
		public User()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		public int Login(string username, string password)
		{
			if (username == "charles" && password == "111111")
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
	}
}
// Form: Code Behind
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using WAB.Conexis;

namespace CSharpTest
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Label lblMessage;

		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			User user = new User();
			int ret = user.Login("charles", "111111");
			lblMessage.Text = Convert.ToString(ret);
		}

		#region Web Form Designer generated code
	}
}


Collection

Keywords: .Net 1.1, collection, ListItemCollection
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

Config: AppSettings

Keywords: .net, config, appSettings, key, configuration
<?xml version="1.0" encoding="Windows-1252"?>
<configuration>
	<appSettings>
		<add key="serverName" value="myServer" />
		<add key="userName" value="sa" />
		<add key="password" value="password" />
		<add key="packageName" value="TestDTS" />
		<add key="interval" value="30000" />
	</appSettings>
</configuration>

Config: AppSettings: Using

Keywords: .Net, C#, AppSettings, System.Configuration
using System.Configuration;
string serverName = ConfigurationSettings.AppSettings["serverName"];

Confirm Popup

Keywords: .Net 1.1, confirm delete, popup

' CODE BEHIND

 

btnDelete.Attributes.Add("OnClick", "return confirm('Are you sure you want to delete " & Replace(DgInQueue.SelectedItem.Cells(11).Text.ToString, "'", "\'", , , CompareMethod.Text) & "?')")

 

' PAGE
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick='return confirm("Are you sure you want to delete this file?");' Text="delete" />

Control: BackColor

Keywords: .Net 1.1, control, back color, fromArgb, FromHtml, BackColor, ColorTranslator
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)

Control: CreateUser: Customize

Keywords: .Net, control, CreateUser, customize
http://www.4guysfromrolla.com/articles/070506-1.aspx

Control: FileUpload

Keywords: .Net, control, FileUpload, file

Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If FileUpload1.HasFile Then
            Try
                Dim path As String = "C:\Websites\DocumentsCustomers\" & lblAppId.Text

                If Directory.Exists(path) Then

                Else
                    Dim di As DirectoryInfo = Directory.CreateDirectory(path)
                End If

                FileUpload1.SaveAs("C:\Websites\Documents\Customers\" & lblAppId.Text & "\" & FileUpload1.FileName)

                pnlSuccess.Visible = True
                pnlError.Visible = False

                GetDocs()
            Catch ex As Exception
                pnlSuccess.Visible = False
                pnlError.Visible = True
                lblError.Text = "ERROR: " & ex.Message.ToString()
            End Try
        Else
            pnlSuccess.Visible = False
            pnlError.Visible = True
            lblError.Text = "You have not selected a file to upload."
        End If
    End Sub

Control: HtmlGenericControl

Keywords: .Net, HtmlGenericControl, FindControl
sTimeZone = f_oRow.Item("TimeZone").ToString()
CType(Me.FindControl("dbtimezone"), HtmlGenericControl).InnerHtml = "Timezone: " & sTimeZone

Control: Reference: C# & VB

Keywords: .net, C#, control, reference, PlaceHolder, FindControl

// C#
PlaceHolder phCTC = (PlaceHolder)(dvw1.FindControl("phCTC"));

' VB
Dim AgentTextBox As TextBox = CType(CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtAgentId"), TextBox) 
 
CreateUserWizard: Reference a Control
Keywords: Membership, CreateUserWizard, Control, ContentTemplateContainer, FindControl 
Dim FirstNameTextBox As TextBox = CType(CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtFirstName"), TextBox)

S.FirstName = FirstNameTextBox.Text.Trim

Control: Style: Align

Keywords: .Net, control, style, align, textbox
<asp:TextBox ID="txtAmount" style="TEXT-ALIGN: right" runat="server" />

Control: TabContainer: Hide Tab

Keywords: .Net, control, TabContainer, hide tab
TabContainer1.Tabs(7).Visible = False
TabContainer1.Tabs(8).Visible = False

Convert: C#

Keywords: .Net, C#, convert, ToDouble, ToDateTime
timer.Interval = Convert.ToDouble(ConfigurationSettings.AppSettings["interval"]);

Convert.ToDateTime(txtDepartDate.Text);

Convert: VB

Keywords: .Net, convert, decimal, string, date
' String to Decimal
f_dAmt = Convert.ToDecimal(f_sAmt)
' String to Date
f_sRegDate = DateTime.Parse(f_sRegDate)

Cookies: 1.1

Keywords: .Net 1.1, 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)

Create and ArrayList will some unique IDs from a table

Keywords: ArrayList, next available id
If Membership.GetUser.UserName = "cmane" Or Membership.GetUser.UserName = "james" Then
            OfficeIdNextGet(4000, 4999)
        ElseIf Membership.GetUser.UserName = "mgood" Then
            OfficeIdNextGet(2000, 2999)
        Else
            lblUserMessage.Visible = False
        End If

Private Sub OfficeIdNextGet(ByVal rangeStart As Integer, ByVal rangeEnd As Integer)
        Dim O As New Office
        Dim dsOfficeIDs As DataSet = Nothing
        Dim usedIDCount As Integer = 0
        Dim availIDCount As Integer = 0
        Dim availIDs As New ArrayList()
        Dim availIDsString As String = String.Empty

        For i = rangeStart To rangeEnd
            availIDs.Add(i)
        Next

        dsOfficeIDs = O.AvailableOfficeIDGet(rangeStart, rangeEnd)
        If dsOfficeIDs.Tables.Count > 0 And dsOfficeIDs.Tables(0).Rows.Count > 0 Then
            usedIDCount = dsOfficeIDs.Tables(0).Rows.Count
            availIDCount = (1000 - usedIDCount)
            For Each dr As DataRow In dsOfficeIDs.Tables(0).Rows
                availIDs.Remove(CInt(dr("OfficeId").ToString))
            Next
        End If

        For i = 0 To availIDs.Count - 1
            availIDsString += CStr(availIDs(i)) & ", "
        Next

        lblUserMessage.Text = "The following Office IDs are available: " & availIDsString
    End Sub

Data Controls: NULL

Keywords: .Net, data controls, null, FormView, DetailsView, GridView, EmptyDataText, ConvertEmptyStringToNull
Data controls support a variety of ways to handle null or missing data. To begin with, 
the GridView, FormView, and DetailsView all support an EmptyDataText or EmptyDataTemplate 
property that you can use to specify a rendering for the control when the data source returns 
no rows of data. Only one of EmptyDataText and EmptyDataTemplate needs to be set 
(EmptyDataTemplate overrides when both are set). You can also specify a ConvertEmptyStringToNull 
property on BoundField (and derived field types), TemplateField or data source parameter objects 
to specify that String.Empty values posted from the client should be converted to null before 
invoking the associated data source operation. ObjectDataSource also supports a ConvertNullToDbNull 
property that can be set to true when the associated method expects DbNull parameters instead of 
null (the TableAdapter classes in a Visual Studio DataSet have this requirement). You can also 
specify a NullDisplayText property on BoundField (and derived field types) to specify a value 
for the field to display when the field value from the data source is returned as null. If this 
value is not changed during edit mode, the value will roundtrip as null back to the data source 
during an Update operation. Lastly, you can also specify a DefaultValue property on data source 
parameters to specify a default value for the parameter when the parameter value passed is null. 
These properties can a chaining effect, for example if both ConvertEmptyStringToNull and DefaultValue 
are set, a String.Empty value will first be converted to null and subsequently to the default value. 

Data: MySQL

Keywords: database, MySQL, Imports MySql.Data.MySqlClient, .Net

http://www.15seconds.com/issue/050407.htm
http://www.mysql.com/products/connector/


' CODE BEHIND
Imports System.Data
Imports MySql.Data.MySqlClient

 

Public Class MysqlTest
    Inherits System.Web.UI.Page

 

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim myConnection  As MySqlConnection
     Dim myDataAdapter As MySqlDataAdapter
     Dim myDataSet     As DataSet

     Dim strSQL        As String
     Dim iRecordCount  As Integer

     myConnection = New MySqlConnection("server=1.1.1.1; user id=myuser; password=111111; database=talki; pooling=false;")

     strSQL = "SELECT forumtopic_id, forumtopic_date, forumtopic_subject, forumtopic_excerpt FROM se_forumtopics LIMIT 0,6"

     myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
     myDataSet = New Dataset()
     myDataAdapter.Fill(myDataSet, "mytable")

     MySQLDataGrid.DataSource = myDataSet
     MySQLDataGrid.DataBind()      
    End Sub
End Class

Database: ExecuteScalar

Keywords: .Net, return one, ExecuteScalar, database, count

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

 

Public Sub TasksTotalGet()
        Dim dbConnection As SqlConnection
        Dim connectionString As String = Nothing
        Dim command As SqlCommand = Nothing
        Dim tasksTotal As Integer = 0
        Try
            connectionString = ConfigurationManager.ConnectionStrings("MeritCardConnectionString").ConnectionString
            dbConnection = New SqlConnection(connectionString)

            Dim sql = "SELECT COUNT(AppId) FROM ServiceCenter WHERE AssignedTo = 'cjanco' AND Completed = 0"
            Dim cmd As New SqlCommand(sql, dbConnection)
            dbConnection.Open()
            tasksTotal = cmd.ExecuteScalar

            lblTaskCount.Text = tasksTotal.ToString
        Catch ex As Exception
            'LogManager.AddToFile("ERROR: WONumberGet: " & Date.Now & ", " & ex.Message)
            lblTaskCount.Text = "0"
        End Try
    End Sub

Database: Oracle: Return Single Value: No Proc

Keywords: .Net, database, return single value, no proc, .ExecuteOracleScalar
Public Function WONumberGet(ByVal vSRNo As Integer) As Integer
        Dim dbConnection As OracleConnection
        Dim connectionString As String = Nothing
        Dim command As OracleCommand = Nothing
        Dim workOrderNumber As Integer = 0
        Try
            connectionString = Config.ORACLE_CONNECTION_STRING
            dbConnection = New OracleConnection(connectionString)

            Dim sql = "SELECT WO_NUMBER FROM wo_xref WHERE SR_NO = " & vSRNo
            Dim cmd As New OracleCommand(sql, dbConnection)
            dbConnection.Open()
            workOrderNumber = cmd.ExecuteOracleScalar
        Catch ex As Exception
            LogManager.AddToFile("ERROR: WONumberGet: " & Date.Now & ", " & ex.Message)
        End Try
retVal:
        Return workOrderNumber
End Function

DataGrid: 1.1

Keywords: .Net 1.1, DataGrid

' CODE

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>



 

DataGrid: HyperLinkColumn

Keywords: .Net 1.1, DataGrid, HyperLinkColumn, DataNavigateUrlField, DataNavigateUrlFormatString
<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>

DataGrid: Pagination: 1.1

Keywords: .Net, DataGrid, 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


 

DataProviders

Keywords: .Net 1.1, DataProviders, OLE DB, SQL, data provider, SQLDataReader, OleDbDataReader

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.

DataReader: 1.1

Keywords: .Net 1.1, DataReader, data, stored proc, SQLDataReader, ExecuteReader, SqlCommand, SqlConnection, AppSettings
' CLASS
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" />

DataReader: Loop: 1.1

Keywords: .Net 1.1, DataReader, while loop
Dim f_oDataReader As SqlDataReader
While f_oDataReader.Read()
	f_bReturn = EmailResponseSend(f_oDataReader(1).ToString(), f_oDataReader(2).ToString())
End While

DataSet: Get Method: 1.1

Keywords: .Net 1.1, DataSet, data, SqlClient, SqlConnection, SqlDataAdapter, AppSettings, Namespace, stored proc, sp, .Fill
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

DataSet: Write to XML File: 1.1

Keywords: .Net 1.1, DataSet, XML, WriteXml
Dim myData As New DataSet

...

myData.WriteXml("TestXML.txt")

DataTable

Keywords: .Net 1.1, DataTable, stored proc, sp, AppSettings, .AddParam, ReturnValue, DataReader

' CLASS

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

Date: Time: Format

Keywords: .Net 1.1, dates, Date.Today, DateTime.Now.ToString, .Today, formatting, MMM, YYYY, HH, hour

' 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

 

<!-- 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")

Date: Weekend Check

Keywords: .Net, date, weekend, DayOfWeek.Saturday, DayOfWeek.Sunday
Private Function InvDueDate(ByVal vNextActiveBillPeriod As String) As Date
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' Compute the due date as two months from the last day of the billed month. 
	' Make sure the date is not a Sunday or Saturday.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_sNextActiveBPMonth As String
	Dim f_sNextActiveBPYear As String
	Dim f_sDueDate As String
	Dim f_dDueDateTemp As Date
	Dim f_dDueDate As Date
	Dim f_dLastDayOfMonth As Date

	f_sNextActiveBPMonth = vNextActiveBillPeriod.Substring(4, 2)
	f_sNextActiveBPYear = vNextActiveBillPeriod.Substring(0, 4)
	f_sDueDate = f_sNextActiveBPMonth & "/" & "1" & "/" & f_sNextActiveBPYear
	f_dDueDateTemp = DateAdd(DateInterval.Month, 2, CDate(f_sDueDate))
	f_dLastDayOfMonth = New Date(f_dDueDate.Year, f_dDueDate.Month, 1).AddMonths(1).AddDays(-1)
	f_dDueDate = New Date(f_dDueDateTemp.Year, f_dDueDateTemp.Month, f_dLastDayOfMonth.Day)

	Select Case f_dDueDate.DayOfWeek
		Case DayOfWeek.Saturday
			f_dDueDate = DateAdd(DateInterval.Day, -1, f_dDueDate)
		Case DayOfWeek.Sunday
			f_dDueDate = DateAdd(DateInterval.Day, -2, f_dDueDate)
	End Select

	Return f_dDueDate
End Function

DateAdd

Keywords: .Net, DateAdd, Date, .ToLongDateString
' Wednesday, July 26, 2006
lblCurrentDate.Text = DateAdd("d", -1, Date.Today).ToLongDateString

Desktop App: Icon Converter

Keywords: desktop application, icon, convert
http://www.coolutils.com/online/image-converter/

DetailsView with ObjectDataSource

Keywords: DetailsView, ObjectDataSource
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName=DB.SP.RelevantYellow"
        SelectMethod="Details_GET" UpdateMethod="Details_SET">
        <SelectParameters>
            <asp:Parameter Name="RETURN_VALUE" DefaultValue="-99" Type="Int32" />
            <asp:Parameter Name="uidPlacementID" Type ="Int32" />                 
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="RETURN_VALUE" DefaultValue="-99" Type="Int32" />
            <asp:Parameter Name="iProfileId" Type="Int32" DefaultValue="0" />
            <asp:Parameter Name="PermalinkURL" Type="string" ConvertEmptyStringToNull="true" />
        </UpdateParameters>
    </asp:ObjectDataSource>

<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="ObjectDataSource1" AutoGenerateRows="false"
                    DefaultMode="ReadOnly" GridLines="None" CellSpacing="4" CellPadding="4" Width="100%">
                        <fields>
                            <asp:BoundField DataField="FirstName" HeaderText="First Name:"  HeaderStyle-Font-Bold="true" />
                            <asp:BoundField DataField="LastName" HeaderText="Last Name:"  HeaderStyle-Font-Bold="true" />
                            <asp:BoundField DataField="Address" HeaderText="Address:" HeaderStyle-Font-Bold="true" />
                            <asp:BoundField DataField="City" HeaderText="City:" HeaderStyle-Font-Bold="true" />
                            <asp:BoundField DataField="State" HeaderText="State:" HeaderStyle-Font-Bold="true" />
                            <asp:BoundField DataField="Zip" HeaderText="Zip Code:" HeaderStyle-Font-Bold="true" />
                        </fields>
                </asp:DetailsView>

DLL: Register/UnRegister

Keywords: .Net, register dll, regasm.exe, /unregister

' 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

Download .Net 1.1

Keywords: .Net 1.1, download, instal, asp.net

.NET Framework Redistributable Now (21 MB) MSDN: .NET Framework Service Pack 2

 

http://www.asp.net/downloads/essential

DropDown: Bind

Keywords: .Net, DropDown, bind, Items.Insert, ListItem
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

Dropdown: Check if Empty

Keywords: .Net, dropdown, dropdownlist, empty check
If DropDownList1.Items.Count = 0 Then
	'...
End If

Dropdown: Collection

Keywords: .Net 1.1, 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

Dropdown: Create in Code Behind

Keywords: dropdown, .Net 1.1, Items.Add, DropDownList
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

Dropdown: Databind: SQLDataSource

Keywords: .net, dropdown, databind, sqldatasource
<asp:DropDownList ID="drpDischargeReason" runat="server" DataSourceID="sdsDischarge" DataTextField="Item" DataValueField="Value">                                                                
 </asp:DropDownList>
 <asp:SqlDataSource ID="sdsDischarge" runat="server" ConnectionString="<%$ ConnectionStrings:DataStore %>" 
 SelectCommand="SELECT Value, Item FROM lkp_Discharge ORDER BY Value ASC"></asp:SqlDataSource>

DropDown: Insert Item

Keywords: .Net 1.1, dropdown, insert item, Items.Insert, ListItem
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"))

DropDown: Item.Add / Item.Insert

Keywords: .Net, dropdown, Item.Add, Item.Insert

DropDownList.Items.Add method allows you to add new ListItem into the DropDownList. This item will be added as the last item of the DropDownList.


dropDownList.Items.Add(new ListItem("Toyota", "0"));

 

DropDownList.Items.Insert method allows you to specify the index of the item within the DropDownList where you want to insert the ListItem.


dropDownList.Items.Insert(0, new ListItem("Toyota", "0"));

DropDown: Selected

Keywords: .Net 1.1, DataGrid, dropdown, 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>

' CODE

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


 

Dropdown: Width: Code Behind

Keywords: .Net, dropdown, width, code behind
ddMember.Width = New WebControls.Unit(300)

DTS: C#

Keywords: .Net, C#, DTS

http://www.15seconds.com/issue/030909.htm

 

Runtime Callable Wrapper (RCW):
1) Strong Name Tool: create key sn.exe -K c:\dts.snk(c:\program files\microsoft visual studio .net\sdk\v1.1\bin)
2) Create RCW assembly: www.12Bravo.com/rcw.doc
3) Install RCW in GAC: www.12Bravo.com/rcw.doc

Email Setup

Keywords: .Net 1.1, email setup, relay, SMTP
(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

Email: 1.1

Keywords: .Net, email, 1.1, System.Web.Mail, MailMessage
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)

Enter Key

Keywords: enter key, submit button

AccessKey="r"

Or

<form id="form1" runat="server" defaultbutton="btnSearch" defaultfocus="txtMerchantName">

Error : It is not possible to run two different versions

Keywords: error, same iis process, iis, .net versions, application pool

"It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration tool to run the application in a separate process."

An application pool is a process that responds to web requests under IIS. An application pool does not have a setting for what type of ASP.Net applications will be run in it. Instead, it loads the appropriate libraries when an ASP.Net application is loaded in the process. Because the libraries for ASP.Net 1.1 and ASP.Net 2.0 are similar, but not the same, the application pool cannot respond to requests for both types of applications at the same time. This can cause sporadic behaviour if you are using the server at the same time as another developer and you have applications using different versions of the framework in the same application pool.

Make sure that on your server there is an application pool dedicated to ASP.Net 2.0 applications and one for ASP.Net 1.1 applications. When you add an ASP.Net application to the server, make sure you select the right application pool for it. 

Error: "...cannot find a method with that name and params..."

Keywords: .Net, error, cannot find a method, OldValuesParameterFormatString
When attempting to run your app which has a GridView/ObjectDataSource, you get a strange message that says it cannot find a method with that name and params such as "generic_".

SOLUTION:
Go to your ObjectDataSource...

OldValuesParameterFormatString="original_{0}"

and change it to...

OldValuesParameterFormatString="{0}"

Error: "...invalid postback or callback argument..."

Keywords: .Net, error, validateRequest, enableEventValidation

ERROR:

invalid postback or callback argument. Event validation is enabled using...

SOLUTION:
Change:

<pages validateRequest="false" />

To:

<pages validateRequest="false" enableEventValidation="false" />

 

NOTE: doing this could open the page up for a SQL injection attack if you are not cautious.

Error: "...null value..."

Keywords: .Net, NullValue property
ERROR: 
If you receive an error related to a null value being returned.
SOLUTION
click on the properties of the field and set the NullValue property to (Nothing).

Error: "...Size property has an invalid size of 0."

Keywords: .Net, error, size property, proc params
ERROR:
String[1]: the Size property has an invalid size of 0.

SOLUTION:
Make sure you specify a size for all your char stored proc params (even output)...

objComm.Parameters.Add(New OleDbParameter("Password", NPPassword))
objComm.Parameters(1).OleDbType = OleDbType.VarChar
objComm.Parameters(1).Direction = ParameterDirection.Output
objComm.Parameters(1).Size = 100

Error: "...Unable to start debugging on the web server..."

Keywords: .Net, error, unable to start debugging
ERROR:
"Unable to start debugging on the web server. The web server is not configured correctly. See help for common configuration errors. Running the web page outside of the debugger may provide further information."

SOLUTION 1: Register .Net 2.0 (if using 2.0)
(1) C:\> cd windows\microsoft.net\framework\v2.0.50727
(2) C:\windows\microsoft.net\framework\v2.0.50727> aspnet_regiis -i

SOLUTION 2: Register .Net 1.1 (if using 1.1)
(1) C:\> cd windows\microsoft.net\framework\v1.1.4322
(2) C:\windows\microsoft.net\framework\v1.1.4322> aspnet_regiis -i

SOLUTION 3:
Make sure that the proper .Net version is selected in IIS for that website.

Error: "...Web server is not running ASP.NET version 1.1..."

Keywords: .Net, error, aspnet_regiis -i, not running
ERROR:
"Visual Studio .NET has detected that the specified Web server is not running ASP.NET version 1.1. You will need to run ASP.NET Web Applications or services."

SOLUTION:
(1) C:\> cd windows\microsoft.net\framework\v1.1.4322
(2) C:\windows\microsoft.net\framework\v1.1.4322> aspnet_regiis -i

Error: "Can't find method"

Keywords: .Net, error, can't find method, .xsd file, DataTable, auto created methods, DeleteCommand, InsertCommand
"Can't find method"

SOLUTION:
When attempting to attach a method to an ObjectDataSource, it does not appear in the drop down (ex: ChargesUpdate). You may see a generic one called "Update". Go to the .xsd file and select the DataTable and view the properties. In the properties window, remove the auto created methods (DeleteCommand, InsertCommand...).

Error: "Delete and Edit not enabled on your .Net 2.0 GridView."

Keywords: .Net, error, DataSource, delete and edit not enabled
ERROR:
Delete and Edit not enabled on your .Net 2.0 GridView.

SOLUTION:
Make sure your datasource has a primary key.

Error: "Failed to enable constraints. One or more rows..."

Keywords: .Net, error, TableAdapter, fill method, failed to enable constraints
ERROR:
"Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

SOLUTION:
Due to a mismatch between the TableAdapter and the specific query with regards to the amount of columns. If the TableAdapter is defined as...

Select * FROM table_a
and the specific Fill Method/Get Method / Query is
SELECT field1 FROM table_a

or

SELECT DISTINCT field1 FROM table_a

and table_a has more than one column,for instance, the exception will be thrown. I saw this by 'previewing' the data with the designer. (Right click on the Query in the designer, and choose preview). The fields not listed in the query were empty, and that's what the exception is barking about. The TableAdapter Query must have the same columns as the individual Queries attached to it.

It makes sense, if you think about it. The Fill/Get method of the TableAdapter is really creating a specific type of DataSet, and if you're missing fields, the binding doesn't work properly.

CGJ - select configure for the Fill, GetData() TableAdapter and copy the fields. Paste the into FillMeterByOrgID, GetMeterByOrgID(OrgID) configuration (previously only had the a select on the MeterID).

Error: "Microsoft OLE DB Provider for SQL Server error 80040e21"

Keywords: .Net, error, OLE DB Provider, 80040e21

ERROR

Microsoft OLE DB Provider for SQL Server error '80040e21'

Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.

 

SOLUTION:

probably forgot a parameter in the CommandText that the stored proc is expecting.

objComm.CommandText = "Insert into crs_tbl_Modules (CourseId,CourseName,Week,Title,Description,Summaries,Status)  values(?,?,?,?,?,?,?)"

Error: "Server Application Unavailable"

Keywords: .Net, error, server application unavailable
"Server Application Unavailable"

SOLUTION:
Make sure that .Net 1 apps are in one Application Pool and .Net 2 are in another.

Error: "The 'DataSource' property cannot be set declaratively"

Keywords: .Net, error, DataSource property cannot be set, DataSourceID
ERROR:
"The 'DataSource' property cannot be set declaratively"

SOLUTION:
Make sure you have DataSourceID="SqlDataSource1" not DataSource="SqlDataSource1" in your GridView.

Error: "The GridView...fired event PageIndexChanging..."

Keywords: .Net, GridView, error, PageIndexChanging, AllowPaging, AllowSorting

ERROR:

The GridView 'grdMonth' fired event PageIndexChanging which wasn't handled.

 

SOLUTION:

If you set AllowPaging="true" or AllowSorting="true" on a GridView control without
using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will
run into the error.

Protected Sub grdMonth_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) _
    Handles grdMonth.PageIndexChanging
        grdMonth.PageIndex = e.NewPageIndex
        GridDataGet()
    End Sub

ERROR: AJAX Controls do not show

Keywords: error, AJAX controls, visibility, ActiveTabIndex, TabContainer
ERROR: AJAX Controls do not show (style="visibility:hidden;")

SOLUTION: <ajax:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" style="display:block;visibility:visible;">

ERROR: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts

Keywords: error, AjaxControlToolkit, Ajax 4.0 scripts, ToolkitScriptManager, ScriptManager
ERROR: Microsoft JScript runtime error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of 
the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.

SOLUTION: 
(1) 

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

(make sure TagPrefix="asp")
 
(2)

CHANGE
<asp:ScriptManager ID="scriptMaster" runat="server"></asp:ScriptManager>
TO
<asp:ToolkitScriptManager ID="toolkitScriptMaster" runat="server"></asp:ToolkitScriptManager>

ERROR: Could not find any resources appropriate for the specified culture or the neutral culture

Keywords: error, neutral culture, ScriptManager, AjaxControlToolkit
ERROR: Could not find any resources appropriate for the specified culture or the neutral culture.  
Make sure "AjaxControlToolkit.Properties.Resources.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" 
at compile time, or that all the satellite assemblies required are loadable and fully signed.

SOLUTION: ADD the ScriptManager -- <asp:ScriptManager ID="ScriptManager1" runat="server" />

ERROR: Custom Error Page not Showing

Keywords: error, custom error page, TrySkipIisCustomErrors
ERROR: would not show custom error page

SOLUTION: Response.TrySkipIisCustomErrors = true; 

ERROR: Excel: RegisterForEventValidation can only be called during Render();

Keywords: .net, excel, export, RegisterForEventValidation
ERROR: (during Excel export)
RegisterForEventValidation can only be called during Render();

SOLUtION:
EnableEventValidation="false"

Error: IIS: "It is not possible to run two different versions of ASP.NET..."

Keywords: .Net, error, IIS, not possible to run, Application Pool
ERROR:
"It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration Tool to reconfigure your server to run the application in a separate process."

SOLUTION:
Keep .Net 1 apps in one App Pool and .Net 2 in another -- http://weblogs.asp.net.

ERROR: insert items for Dropdown does not work

Keywords: error, insert items, dropdown
ISSUE: insert items for dropdown does not work...

SOLUTION:
add AppendDataBoundItems="true"

Error: Oracle: "OCI-22053: overflow error "

Keywords: .Net, Oracle, error, overflow, OCI-22053, truncate
ERROR:
OCI-22053: overflow error

SOLUTION:
Truncate the decimal field to 2 decimal places. You probably have on field returning a value such as 3.27927120669056....

TRUNC(cc_charge, 2)

Error: Oracle: "ORA-00936: missing expression"

Keywords: .Net, error, Oracle, ORA-00936: missing expression
ERROR:
ORA-00936: missing expression

SOLUTION:
Needed to add single quotes around my variables that are strings when passing them in a SQL statement.

Error: Oracle: "ORA-12514: TNS:listener does not currently know of..."

Keywords: .Net, Oracle, ORA-12514: TNS:listener does not currently know of, TNSNAMES.ORA, Windows Service
ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor

SOLUTION:
Needed to install the Windows Service which talks to Oracle server on the D: drive where the TNSNAMES.ORA is located (not C:).

Error: Oracle: "ORA-12545: Connect failed because target..."

Keywords: .Net, Oracle, ORA-12545: Connect failed because target
ERROR:
ORA-12545: Connect failed because target host or object does not exist

SOLUTION:
I had the connection string value commented out.

ERROR: property 'SelectedItem' is 'ReadOnly'

Keywords: SelectedItem, property, ReadOnly, FindByText
ERROR: property 'SelectedItem' is 'ReadOnly'

SOLUTION:
Protected Sub drpOffice_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles drpOffice.PreRender
        drpOffice.Items.FindByText(officeName).Selected = True
    End Sub

ERROR: There is no source code available for the current location

Keywords: error, no source code
ERROR: There is no source code available for the current location.

SOLUTION: I removed the Google charts JS from the Head of the Dashboard.

ERROR: Validation of viewstate MAC failed

Keywords: error, validation of viewstate, MAC, EnableViewStateMac
ERROR:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. 

SOLUTION:
Add EnableViewStateMac="false".
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="search.aspx.vb" Inherits="GEAStore.search" EnableViewStateMac="false" %>

ERROR: Your step-into request resulted in an automatic step-over of a property or operator.

Keywords: .net, error, visual studio, debugging
ERROR:
Your step-into request resulted in an automatic step-over of a property or operator. 

FIX:
•Go to Tools > Options menu in Visual Studio.
•Goto Debugging > General menu item in left pane.
•In right view you will see and option Step over properties and operators (Managed only). Uncheck this option and then you are all set.

ErrorHandler

Keywords: .Net 1.1, ErrorHandler, GoTo, error log, StreamWriter, File.AppendText, WriteLine, Resume Next, System.IO
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

Event Log: Write To

Keywords: .Net, application log, app log, write to, error logging, System.Diagnostics, event log

Imports System.Diagnostics

Public Function WriteToEventLog(ByVal Entry As String, _
   Optional ByVal AppName As String = "VB.NET Application", _
   Optional ByVal EventType As _
   EventLogEntryType =  EventLogEntryType.Information, _
   Optional ByVal LogName As String = "Application") As Boolean

'*************************************************************
 'PURPOSE: Write Entry to Event Log using VB.NET
 'PARAMETERS: Entry - Value to Write
 '            AppName - Name of Client Application. Needed
 '              because before writing to event log, you must
 '              have a named EventLog source.
 '            EventType - Entry Type, from EventLogEntryType
 '              Structure e.g., EventLogEntryType.Warning,
 '              EventLogEntryType.Error
 '            LogName: Name of Log (System, Application;
 '              Security is read-only) If you
 '              specify a non-existent log, the log will be
 '              created
       
 'RETURNS:   True if successful, false if not
       
 'EXAMPLES:
 '1. Simple Example, Accepting All Defaults
 '    WriteToEventLog "Hello Event Log"
       
 '2.  Specify EventSource, EventType, and LogName
 '    WriteToEventLog("Danger, Danger, Danger", "MyVbApp", _
 '                      EventLogEntryType.Warning, "System")
 '
 '******************************************************
       
        Dim objEventLog As New EventLog()
       
        Try
            'Register the App as an Event Source
            If Not objEventLog.SourceExists(AppName) Then
               
                objEventLog.CreateEventSource(AppName, LogName)
            End If
           
            objEventLog.Source = AppName
           
            'WriteEntry is overloaded; this is one
            'of 10 ways to call it
            objEventLog.WriteEntry(Entry, EventType)
            Return True
        Catch Ex As Exception
            Return False
           
        End Try
       
    End Function

EventLog: C#

Keywords: .Net, C#, EventLog, System.Diagnostics, WriteEntry
using System.Diagnostics;

EventLog.WriteEntry("POPService", x.Message);

Export GridView to Excel

Keywords: export, GridView, Excel

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles btnExport.Click
        ExportToExcel("AlertsReport.xls", grdAlerts)
    End Sub

 

Private Sub ExportToExcel(ByVal strFileName As String, ByVal dg As GridView)
        Response.Clear()
        Response.Buffer = True
        Response.ContentType = "application/vnd.ms-excel"
        Response.Charset = ""
        Me.EnableViewState = False
        Dim oStringWriter As New System.IO.StringWriter
        Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

        grdAlerts.RenderControl(oHtmlTextWriter)

        Response.Write(oStringWriter.ToString())
        Response.[End]()
    End Sub

External Process: Call .exe

Keywords: .Net, external process, call exe, Process.Start, System.Diagnostics
Imports System.Diagnostics

Protected Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnPreview.Click
	' (1) Check if file exists
	Dim f_sFileDirectory As String = ConfigurationManager.AppSettings("InvoicePrintPDFDir")
	Dim f_sFilePath As String = f_sFileDirectory & "\" & drpBillPeriods.SelectedValue & "\" & "invoice-" & _
		drpBillPeriods.SelectedValue & "-" & drpAgencies.SelectedValue & ".pdf"
	Dim f_sAcrobatPath As String = ConfigurationManager.AppSettings("InvoicePrintAcrobatDir")
	 
	If File.Exists(f_sFilePath) Then
		' (2) Call process
		Process.Start(f_sAcrobatPath, f_sFilePath)
	Else
		lblMessage.ForeColor = Drawing.Color.Red
		lblMessage.Text = "The invoice file does not exist. Cannot preview."
		Exit Sub
	End If
End Sub
' EXE
System.Diagnostics.Process.Start("\\CLEFS1\apps\Carpe\CD32.EXE /I")

File: Create/Write To

Keywords: .Net, file, create, write to, OpenOrCreate, StreamWriter, System.IO, .WriteLine, .Flush, error logging, FileStream
Imports System.IO

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

File: DataGrid

Keywords: .Net 1.1, DataGrid, file, System.IO, Server.MapPath, GetFiles, HyperLinkColumn, Panel
' CODE
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
' PAGE
<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>

File: Exists

Keywords: .Net, file, exists
Imports System.IO

If File.Exists("C:\Temp\test.txt") Then

End If

File: Format

Keywords: .Net, file, format, GridView
<!-- File Size -->
<asp:BoundColumn DataField="Length" HeaderText="File Size" DataFormatString="{0:#,### bytes}" />

File: Upload

Keywords: .Net 1.1, file, upload, HTMLInputFile, MapPath, PostedFile
<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

FileStream: C#

Keywords: .Net, C#, FileStream, StreamWriter
private void AddToFile(string contents)
{
	FileStream objFileStream = new 
	FileStream(@"c:\pop3grabber.txt", FileMode.OpenOrCreate, FileAccess.Write);
	
	StreamWriter objStreamWriter = new StreamWriter(objFileStream);

	objStreamWriter.BaseStream.Seek(0, SeekOrigin.End);

	objStreamWriter.WriteLine(contents);

	objStreamWriter.Flush();

	objStreamWriter.Close();			
}

Font: FontUnit

Keywords: .Net, font size, FontUnit
lb.Font.Size = FontUnit.Point(9)

Form: Default Field Focus

Keywords: form, default field focus
<form id="form1" runat="server" defaultbutton="btnSearch" defaultfocus="txtMerchantName">

Format: Currency

Keywords: .Net, FormatCurrency, decimal
txtAnnualCCVolume.Text = FormatCurrency(dr("AnnualCCVolume").ToString, 2)

Format: Dates

Keywords: .Net, format, dates, string.format, eval, DataFormatString

' BOUND FIELD


' 12/31/2008
<asp:BoundField DataField="DATE" HeaderText="Date" HtmlEncode="False" DataFormatString="{0:MM/dd/yyyy}" />

 

' TEMPLATE FIELD

<asp:TemplateField HeaderText="Peak Date">
	<EditItemTemplate>
		<asp:TextBox ID="txtPeakDayEdit" Text='<%# String.Format("{0:MM/dd/yyyy}", Eval("PEAK_DAY")) %>' 
		runat="server" MaxLength="10" Width="70" />
	</EditItemTemplate>   
	<ItemTemplate>
		<asp:Label ID="lblPeakDayRetrieve" Text='<%# String.Format("{0:MM/dd/yyyy}", Eval("PEAK_DAY")) %>' 
		runat="server" />
	</ItemTemplate>
</asp:TemplateField>

Format: Numbers

Keywords: .Net, format, GridView, BoundField, String.Format, DataFormatString, numbers, currency

' NUMBERS (set HTMLEncode to false)

' $148,267.80
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:C}" /> 
 
' 148,267
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###}" /> 
 
' 148,267.8
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###.##}" />

' 148,267.0
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###.0}" />

' GridView

<asp:Label ID="lblAmount" Text='<%# String.Format("{0:C}", Eval("AMOUNT")) %>' runat="server" />


' Code Behind

Dim f_cAmount As Decimal = 12.21 
lblMessage.Text = String.Format("{0:C}", f_cAmount)

GAC: Path

Keywords: .Net, GAC, path
C:\WINDOWS\assembly

GridView : Eval : Format Currency

Keywords: .net, gridview, format, currency, eval
<%#Eval("mCost", "{0:$###,##0.00}")%>

Gridview Links Style

Keywords: css, gridview, LinkButton, CommandField, style, link

A.bluelink, A.bluelink:link, A.bluelink:visited, A.bluelink:hover
{
color: #0000ff;
}

<asp:LinkButton ID="btnDelete" runat="server" CssClass="bluelink" CausesValidation="false">Delete</asp:LinkButton>

<asp:CommandField ShowEditButton="True" CausesValidation="False" ControlStyle-CssClass="bluelink" />

GridView Row Item Color

Keywords: GridView, color, row
Protected Sub grdProjects_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
    Handles grdProjects.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If e.Row.Cells(6).Text.Trim = "complete" Then
                e.Row.Cells(6).ForeColor = Drawing.Color.Green
                e.Row.Cells(6).Font.Bold = True
            End If
        End If
    End Sub

GridView: ButtonField

Keywords: .Net 2.0, ButtonField, GridView, CommandName, Button

DataKeyNames="iMemberId"

<asp:ButtonField ButtonType="Image" CommandName="Manage" ImageUrl="~/Images/name-icon.gif" HeaderText="Manage" ItemStyle-HorizontalAlign="Center" Visible="false" />

Protected Sub grdMeters_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles grdMeters.RowCommand
 Dim iIndex As Integer = Convert.ToInt32(e.CommandArgument)
 Dim iMemberIdKey As Integer = 0

 If e.CommandName.ToLower = "manage" Then
  iMemberIdKey = Convert.ToInt32(grdMeters.DataKeys(iIndex).Values("iMemberId").ToString())
  Response.Redirect("~/Meters.aspx?Id=" & iMemberIdKey)
 End If
End Sub

GridView: Count Rows

Keywords: .Net, GridView, count rows
If grdComments.Rows.Count > 0 Then
	btnDelete.Enabled = True
End If

GridView: Edit

Keywords: .Net, GridView, edit, ShowEditButton, SqlDataSource, CommandField
<asp:GridView ID="grdDischarge" runat="server" AutoGenerateColumns="False"  
                                DataSourceID="sdsDischarge" Width="600px" CellPadding="3" CellSpacing="3" BorderWidth="0px" 
                                EmptyDataText="No records to display." Font-Size="Larger">                  
                           <Columns>
                           <asp:BoundField DataField="Value" HeaderText="Id" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" />
                           <asp:BoundField DataField="Item" HeaderText="Item" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" />
                                    <asp:CommandField ButtonType="Link" ShowEditButton="true" />
                           </Columns>
                           <HeaderStyle BackColor="#D5DFF3" Font-Bold="True" Font-Names="Verdana" />
                           <AlternatingRowStyle BackColor="#EEEEEE" />
                            </asp:GridView>
                            <asp:SqlDataSource ID="sdsDischarge" runat="server" ConnectionString="<%$ ConnectionStrings:DataStore %>" 
                            SelectCommand="SELECT Value, Item FROM lkp_Discharge ORDER BY Value ASC"></asp:SqlDataSource>

GridView: Edit

Keywords: .Net, GridView, edit, cancel edit

http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx

 

Protected Sub grdWeeklyTime_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) _
        Handles grdWeeklyTime.RowCancelingEdit
            grdWeeklyTime.EditIndex = -1
            MemberTimeGet()
End Sub

 

Protected Sub grdWeeklyTime_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) _
        Handles grdWeeklyTime.RowEditing
            grdWeeklyTime.EditIndex = e.NewEditIndex
            MemberTimeGet()
End Sub

 

Protected Sub grdWeeklyTime_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
        Handles grdWeeklyTime.RowUpdating
            Try
                Dim iRet As Integer
                Dim iMemberId As Integer = 0
                Dim ddMember As DropDownList
                Dim dtWeekDate As Date
                Dim sDateIdKey As String = String.Empty

                ddMember = CType(Me.ucSalesPersonDropDown1.FindControl("dropMember"), DropDownList)
                iMemberId = CInt(ddMember.SelectedValue)

                dtWeekDate = CDate(txtWeek.Text.Trim)

                sDateIdKey = grdWeeklyTime.DataKeys(e.RowIndex).Values("idateID").ToString()

                Dim txtClockIn As System.Web.UI.WebControls.TextBox
                txtClockIn = CType(grdWeeklyTime.Rows(e.RowIndex).FindControl("txtClockInEdit"), TextBox)
                Dim dtClockIn As DateTime = CDate(txtClockIn.Text.Trim)

                Dim txtClockOut As System.Web.UI.WebControls.TextBox
                txtClockOut = CType(grdWeeklyTime.Rows(e.RowIndex).FindControl("txtClockOutEdit"), TextBox)
                Dim dtClockOut As DateTime = CDate(txtClockOut.Text.Trim)

                Call RADB.SP.RelevantYellow.SP_pay_usp_Hours_UPD(iRet, iMemberId, CDate(sDateIdKey), dtClockIn, dtClockOut)

                If iRet <> 0 Then
                    lblMessage.Text = "ERROR: Timesheet was not updated."
                Else
                    lblMessage.Text = "Timesheet updated."
                End If

                e.Cancel = True
                grdWeeklyTime.EditIndex = -1
                grdWeeklyTime.DataBind()
                'Call MemberTimeGet()
  

GridView: EditItemTemplate

Keywords: .Net, GridView, EditItemTemplate, ItemTemplate
<asp:GridView>
	<Columns>
		<asp:templatefield headertext="Name">
			<itemtemplate>
				<asp:label id="FirstName" text= '<%# Eval("fname") %>' runat="server"/>
				<asp:label id="LastName" text= '<%# Eval("lname") %>' runat="server"/>
			</itemtemplate>
			<edititemtemplate>
				<asp:textbox id="Textbox1" text= '<%# Eval("fname") %>' runat="server"/>
				<asp:textbox id="Textbox2" text= '<%# Eval("lname") %>' runat="server"/>
			</edititemtemplate>
		</asp:templatefield>
	</ Columns>
</asp:GridView>

GridView: Events: RowCommand

Keywords: .Net, GridView, RowCommand, ButtonField, e.CommandArgument, e.CommandName
' Page
<asp:ButtonField Text="Void" ButtonType="Link" CommandName="Void" />

' Code Behind
Protected Sub grdMeterCorrection_RowCommand(ByVal sender As Object, ByVal e As 
System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles grdMeterCorrection.RowCommand
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after a ButtonField button in the GridView is clicked.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_iIndex As Integer = Convert.ToInt32(e.CommandArgument)
	Dim f_oSelectedRow As GridViewRow = grdMeterCorrection.Rows(f_iIndex)
	Dim f_oCertIdCell As TableCell = f_oSelectedRow.Cells(11)
	Dim f_sCertId As String = f_oCertIdCell.Text.Trim
	Dim f_oRateAmtLabel As Label = f_oSelectedRow.FindControl("lblRateAmtId")
	Dim f_sRateAmt As String = f_oRateAmtLabel.Text.Trim
 
	If e.CommandName.ToLower = "void" Then
		Dim f_bVoidRet As Boolean = VoidCert(f_sCertId)
	ElseIf e.CommandName.ToLower = "activate" Then
		Dim f_bActivateRet As Boolean = ActivateCert()
	End If
End Sub

GridView: Events: RowDataBound

Keywords: .Net, GridView, RowDataBound, e.Row.Cells, disable checkbox
Protected Sub grdCustomers_RowDataBound(ByVal sender As Object, ByVal e As 
System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles grdCustomers.RowDataBound
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires as the GridView is being constructed (as each row becomes
' databound). Here we check weather or not to disable/enable the Mark Ok
' checkbox.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	If e.Row.RowType = DataControlRowType.DataRow Then
		If e.Row.Cells(1).Text.Trim.Length > 0 Then
			e.Row.Cells(8).Enabled = False
			
			' another way - using Template/HyperLink 
			'Dim f_oHyperLink As System.Web.UI.WebControls.HyperLink
			'f_oHyperLink = e.Row.Cells(8).FindControl("lnkVolAf")

			'If f_oHyperLink.Text.Trim <> e.Row.Cells(9).Text.Trim Then
				'f_oHyperLink.ControlStyle.ForeColor = Drawing.Color.Red
			'Else
				'f_oHyperLink.ControlStyle.ForeColor = Drawing.Color.Black
			'End If
		End If
	End If
End Sub

GridView: Events: RowUpdating

Keywords: .Net, GridView, RowUpdating, .Rows(e.RowIndex).FindControl
Sub grdCustomers_RowUpdating(ByVal o As Object, ByVal e As GridViewUpdateEventArgs) _
Handles grdCustomers.RowUpdating
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after the Update button is clicked. We need to do some
' validating before updated record is sent to DB.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim f_oNameTextBox As System.Web.UI.WebControls.TextBox
f_oNameTextBox = grdCustomers.Rows(e.RowIndex).FindControl("txtName")
Dim f_sName As String = f_oNameTextBox.Text.Trim
End Sub

GridView: Footer

Keywords: .Net, GridView, DataControlRowType.Footer
Protected Sub grdCertified_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles grdCertified.RowDataBound
	If e.Row.RowType = DataControlRowType.Footer Then
		e.Row.Cells(13).ColumnSpan = 3
		e.Row.Cells(13).Text = "Amt Total:"
		e.Row.Cells(13).HorizontalAlign = HorizontalAlign.Right
		e.Row.Cells(14).ColumnSpan = 2
		e.Row.Cells(14).Text = String.Format("{0:C}", Me.CertAmtTotal)
		e.Row.Cells(14).HorizontalAlign = HorizontalAlign.Left
	End If
End Sub

GridView: Freeze Columns

Keywords: .Net, GridView, freeze columns, .StaticColumn, css
' GRIDVIEW
<asp:Panel ID="pnlCustomers" Width="800px" ScrollBars="Horizontal" runat="server">
	<asp:GridView ID="grdCustomers" runat="server">
		<Columns>
			<asp:BoundField DataField="CUST_ID" HeaderText="Customer" 
				ItemStyle-CssClass="StaticColumn" HeaderStyle-CssClass="StaticColumn" />
		</Columns>
	</asp:GridView>
</asp:Panel>
  
                                              
' CSS
.StaticColumn
{      
	background-color:#eeeeee;
	border: none;
	position: relative;
}

GridView: Hide Column

Keywords: GridView, .Net, hide coulum
grdMerchants.Columns(6).Visible = True

GridView: HyperLinkField

Keywords: .Net. GridView, HyperLinkField, DataNavigateUrlFormatString, DataNavigateUrlFields, HyperLink, NavigateUrl
<asp:HyperLinkField HeaderText="Vol Af" DataTextField="Vol Af" DataNavigateUrlFields="METER_ID,OCCUR_PERIOD" 
	DataNavigateUrlFormatString="DailyRounding.aspx?M={0}&O={1}" Target="_new" />
 
' Template Field
<asp:TemplateField HeaderText="Volume"> 
	<ItemTemplate> 
		<asp:HyperLink ID="lnkVolAf" Text='<%# Eval("Volume") %>' NavigateUrl='<%# String.Format(
			"MyPage.aspx?I={0}&P={1}", Eval("ID"), Eval("PERIOD")) %>' Target="_new" runat="server" />
	</ItemTemplate> 
</asp:TemplateField> 

GridView: HyperLinkField: MailTo

Keywords: GridView, HyperLinkField, mailto, DataNavigateURLFields

<asp:HyperLinkField HeaderText="Email" DataTextField="ContactEmail" DataNavigateUrlFields="ContactEmail" DataTextFormatString="<a href=mailto:{0}>{0}</a>" />

GridView: List/Delete Files

Keywords: .Net, GridView, list files, delete file

<asp:GridView ID="grdDocs" runat="server" AutoGenerateColumns="False" Width="100%"
 AlternatingRowStyle-BackColor="#F2F2F2" HeaderStyle-BackColor="#B6B6B6" CellPadding="2"
 Font-Size="11px">
 <Columns>
  <asp:TemplateField>
   <ItemTemplate>
    <asp:HyperLink ID="hypOpenFile" Text='<%# Eval("Name") %>' Target="_new" runat="server" />
   </ItemTemplate>
  </asp:TemplateField>
  <asp:BoundField DataField="LastWriteTime" DataFormatString="{0:d}" HeaderText="Last Write Time">
   <ItemStyle HorizontalAlign="Center" />
  </asp:BoundField>
  <asp:BoundField DataField="Length" DataFormatString="{0:#,### bytes}" HeaderText="File Size" HeaderStyle-HorizontalAlign="Right">
   <ItemStyle HorizontalAlign="Right" />
  </asp:BoundField>
  <asp:TemplateField HeaderText="Delete" HeaderStyle-Width="12px" ItemStyle-Width="12px">
   <ItemStyle HorizontalAlign="Center" Width="30%" />
   <ItemTemplate>
    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
    OnClientClick='return confirm("Are you sure you want to delete this file?");'
    Text="delete" />
   </ItemTemplate>
  </asp:TemplateField>
 </Columns>
 <AlternatingRowStyle BackColor="#F2F2F2"></AlternatingRowStyle>
 <EmptyDataTemplate>
  &nbsp; No documents to display for this merchant.
 </EmptyDataTemplate>
</asp:GridView>

 

 

Protected Sub grdDocs_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) _
    Handles grdDocs.RowDeleting
        e.Cancel = True
        Dim fileName As String = (CType(grdDocs.Rows(e.RowIndex).FindControl("hypOpenFile"), HyperLink)).Text

        Dim dirPath As String
        dirPath = "C:\WebSites\Documents\Customers\" & lblAppId.Text & "\"
        fileName = Path.Combine(dirPath, fileName)
        File.Delete(fileName)
        grdDocs.DataBind()
    End Sub

 

Protected Sub grdDocs_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
    Handles grdDocs.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim f_oHyperLink As System.Web.UI.WebControls.HyperLink
            f_oHyperLink = e.Row.FindControl("hypOpenFile")
            Dim navLink As String = "Documents\Customers\" & lblAppId.Text & "\" & f_oHyperLink.Text.Trim
            f_oHyperLink.NavigateUrl = navLink

  If User.IsInRole("super") <> True Then
                Dim linkButtonDelete As LinkButton = e.Row.FindControl("LinkButton1")
                linkButtonDelete.Visible = False
            End If
        End If
    End Sub

 

    Public Sub GetDocs()
        Try
            Dim dirPath As String
            dirPath = "C:\WebSites\DocumentsCustomers\" & lblAppId.Text & "\"
            Dim dirInfo As DirectoryInfo = New DirectoryInfo(dirPath)
            grdDocs.DataSource = dirInfo.GetFiles()
            grdDocs.DataBind()
        Catch ex As Exception

        End Try
    End Sub

GridView: Pagination: PageIndex

Keywords: .Net, GridView, pagination, PageIndex
Protected Sub btnRetrieve_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnRetrieve.Click
	grdExclusions.PageIndex = 0
End Sub

GridView: RowCommand: DataKeyNames

Keywords: GridView, RowCommand, DataKeyNames
Protected Sub grdOpen_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
    Handles grdOpen.RowCommand
        If e.CommandName.ToLower = "bid" Then
            Dim sidKey As String = grdOpen.DataKeys(e.CommandArgument).Values(0).ToString
            Dim redirURL As String = "ContractorBid.aspx?SID=" & sidKey
            Response.Redirect(redirURL)
        End If
    End Sub

Gridview: RowDataBound: Set Field Value

Keywords: Gridview, RowDataBound, Set Field Value, e.row.cells

Protected Sub grdMerchants_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
    Handles grdMerchants.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If e.Row.Cells(7).Text.Trim = "01/01/1980" Then
                e.Row.Cells(7).Text = String.Empty
            End If
        End If
    End Sub

GridView: RowUpdating: Exit

Keywords: .Net, GridView, RowUpdating, exit, .EditIndex, e.cancel
lblMessage.Text = "Comment updated."
e.Cancel = True
grdComments.EditIndex = -1
grdComments.DataBind()
Exit Sub

GridView: Sort

Keywords: .Net, GridView sort

Private Const ASCENDING As String = " ASC"
    Private Const DESCENDING As String = " DESC"

    Public Property GridViewSortDirection() As SortDirection
        Get
            If ViewState("sortDirection") = Nothing Then
                ViewState("sortDirection") = SortDirection.Ascending
            End If
            Return ViewState("sortDirection")
        End Get
        Set(ByVal value As SortDirection)
            ViewState("sortDirection") = value
        End Set
    End Property

 

Protected Sub grdMerchants_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) _
    Handles grdMerchants.Sorting
        Dim sortExpression As String = e.SortExpression

        If GridViewSortDirection = SortDirection.Ascending Then
            GridViewSortDirection = SortDirection.Descending
            Call GetGridviewData(sortExpression, DESCENDING)
        Else
            GridViewSortDirection = SortDirection.Ascending
            Call GetGridviewData(sortExpression, ASCENDING)
        End If
    End Sub


If Request.QueryString("Search") = Nothing And Request.QueryString("TopSearch") = Nothing Then
            ds = Merchant.GetAgentApps30(Membership.GetUser.UserName, userRole)

            If Not ds Is Nothing Then
                If ds.Tables.Count > 0 And ds.Tables(0).Rows.Count > 0 Then
                    If sortExpression.ToLower <> "na" Then
                        Dim dv As DataView = New DataView(ds.Tables(0))
                        dv.Sort = sortExpression & direction
                        grdMerchants.DataSource = dv
                        grdMerchants.DataBind()
                    Else
                        grdMerchants.DataSource = ds
                        grdMerchants.DataBind()
                    End If
                End If
            End If
        End If

GridView: TemplateField: HyperLink: FindControl

Keywords: .Net, GridView, TemplateField, HyperLink, FindControl

<asp:TemplateField SortExpression="MerchantName">
 <ItemTemplate>
  <asp:HyperLink ID="hypMerchantView" runat="server" Text='<%# Eval("MerchantName") %>'
   NavigateUrl='<%# String.Format("MerchantView2.aspx?AID={0}", Eval("AppId")) %>'></asp:HyperLink>
 </ItemTemplate>
</asp:TemplateField>

<asp:ButtonField ButtonType="Image" ItemStyle-HorizontalAlign="Center" ImageUrl="images/arrow_right.gif" CommandName="GetImplementation" />

 

Protected Sub grdImplementation_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
    Handles grdImplementation.RowCommand
        grdImplementation.DataBind()

        If e.CommandName.ToLower = "getimplementation" Then
            lblMerchName.Text = String.Empty

            Dim f_iIndex As Integer = Convert.ToInt32(e.CommandArgument)
            Dim f_oSelectedRow As GridViewRow = grdImplementation.Rows(f_iIndex)

            Dim f_oAppIdCell As TableCell = f_oSelectedRow.Cells(0)
            Dim f_iAppId As Integer = CInt(f_oAppIdCell.Text.Trim)

            Dim MerchantNameHyperLink As System.Web.UI.WebControls.HyperLink
            MerchantNameHyperLink = f_oSelectedRow.Cells(2).FindControl("hypMerchantView")
            lblMerchName.Text = MerchantNameHyperLink.Text.Trim

            pnlDefault.Visible = False
            pnlSteps.Visible = True

            f_oSelectedRow.BackColor = Drawing.ColorTranslator.FromHtml("#7AA4F0")

            GetImplementation(f_iAppId)
        End If
    End Sub

GUID

Keywords: .Net, GUID
Dim sGuid = New Guid("1CBC11EB-7AEC-4D15-8FAD-85951FD55B6E")

Hashtable

Keywords: .Net 1.1, Hashtable
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

HashTable: 2.0

Keywords: .Net, 2.0, HashTable
Dim ht as new HashTable()
ht.Add("Number", 10)
ht.Add("Name", "Fred Flintstone")
ht.Add("Age", 40)

lblName.Text = ht.Item("Name")

HtmlGenericControl

Keywords: HtmlGenericControl, style, Style.Add, InnerHtml, dynamic logo
<div id="Header" class="clearfix" runat="server"></div>

Private Sub LogoSet()
        Try
            Dim logoCSS As String = " style=""background-image:url('images/back_topnav.gif')"""
            Dim logoCSSFun As String = " style=""background-image:url('images/logo_edge_mavs.gif')"""
            If User.IsInRole("employee") Then
                CType(Me.FindControl("Header"), HtmlGenericControl).Style.Add("background-image", "url('images/logo_edge_mavs.gif')")
            ElseIf User.IsInRole("super") Then
                CType(Me.FindControl("Header"), HtmlGenericControl).Style.Add("background-image", "url('images/logo_edge_mavs.gif')")
            ElseIf User.IsInRole("agent") Then
                CType(Me.FindControl("Header"), HtmlGenericControl).Style.Add("background-image", "url('images/back_topnav.gif')")
            Else
                CType(Me.FindControl("Header"), HtmlGenericControl).Style.Add("background-image", "url('images/back_topnav.gif')")
            End If
        Catch ex As Exception

        End Try
    End Sub

' Add some HTML

Dim someContent As String = "some content I want to show between the DIV tags"

CType(Me.FindControl("Header"), HtmlGenericControl).InnerHtml = someContent



JSON

Keywords: .Net, JSON

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
    <script src="../Includes/select-chain.js" type="text/javascript"></script>
    <script type="text/javascript">
    <!--
   $(function () {
           var cat = $('#categorySelect');
           var el = $('#<%=elementSelect.ClientID%>');

             // note that we're assigning in reverse order
           // to allow the chaining change trigger to work
           cat.selectChain({
               target: el,
               type: "POST",
               url: '../Helper/defaultT.aspx/TT'
           });
    });
    //-->
    </script>  

LineBreak

Keywords: .Net, LineBreak, vbCrLf, Chr(13)
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)

LiteralControl

Keywords: .Net, control, LiteralControl

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

Login/Logout: .Net 1.1

Keywords: .Net 1.1, login, FormsAuthentication, RedirectFromLoginPage, .SetAuthCookie, SignOut, logout, IsAuthenticated
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
 
' Lougout
FormsAuthentication.SignOut()
Response.Redirect("Login.aspx")

Machine.Config

Keywords: .Net 2.0, machine.config, config
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG

MasterPage: Set DefaultButton

Keywords: .Net, C#, MasterPage, set DefaultButton, FindControl, UniqueID

this.BaseMasterPage.Page.Form.DefaultButton = ((LinkButton)this.BaseMasterPage.FindControl("pnlQuery").FindControl("cmdQuery")).UniqueID;

Membership Management : Users and Roles

Keywords: .net, roles, users, membership, reset password, role

' Create Role
Roles.CreateRole("Student")

' Add user to Role
Roles.AddUserToRole("testme", "Student")

' Remove user from Role
Roles.RemoveUserFromRole("testme", "Student")

' Delete User
Membership.DeleteUser("testme")

' Unlock User
Dim mu As MembershipUser = Membership.GetUser("testme")
mu.UnlockUser()
Membership.UpdateUser(mu)

' Reset Password
Dim mu As MembershipUser = Membership.GetUser("testme")
mu.ChangePassword(mu.ResetPassword, "111111") 
 
' Get a User's Role 
If (Roles.IsUserInRole(drpAssignTo.SelectedValue, "agent")) Then

End If 

Membership Provider: GetUser

Keywords: .Net, Membership Provider, GetUser, username, identity

Membership.GetUser.UserName

 

User.Identity.Name

Membership Provider: Setup

Keywords: .Net, Membership Provider, aspnet_regsql.exe, SQL

Setup Provider to work with MS SQL 7.0, 2000, 2005, or 2008.

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

aspnet_regsql.exe


 

Membership Provider: Setup SQL

Keywords: .Net, membership provider, setup, SQL, Aspnet_regsql.exe

http://bloggingabout.net/blogs/dennis/archive/2007/12/01/configuring-an-asp-net-membership-provider-instead-of-localsqlserver.aspx

The Aspnet_regsql.exe file is located in the [drive:]\%windir%\Microsoft.NET\Framework\version folder on your Web server.

 

http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx

Membership: Get UserId/GUID

Keywords: .net, membership, UserId, GUID
Dim UserID As String
Dim MemUser As MembershipUser
MemUser = Membership.GetUser()
UserID = MemUser.ProviderUserKey.ToString()

New in .Net 3.5

Keywords: .Net, new, 3.5
- Integrated ASP.NET AJAX support 
- The ListView control
- The DataPager control 
- Enhanced CSS editing capabilities 
- JavaScript IntelliSense and debugging
- Ability to mutli-target framework versions

Nothing

Keywords: .Net, nothing
' Integer
If Not f_iBase = Nothing Then

End If

' String
If Not f_sBase Is Nothing Then

End If

NULL

Keywords: .Net, null, DBNull
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

Nullable: HasValue

Keywords: .Net, HasValue, Nullable, decimal
We can set a decimal to nullable and then check if it has value later on.
Dim TotalCertified As Nullable(Of Decimal)
TotalAvail = QueryTA.GetVolAvailableToCertify(CDec(Me.OccurPrdTextBox.Text), Me.ddlAgency.SelectedValue)
If TotalAvail.HasValue Then
	Dim AccountTA As New WINS.DataTier.AccountInfoTableAdapters.12B_ACCT_CONTRACTTableAdapter
	Dim ContractsCount As Data.DataTable
	ContractsCount = AccountTA.GetOpenContracts(Me.BillAgency , Me.DeliveryAgency, "SSS", Me.OccurPeriod)
	 
	Dim ContractsTA As New WINS.DataTier.AccountInfoTableAdapters.12B_ACCT_CONTRACTTableAdapter
	Dim ContractsTable As WINS.DataTier.AccountInfo.WINS_ACCT_CONTRACTDataTable = ContractsTA.GetOpenContracts (Me.BillAgency, 
		Me.DeliveryAgency, "SSS", Me.OccurPeriod)
	If ContractsTable.Rows.Count = 0 Then
	
	End If
End If

Number: Format

Keywords: .Net, number, format, :c
<!-- 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)

Number: Rounding

Keywords: .Net, number, rounding, Math.Round, MidpointRounding, decimal
Dim f_cExample As Decimal = 4.346

' 4.35
Dim f_cRounded1 As Decimal = Math.Round(f_cExample, 2, MidpointRounding.AwayFromZero)
 
' 4.34
Dim f_cRounded2 As Decimal = Math.Round(f_cExample, 2, MidpointRounding.ToEven)

Object Test Bench

Keywords: .Net, Object Test Bench

Working with Immediate Window has one major drawback: it requires a lot of typing without any kind of support from the IDE. There is however an alternative way to call your methods using Visual Studio Object Test Bench.

(1) Set your project as the StartUp Project.
(2) Switch to Class View.
(3) Select the method. EX: {}Store {}DataTier {}InvoiceInfo.
(4) Right click on method and select: Create Instance : New().
(5) You should see the Object Test Bench window at the bottom. Right click on your instance and
    select: Invoke Method : (select method).
http://vaultofthoughts.net/ObjectTestBench.aspx

ObjectDataSource: Control Parameter

Keywords: .Net, ObjectDataSource, ControlParameter, FormParameter, ControlID, OldValuesParameterFormatString, SelectMethod, SelectParameters

<asp:ObjectDataSource ID="odsPrograms" runat="server" OldValuesParameterFormatString="original_{0}"
    SelectMethod="GetProgram" TypeName="WINS.DataTier.CertificationInfoTableAdapters.CERT_LPPTableAdapter">
    <SelectParameters>
        <asp:ControlParameter ControlID="ddlMeters" Name="cmbMeter" PropertyName="SelectedValue" Type="String" DefaultValue="N/A" />
        <asp:ControlParameter ControlID="OccurPrdTextBox" Name="dfOCCUR_PERIOD" PropertyName="Text" Type="String" DefaultValue="N/A" />
    </SelectParameters>
</asp:ObjectDataSource>

 

' ControlParameter vs. FormParameter in a MasterPage

http://www.mandsconsulting.com/aspcontrolparameter-vs-aspformparameter-in-master-page
 

Optional Parameter

Keywords: .Net, function, method, optional parameter
Public Shared Function ProfileSubscription_OUT(ByRef RETURN_VALUE As Int32, ByVal iMemberID As Int32, Optional ByRef ProductName As String = Nothing)

Overload Methods

Keywords: .Net, overloads
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.
Public Overloads Function GetPersonInfo(ByVal v_sFirstName As String)

End Function

Public Overloads Function GetPersonInfo(ByVal v_lPersonId As Long)

End Function

Page: Close: Unsaved Changes

Keywords: .Net, page, postback, window.onbeforeunload, JavaScript, window.event, OnSubmitScript, unsaved changes
Check if Postback before processing some javascript. If user made changes on the form but did not save,
they are prompted...
' PAGE
<script language="javascript">
<!--
var g_isPostBack = false;

window.onbeforeunload = function ()
{
 if( g_isPostBack == true )
  return; // Let the page unload

 if ( window.event )
  window.event.returnValue = 'You will lose any unsaved changes!'; // IE
 else
  return 'You will lose any unsaved changes!'; // FX
}
//-->
</script>

' CODE BEHIND
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles MyBase.Load
	
    RegisterOnSubmitStatement("OnSubmitScript", "g_isPostBack = true;")
End Sub

Page: Life-Cycle

Keywords: .Net, page, life cycle, PreInit, PreLoad, PreRender
PreInit
Init
InitComplete
PreLoad
Load
Control Events
Load Complete
PreRender
SaveStateComplete
Render
Unload
http://msdn.microsoft.com/en-us/library/ms178472.aspx#databindingevents

Page: PreRenderComplete

Keywords: .Net, page, PreRenderComplete
Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
	Me.CertSingleVolumeEntry1.EnableEditButtons(Me.CertIDGenerator1.SelectedCertStatus)
	Me.UpdatePanel5.Update()
End Sub

PageMethod: Call Method After Window Close

Keywords: .Net, Web Services, WebMethod, ScriptMethod, scriptmanager, close window
Exposing Web Services to client script...
<asp:scriptmanager id="ScriptManager1" runat="server" enablepagemethods="true" />

<body onunload="HandleClose()">

<script language="javascript" type="text/javascript">
  //<![CDATA[
  function HandleClose() 
   {
		if(window.event.clientY < 0 && window.event.clientY < -80)
		{
			PageMethods.DeleteCart();
		}
   }
   //]]>
</script>
 
' CODE
<WebMethod(EnableSession:=True)> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Xml, _
            XmlSerializeString:=True)> _
    Public Function DeleteCart() As String
        Dim f_bRet As Boolean = False
        f_bRet = DeleteCart()
        If f_bRet = False Then
            Return False
        End If

        Return True
    End Function

Panel: Hide/Show

Keywords: .Net, panel, hide show
Me.Panel1.Style.Item("display") = "none" 
Me.Panel1.Style.Item("display") = ""

Parallel Threads

Keywords: threading, Parallel.Invoke, functional programming


Imports System.Threading

 

Parallel.Invoke(

     Sub()

          Console.WriteLine("Task 1")

          Thread.Sleep(1200)

     End Sub,

 

     Sub()

          Console.WriteLine("Task 2")

          Thread.Sleep(1000)

     End Sub

)

PopUp Window: Button Click: Return

Keywords: .Net, JavaScript, popup window, return, button click, ClientScript.GetPostBackEventReference, EVENTTARGET
1. 

' CODE BEHIND (ORIGINAL PAGE)

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles MyBase.Load

	' OBSOLETE: Me.GetPostBackEventReference(Me, String.Empty)
	ClientScript.GetPostBackEventReference(Me, String.Empty)

	If Not Page.IsPostBack Then
		Call SetDefaults()
	Else
		Dim f_sEventTarget As String = IIf((Me.Request("__EVENTTARGET") Is Nothing), String.Empty, _
			Me.Request("__EVENTTARGET"))

		If f_sEventTarget = "PostBackFromChildWindow" Then
			Call BindAllGrids()
		End If
	End If
End Sub

Protected Sub btnMeterCorrection_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMeterCorrection.Click
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' This event fires after the Meter Correction button is clicked.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	lblMessage.Text = String.Empty

	Dim f_oTextBoxInvNum As TextBox = Me.fmvAgencyInvoice.FindControl("txtInvNum")
	Dim f_oTextBoxInvNumVer As TextBox = Me.fmvAgencyInvoice.FindControl("txtVersion")
	Dim f_oTextBoxBillPeriod As TextBox = Me.fmvAgencyInvoice.FindControl("txtBillPeriod")

	Dim f_sPath As String = "MeterCorrection.aspx?A=" & drpAgencies.SelectedValue & "&I=" & _
	f_oTextBoxInvNum.Text.Trim & "&V=" & f_oTextBoxInvNumVer.Text.Trim & "&B=" & _
	f_oTextBoxBillPeriod.Text.Trim

	Call Popup(f_sPath)
End Sub

Private Sub Popup(ByVal sPath As String)
	Dim lbl As New Label
	lbl.Text = "<script language='javascript'>" & _
		"window.open('" & sPath & "','popupWindow','1000,600,resizable=yes,scrollbars=yes');</script>"
	Page.Controls.Add(lbl)
End Sub

' PAGE (ORIGINAL PAGE)
<asp:LinkButton ID="btnMeterCorrection" Text="Meter Correction" 
ForeColor="#0000ff" CausesValidation="false" runat="server" />

' PAGE (POPUP PAGE)
<asp:LinkButton ID="btnExit" Text="Exit" OnClientClick="window.opener.__doPostBack('PostBackFromChildWindow', ''); 
	window.close(); return false;" runat="server" />
2. 

<asp:LinkButton ID="btnMeterCorrection" Text="Meter Correction" ForeColor="#0000ff" 
CausesValidation="false" runat="server" OnClientClick="javascript:window.open('MeterCorrection.aspx', 
'window_name', 'width=1000, height=600, resizable=yes, scrollbars=yes');" />

OR

Me.btnMeterCorrection.Attributes.Add("onclick",
"javascript:window.open('MeterCorrection.aspx', 'window_name',
'width=1000, height=600, resizable=yes, scrollbars=yes');")

Prime Calculator

Keywords: C#, calculator, prime
namespace primecalculator
{
  public class PrimeCalculator
  {
    public bool IsPrime(int x)
    {
      if(x <= 1)
        return false;
      else
      {
        for(int i = 2; i < ((x/2) + 1) ; i++)   //the largest integer that can divide integer 'x' is half of 'x' (i.e., x/2).
        {
          int num = i,incrementednumber = i;
          while(true)
          {
            if(incrementednumber == x)
              return false;
            else if(incrementednumber > x)
              break;
            else
              incrementednumber = incrementednumber + num;
          }
        }
        return true;
      }
      
     // return false;
    }

    public int NextPrime(int x)
    {
       int NextPrime = x + 1;bool flag = true;
       while(true)
       {
       for(int i = 2; i < ((NextPrime/2) + 1) ; i++)   //the largest integer that can divide integer 'x' is half of 'x' (i.e., x/2).
        {
          int num = i,incrementednumber = i;
          while(true)
          {
            if(incrementednumber == NextPrime)
            {
              flag = false;
              break;
            }
            else if(incrementednumber > NextPrime)
            {
              flag = true;
              break;
            }
            else
              incrementednumber = incrementednumber + num;
          }
          
          if(!flag)
          {
            break;
          }
          
        }
        if(flag)
          return NextPrime;
        else
            NextPrime++;
       }
     // return 0;
    }
    
    public int PrimesCount(int x, int y)
    {
      int count = 0;bool flag =true;
       for(int j = x; j <= y; j++)
       {
       for(int i = 2; i < ((j/2) + 1) ; i++)   //the largest integer that can divide integer 'x' is half of 'x' (i.e., x/2).
        {
          int num = i,incrementednumber = i;
          while(true)
          {
            if(incrementednumber == j)
            {
              flag = false;
              break;
            }
            else if(incrementednumber > j)
            {
              flag = true;
              break;
    &nb

Proper Case

Keywords: proper case, StrConv, VbStrConv, string
StrConv(txtFirstName.Text.Trim, VbStrConv.ProperCase)

RegisterStartupScript: Window.Open

Keywords: .Net 1.1, 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)

Remove items from a DropDown

Keywords: Dropdown, remove items
drpBackColor.Items.Remove(ddl.Items.FindByText("Orange"));
drpBackColor.Items.Remove(ddl.Items.FindByText("Maroon"));

Repeater

Keywords: .Net 1.1, Repeater, SeperatorTemplate
<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>

Reverse String

Keywords: reverse string, string, C#
public static string Reverse(string Input)
        {
          int len= Input.Length;
          char[] s= new char[len];
          for(int i= 0;i<len;i++)
          {
            s[i]=Input[len-1-i];
          }
            return new string(s);
        }

Roles: BitWise

Keywords: .Net 1.1, bitwise operation, role, user
If ((m_iRole And 8) = 8) Then
	' User is an admin...
	
Else
	' Not an admin...
	
End If

RSS

Keywords: .Net, RSS
Imports System.Xml

Private Sub ProcessRSSItem(ByVal rssURL As String)
        Dim myRequest As WebRequest = System.Net.WebRequest.Create(rssURL)
        Dim myResponse As WebResponse = myRequest.GetResponse()

        Dim rssStream As Stream = myResponse.GetResponseStream()
        Dim rssDoc As New XmlDocument()
        rssDoc.Load(rssStream)

        Dim rssItems As XmlNodeList = rssDoc.SelectNodes("rss/channel/item")

        Dim title As String = ""
        Dim link As String = ""
        Dim description As String = ""
        Dim i As Integer
        Dim rssString As String

        For i = 0 To rssItems.Count - 1
            ' Only show 6
            If i = 6 Then Exit For

            Dim rssDetail As XmlNode

            rssDetail = rssItems.Item(i).SelectSingleNode("title")
            If rssDetail.Equals(Nothing) = False Then
                title = rssDetail.InnerText
            Else
                title = ""
            End If

            rssDetail = rssItems.Item(i).SelectSingleNode("link")
            If rssDetail.Equals(Nothing) = False Then
                link = rssDetail.InnerText
            Else
                link = ""
            End If

            rssString = rssString & "<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/><br/>"
        Next
        lblRSS.Text = rssString
    End Sub


<asp:Label ID="lblRSS" runat="server"></asp:Label>

Securuty: ValidateRequest

Keywords: .Net, security, ValidateRequest, HTMLEncode

.Net has built in security to prevent HTML tags from being entered into form fields.

' Enable built-in security
<%@ Page Language="VB" CodeFile="Comments.aspx.vb" Inherits="Invoice_Comments" ValidateRequest="true" %>

' Disable and handle manually
<%@ Page Language="VB" CodeFile="Comments.aspx.vb" Inherits="Invoice_Comments" ValidateRequest="false" %>

f_sInvoiceComments = Server.HtmlEncode(f_sInvoiceComments)

Send SMTP Using Command Line

Keywords: SMTP, command line, SMTPMAIL.EXE
SMTPMAIL.EXE from=example@smptinfo.com to=example@smtpinfo.com body="Hello World!" subject=Example server=smtp.smtpinfo.com

SetFocus: C#

Keywords: .Net, C#, SetFocus, StringBuilder, Page.RegisterStartupScript, focus
// .Net 1.1
private void SetFocus(String ctrlID)
{
 // Build the JavaScript String
 System.Text.StringBuilder sb = new System.Text.StringBuilder();
 sb.Append("")

 // Register the script code with the page.
 Page.RegisterStartupScript("FocusScript", sb.ToString());
}
// .Net 2
void Page_Init(object sender, EventArgs e)
{
 SetFocus(ControlToSetFocus);
}

// OR (call in Page_Load)
TextBox1.Focus();

SortedList

Keywords: .Net 1.1, SortedList, DictionaryEntry, System.Collections
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

Source Control: Settings

Keywords: .Net, source control, settings
Toos|Options|Source Control

SQL Injection: Prevent using Parameters

Keywords: SQL, injection, parameters

 Dim objConn
  Dim adOpenForwardOnly, adLockReadOnly, adCmdText, adCmdTable, adCmdStoredProc
  Dim adInteger, adVarWChar, adParamReturnValue, adParamInput, adParamOutput
  Dim adChar, adVarChar, adDate
  Dim adUseClient
 
  Const adLongVarChar = 201
  Const adBoolean = 11
   
  adOpenForwardOnly = 0
  adLockReadOnly    = 1
  adCmdText         = 1
  adCmdTable        = 2
  adCmdStoredProc   = 4

  adParamInput      = 1
  adParamOutput     = 2
  adParamReturnValue = 4

  adUseClient       = 3

  adInteger         = 3
  adChar            = 129
  adVarChar         = 200
  adVarWChar        = 202
  adDate            = 7

  Set objConn   = Server.CreateObject("ADODB.Connection")

  objConn.CursorLocation = adUseClient  ' Required to get Output Parameters
  objConn.Open  "Provider=SQLOLEDB;Data Source=raweb02.relevantads.com;Database=ibls;" & _
                "User ID=ibls_user;Password=hotel7H;"

objComm.CommandType = adCmdText
 objComm.CommandText = "Insert into LawJournal (NW_Headline,NW_Body,NW_Status,NW_AdditionDate,NW_ModificationDate)  values(?,?,?,?,?)"
 objComm.Parameters.Append (objComm.CreateParameter("NW_Headline",adChar,adParamInput,1000,Request("title")))
 objComm.Parameters.Append (objComm.CreateParameter("NW_Body",adLongVarChar,adParamInput,2147483647,artBody))
 objComm.Parameters.Append (objComm.CreateParameter("NW_Status",adBoolean,adParamInput,,Status))
 objComm.Parameters.Append (objComm.CreateParameter("NW_AdditionDate",adDate,adParamInput,,now()))
 objComm.Parameters.Append (objComm.CreateParameter("NW_ModificationDate",adDate,adParamInput,,now()))


 Set objComm.ActiveConnection = objConn
 objComm.Execute

SSL Switching

Keywords: ssl, force, switching, https, .Net


YOUTUBE: http://www.youtube.com/watch?v=Q_gVxaXHM7U&feature=youtube_gdata_player

 

http://kojiroh.wordpress.com/2006/09/06/hello-world/

 

http://forums.asp.net/p/1624044/4179211.aspx#4179211

 

 

Starter Kit: Time Tracker

Keywords: .Net, starter kit, time tracker
(1)
RUN
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe

(2)
ATTACH DB

EXEC

sp_attach_single_file_db @dbname = 'TimeTracker',
@physname = 'D:\Websites\TimeTracker\App_Data\TimeTracker.mdf'

Stored Procedure

Keywords: .Net, stored procedure, sp, proc, CommandType.StoredProcedure
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Function Delete(ByVal vDataSourceID As Integer) As Boolean
	Dim f_oConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
	Dim f_oCommand As New SqlCommand("dc_source_delete", f_oConnection)

	f_oCommand.CommandType = CommandType.StoredProcedure

	Dim f_iDataSourceID As New SqlParameter("@data_source_id", SqlDbType.Int, 4)
	f_iDataSourceID.Value = vDataSourceID
	f_oCommand.Parameters.Add(f_iDataSourceID)

	f_oConnection.Open()
	f_oCommand.ExecuteNonQuery()
	f_oConnection.Close()

	Return True
End Function

String: IndexOf: C#

Keywords: .Net, C#, IndexOf, Console.WriteLine, ReadLine, String
string x = "yyy ntp est";

if (x.IndexOf("np") != -1)
{
	Console.WriteLine("valid");
	Console.ReadLine();
}
else
{
	Console.WriteLine("in-valid");
	Console.ReadLine();
}

String: IndexOf: VB

Keywords: .Net, VB, string, IndexOf
If f_sReturn.ToUpper.IndexOf("ALREADY EXISTS") <> -1 Then
	'...
End If

String: IsNullOrEmpty

Keywords: IsNullOrEmpty, NULL, .Net, String

If Not String.IsNullOrEmpty(dr("M2SharePercentage").ToString) Then txtAgentsRevenueShareM2.Text = dr("M2SharePercentage").ToString

String: StartsWith: C#

Keywords: .Net, C#, string, StartsWith
private string VerifyMessage(string subject)
{
	if (subject.ToLower().StartsWith("np"))
	{
		return "NPTest.txt";
	}
	else if (subject.ToLower().StartsWith("sonoma"))
	{
		return "sonoma.txt";
	}
	else
	{
		return "";			
	}
}

String: Substring

Keywords: .Net, string, substring
' 121094754 (returns 10947)
Me.DealID = Request.Params("DID").Substring(2, 5)

' 121094754 (returns 1094754)
Me.DealID = Request.Params("DID").Substring(2)

String: SubString

Keywords: .Net, String, SubString
Dim f_sCurrentBPYear As String = Me.CurrentBillPeriod.Substring(0, 4)

Style

Keywords: .Net, style.Add

' 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" />

StyleSheet: Dynamically Load

Keywords: .Net, .css, dynamically load, StyleSheet

<link id="stlCWA" rel="stylesheet" type="text/css" runat="server" />

 

If ProfileId = 60947 Or ProfileId = 61639 Then
           stlCWA.Attributes.Add("href", "/cwa/css/style_maroon.css")
Else
            stlCWA.Attributes.Add("href", "/cwa/css/style.css")
End If

Submit to Another Page: .Net 1.1

Keywords: .Net 1.1, submit to another page, Context.Handler, DataGridCommandEventArgs, DataGrid, e.CommandName, ButtonColumn
' 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

TableAdapter

Keywords: .Net, TableAdapter

Check if any rows returned...

Dim f_oTableAdapter As New ChargeInfoTableAdapters.CHG_CHARGESTableAdapter
Dim f_oTable As ChargeInfo.CHG_CHARGESDataTable
f_oTable = f_oTableAdapter.GetBaseChargeNull()
If f_oTable.Rows.Count = 0 Then
	e.Row.Cells(12).Enabled = False
Else
	e.Row.Cells(12).Enabled = True
End If
f_oTableAdapter.Dispose()
 
Grab record values...
Dim f_oTableAdapter As New ChargeInfoTableAdapters.RULE_SETTableAdapter
Dim f_oTable As DataTier.ChargeInfo.RULE_SETDataTable = f_oTableAdapter.GetComment(drpNonStandard.SelectedValue)
If Not f_oTable.Rows.Count = 0 Then
	Dim f_oRow As DataTier.ChargeInfo.RULE_SETRow = f_oTable.Rows(0)
	txtComment.Text = f_oRow.DESCR.Trim
End If
f_oTableAdapter.Dispose()
 
Return string value...
Dim f_oOkTableAdapter As New InvoiceInfoTableAdapters.WINS_INV_CRCTableAdapter
Dim f_sOk As String = f_oOkTableAdapter.CCSetupCheckOk(drpAgencies.SelectedValue, f_sStartPeriod, f_sEndPeriod)
If Not f_sOk Is Nothing Then
	If f_sOk.Length > 0 Then
		lblMessage.Text = "An error occurred. The corresponding invoice has already been Ok'd."
		Exit Sub
	End If
End If
f_oOkTableAdapter.Dispose()
 
Return one value...
Dim CurrBillPeriod As Nullable(Of Decimal)
Dim BillPrdTA As New WINS.DataTier.CertificationInfoTableAdapters.QueriesTableAdapter
CurrBillPeriod = BillPrdTA.GetCurrentBillPeriod
If CurrBillPeriod.HasValue = True Then
	Me.CurrentBillPeriod = CurrBillPeriod.Value
Else
	lblMessage.Text = "An error occurred. Current Bill Period was not retrieved from the database."
	Exit Sub
End If
Return count...
Dim f_oTableAdapter As New InvoiceInfoTableAdapters.INV_METER_BILLEDTableAdapter
Dim f_iCount As Integer = f_oTableAdapter.GetDisableEnable(f_oTextBoxInvNum.Text.Trim)
If f_iCount > 0 Then
	btnMeterCorrection.Enabled = True
Else
	btnMeterCorrection.Enabled = False
End If
f_oTableAdapter.Dispose()
Process and check return value...
Dim f_oTableAdapter1 As New InvoiceInfoTableAdapters.INV_MASTER_CHARGESTableAdapter
Dim f_sReturn1 As String = String.Empty
f_sReturn1 = f_oTableAdapter1.MasterChargesInsert(drpAgencies.SelectedValue)
If f_sReturn1.ToLower = "record inserted" Then
	f_sBillingPeriod = f_sBillingPeriod + 1
Else
	lblMessage.Text = "An error occurred. Please contact support and report the following: " & f_sReturn1
	Exit Sub
End If

Textbox Linebreaks

Keywords: textbox, linebreak, sql, .net, vbCrLf

(1) Send textarea content to DB...

Dim code As String = txtCode.Text.Trim.Replace(vbCrLf, "<br>")

Server.HtmlEncode(code)

(2) Display content from DB in GridView TemplateField...

<%#Eval("Code").Replace("&lt;br /&gt;", "<br>")%>

Timeout: Command

Keywords: .Net 1.1, Timeout, CommandTimeout, command
f_oCommand.CommandTimeout = 3000

Trace

Keywords: .Net, trace, error handling
Trace.IsEnabled = True

Trace.Warn("Control Loop Begin")

User Control: Access Parent Page

Keywords: .Net, DirectCast, FindControl, Me.Parent.Page

Access a control (label) on a parent page from a User Control.

 

qsLang = DirectCast(Me.Parent.Page.FindControl("lblLang"), Label).Text

UserControl: Property

Keywords: .Net, user control, .ascx, property

' PAGE

<%@ Register TagPrefix="Bravo" Tagname="Head" src="controls/Head.ascx" %>

<Bravo:Head ID="Head1" Name="Head1" CurrentPage="home" Runat="server" />


' USER CONROL CODE

Public CurrentPage As String

If Me.CurrentPage.ToLower = "home" Then
	tabHome.ImageUrl = "\images\tab_home_on.gif"
End If

UserControl: Reference a Control

Keywords: .Net, UserControl, reference, dropdown, C#

Referencing the dropdown that is located in the UserControl from the code behind of a web form.

 

x = ((DropDownList)UC1.FindControl("DD1")).SelectedItem.Value;

Using

Keywords: .Net, using

You can now write code that uses disposable resources without having to author your own Try/Finally blocks, just like in C#.

 

Using conn As New SqlConnection(dsn)
  Using cmd As New SqlCommand("SELECT * FROM Employees", conn)
    conn.Open()
      Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
          Console.WriteLine(rdr(0))
        End While
      End Using
  End Using
End Using

Validation Contorl: RegularExpression

Keywords: .Net, validation, RegularExpression, allow negative, decimal, integer

Numeric - Integer (positive, no decimal)

<asp:RegularExpressionValidator ID="regRateType" ControlToValidate="txtRateType" ValidationExpression="^\d+$" 
ErrorMessage="Invalid Rate Type. Valid value: 111" runat="server" />

Numeric - Integer (6 digits only)

<asp:RegularExpressionValidator ID="regBillPeriod" ControlToValidate="txtBillPeriod" Font-Size="8pt" 
Display="Dynamic" ErrorMessage="Invalid Bill Period. Valid format: YYYYMM." runat="server" 
ValidationExpression="\d{6}" />	

Numeric - Decimal

 

<asp:RegularExpressionValidator ID="regAmount" ControlToValidate="txtAmount" Font-Size="8pt"
Display="Dynamic" ErrorMessage="Invalid Amount. Valid format: 1234567.123456 or 1234567."
runat="server" ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$" />

 

Numeric - Decimal


<asp:RegularExpressionValidator ID="regCCFlow" ControlToValidate="txtCCFlow" Font-Size="8pt"
Display="Dynamic" ErrorMessage="Invalid CC Flow. Valid format: 1234567.12 or 1234567." runat="server"
ValidationExpression="^\d+(\.\d\d)?$" />

 

Numeric - Decimal (allow negative)

 

<asp:RegularExpressionValidator ID="regBillAmount" ControlToValidate="txtBillAmount" Font-Size="8pt"
Display="Dynamic" ErrorMessage="Invalid Bill Amount. Valid format: 1234567.12 or 1234567."
runat="server" ValidationExpression="^(-)?\d+(\.\d\d)?$" />

 

Multiline Length Validation

<%@ Register Assembly="Validators" Namespace="Sample.Web.UI.Compatibility" TagPrefix="cc1" %>

<cc1:RegularExpressionValidator ID="regComments" ControlToValidate="txtComments" Display="Dynamic" 
	ErrorMessage="Maximum length is 30 characters" ValidationExpression=".{0,30}" runat="server" />

Validation Control: Custom

Keywords: .Net, validation control, custom

' CODE

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

' PAGE

<asp:CustomValidator id="vldState" OnServerValidate="StateValidate" ControlToValidate="txtState" 
Display="None" ErrorMessage="State must be 2 characters." runat="server" />

Validation Control: Custom: Client Side

Keywords: .Net, validation control, custom, 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" />

Validation Controls

Keywords: .Net, validation, control, ValidationSummary, CustomValidator, RegularExpressionValidator
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
' REQUIRED
<asp:RequiredFieldValidator id="vldCompanyName" ControlToValidate="CompanyName" Display="dynamic" 
ErrorMessage="Enter your company name." runat="server" />
' DATES

<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" />
' EMAIL

<asp:CompareValidator id="vldCompareEmail" ControlToValidate="txtConfirmEmail" ControlToCompare="txtEmail" 
Display="Dynamic" ErrorMessage="Emails do not match." runat="server" />
' REGULAR EXPRESSION
<asp:RegularExpressionValidator id="vldEmail" ControlToValidate="txtEmail" 
ValidationExpression="[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+" Display="None" 
ErrorMessage="'Email' is invalid." runat="server" />
' SUMMARY
<asp:ValidationSummary ID="vldSummary" HeaderText="Please correct the following error(s):" 
DisplayMode="BulletList" ShowMessageBox="True" ShowSummary="False" Runat="server" />
' CUSTOM
<asp:CustomValidator id="ccNumCustVal" ControlToValidate="ccNum" ErrorMessage="Card Number." 
clientvalidationfunction="ccClientValidate" Display="Static" runat=server />

Web Parts

Keywords: .Net, Web Parts
http://ondotnet.com/pub/a/dotnet/2005/06/06/webparts_2.html

Web Service

Keywords: .Net, web service

Call a web service upon browser close. Page uses a MasterPage so it needs a ScriptManagerProxy.

 

APP_CODE/InvoiceLocking.vb

Imports 12Bravo.DataTier
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class InvoiceLocking
    Inherits System.Web.Services.WebService

    <WebMethod(EnableSession:=True)> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Xml, _
            XmlSerializeString:=True)> _
    Public Function UnlockInvoices() As String
        Try
            Dim f_oTableAdapter1 As New InvoiceInfoTableAdapters.WINS_INVTableAdapter
            Dim f_sReturn1 As String = String.Empty
            f_sReturn1 = f_oTableAdapter1.UnlockInvoices()
            If f_sReturn1.ToLower = "record deleted" Then
                Return "True"
            Else
                Return "False"
            End If
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function
End Class
 
Invoice.aspx
<%@ Page Language="VB" MasterPageFile="MasterPage.master" AutoEventWireup="false" CodeFile="Invoice.aspx.vb" 
	Inherits="Invoice_Agency" title="Invoice" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebServices/InvoiceLocking.asmx" />
        </Services>
    </asp:ScriptManagerProxy>
    <script language="javascript" type="text/javascript">
    //<![CDATA[    
    window.onunload = HandleClose;
    
    function HandleClose() 
    {
        if(window.event.clientY < 0 && window.event.clientY < -80)
	    {
            //alert('Calling Unlock');
            InvoiceLocking.UnlockInvoices();
	    }
    }
    //]]>
    </script>


 

Web Service

Keywords: .Net 1.1, web services, WebMethod
<%@ 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

Web Service: OnBeforeUnload

Keywords: javascript, .Net, Web Service, AsyncPostBackTimeout, .asmx,


'Run a server side process (Web Service) after browser close button click.


<body id="mybody"  onbeforeunload="releaseLocks();">

<form id="Form2"  runat="server">
 <asp:ScriptManager ID="ScriptManager1" AsyncPostBackTimeout="360000" runat="server">
  <Services>
   <asp:ServiceReference Path="~/WebServices/CertLocking.asmx" />
  </Services>
 </asp:ScriptManager>

<script language="JavaScript">
<!--
var certIsLocked=false;

function releaseLocks(){
 if(document.activeElement.protocol!="http:" ){
  //do nothing - this is a javascript call or the active element
  //does not have a protocol property
 }
 else if(document.activeElement.protocol=="undefined"){
  //some other tag type?
 }
 else {
  if (certIsLocked==true){
   try{
    CertLocking.UnlockCerts();
   }
   catch(err){
   }                 
  }
                
 }          
}
// -->
</script>

Web.Config: Authorization: All Secure Except One

Keywords: .Net, web.config, authorization, allow users
<configuration>
<location path="CardInquiry.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>

Web.Config: Authorization: Deny All

Keywords: .Net 1.1, web.config, security, deny users, authorization
<configuration>
	<system.web>
		<authentication mode="Forms">
			<forms name="AuthCookie" loginUrl="login.aspx" protection="All" path="/" />
		</authentication>
		<authorization>
			<deny users="?" />
		</authorization>
	</system.web>
</configuration>

Web.Config: Authorization: Deny Specific Page

Keywords: .Net 1.1, web.config, authorization, deny users
<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>

Web.Config: Basic: 1.1

Keywords: .Net 1.1, web.config
<?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>

Web.Config: Connection String: 2.0

Keywords: .Net, web.config, connection string, configuration, C#
<configuration>
	<connectionStrings>
		<add
		name="MyConnectionString"
		providerName="System.Data.SQLClient"
		connectionString="Data Source=SQL01; Initial Catalog=Store; User ID=sa; Password=111111" />
	</connectionStrings>
</configuration>
' CODE
ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
' C#
using System.Configuration;

SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["CHGSQL"].ConnectionString);

Web.Config: Connection String: Access: 1.1

Keywords: .Net 1.1, connection string, conn string, appSettings, 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: Connection String: SQL: 1.1

Keywords: .Net 1.1, Web.Config, connection string, sql, appSettings
' WEB.CONFIG
<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

Web.Config: ExecutionTimeout

Keywords: Web.Config, ExecutionTimeout, timeout
<location path="Charges/Process.aspx">
	<system.web>
		<httpRuntime executionTimeout="300000"/>
	</system.web>
</location>

Web.Config: Keys

Keywords: .Net 1.1, web.config, keys, ConfigurationSettings.AppSettings, System.Configuration
<?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

Web.Config: Roles

Keywords: .Net, Web.Config, roles, allow, deny, authorization
<location path="Invoice/EmailAddresses.aspx">
    <system.web>
      <authorization>
        <allow roles="12bAdmin" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>

Website Administration Tool

Keywords: .Net, Website Administration Tool, roles, users, settings

Administer users, roles, and authorization settings.

URL: http://localhost:3057/asp.netwebadminfiles

Or go to Website/ASP.Net Configuration

Windows Service

Keywords: .Net, C#, Windows Service, installutil

// C#

http://www.aspfree.com/c/a/C-Sharp/Timer-Objects-in-Windows-Services-with-C-sharp-dot-NET/1/


Install: C:\> cd windows\microsoft.net\framework\v1.1.4322

C:\windows\microsoft.net\framework\v1.1.4322> installutil c:\services\MyService.exe

 

UnInstall: C:\windows\microsoft.net\framework\v1.1.4322> installutil /u c:\services\MyService.exe 
 
' make sure that your ServiceProcessInstaller1 Account property is set to: "LocalSystem"

XSD File

Keywords: .Net, XSD file

Rather than calling a function in a .vb file, here is an example of calling a Method built into an .xsd file. The XSD file allows you to add TableAdapters.

 

Private Sub CommentsGet()
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' Populate the Comments textbox -- Rule #7.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_oTableAdapter As New ChargeInfoTableAdapters.12B_RULE_SETTableAdapter
	 
	Dim f_oTable As 12Bravo.DataTier.ChargeInfo.12B_RULE_SETDataTable = f_oTableAdapter.GetComment()

	If Not f_oTable.Rows.Count = 0 Then
		Dim f_oRow As 12Bravo.DataTier.ChargeInfo.12B_RULE_SETRow = f_oTable.Rows(0)
		txtComment.Text = f_oRow.DESCR.Trim
	End If
 
	f_oTableAdapter.Dispose()
End Sub