Archive for the ‘Visual Basic’ Category

DataBinder.Eval function

I am creating a blog and I need to preserve white space for user comment. So I need to put <pre> tag around the comment content. In ASP.NET, I could do it in the ItemDataBound function and then use the FindControl function and append <pre> tags to the text property of the label. But there is a much better and easier way. Use the DataBinder.Eval function like below

<asp:Label ID=”CommentLabel” runat=”server” Text='<%# DataBinder.Eval(Container.DataItem,”comment_content”,”<pre>{0}</pre>”) %>’></asp:Label>

In my case, the “comment_content” is the name of the field in my table that contains the user htmlencoded content.


Ways to pass data for website

  1. ViewState – Maintain data for postback for a page
  2. Context items collection – Simple data pass from 1 page to another. (common use for server farm)
  3. QueryString – put value in the URL
  4. Session – Server store value per user (example: user id)
  5. Application – For the whole web application
  6. Cache – Server storing data among all users (example: the product table)
  7. Cookie – Store information on the user’s pc for a long time (example: track first time visit)
  8. PreviousPage object

…and others

Context.Items vs. ViewState

To pass values from one page to another, Context.Items and ViewState are used most often.

It is important to keep in mind that values stored in the Context.Items collection only last for the current request. If I were to do a postback on the page, the Context item would be lost. Most of the time this is convienient since we only need to store that value between pages and no longer.

To keep track of values between postback, use ViewState. Unlike Context.Items collection that is used to transfer data from one page to another, ViewState can be only used for the same page. It is useful for postback. Also, Context.Items is used very often in the server farm architecture.

It’s common to use this in the page_load function of the page. Check out the example below. Note that the IsPostBack condition below. If that is not there, then the postback of the page will read Context.Items(“id”) again which will be null. This will cause a problem. That is why it is important to have it there.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ProductToShow As Integer
If Not Me.IsPostBack Then
ProductToShow = Context.Items("Id")
Me.ViewState("Id") = ProductToShow
ProductToShow = Me.ViewState.Item("Id")
End If
End Sub

Use different connection strings depends on current URL

I manage two servers at work. One for development and the other one is production server. I used to have two different web.config file and have different connection string to the database in them. But what I should do is write an if statement to decide what to use depends on what the current URL is.

In <appSettings> tag of the “web.config” file, add the following:

<add key=”Staging” value=”; />
<add key=”DevelopmentConnectionString” value=”server=Dev-DB01; database=DBSample;Integrated Security=SSPI”/>
<add key=”ProductionConnectionString” value=”server=Dev-DB01; database=DBSample;Integrated Security=SSPI”/>

Create a Global Application Class file and name it “Global.asax“. In the file, add the following:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
If (Request.Url.Host = ConfigurationManager.AppSettings(“Staging”)) Then
Context.Items.Add(“ConnectionString”,ConfigurationManager.AppSettings( “DevelopmentConnectionString”))
context.Items.Add(“ConnectionString”,ConfigurationManager.AppSettings( “ProductionConnectionString”))
End If
End Sub

Encrypt DB Connection String

The web.config file of the website contains the user name and password to the SQL Server database. When uploading a website to another server, whoever has access to the server can read the login info for the database server. We can encrypt this connection string info in the web.config file.

Create a page with two buttons. One to encrypt and one to decrypt.

Protected Sub Button_Encrypt_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub

Protected Sub Button_Decrypt_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub

Protected Sub EncryptConfig(ByVal bEncrypt As Boolean)
Dim path = “/SCRP”

Dim config As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(path)
Dim appSettings As ConfigurationSection = config.GetSection(“connectionStrings”)

If bEncrypt Then
End If

End Sub

Other thoughts:
Maybe it’s better to compiled the whole website into .dll files…


Redirect if there is no PreviousPage

An online form has been broken down into several steps. Each step is a single aspx page. Sometimes user goes directly into a step in the middle.

To prevent visitor to go to a page directly, below is the code to check to see if there is no previouspage and redirect it to the default.aspx

In VB:
If IsNothing(PreviousPage) Then
Response.Redirect("Default.aspx" )
End If

In C#:
if (PreviousPage == null)

Set the DefaultFocus or DefaultButton in a Page Based on a Master Page

When user type in the keyword in the search textbox and press the Enter key on keyboard, the webpage just do a simple postback. It doesn’t run the query until the user hit the “Search” button.

Use defaultfocus and defaultbutton.
defaultfocus puts the mouse cursor into the control when the page loads
defaultbutton cause the button click event, without it, it just cause a pagepost back

Because of the Master page, UniqueID and ClientID is necessary for this to work properly.

protected void Page_Load(object sender, EventArgs e)
Page.Form.DefaultButton = this.Button_Continue.UniqueID;
Page.Form.DefaultFocus = this.TextBox_PN.ClientID;

Count user session

In Global.asax add the following code to keep track of user session

void Application_Start(object sender, EventArgs e)
// Code that runs on application startup
Application.Add("userCount", 0);

void Session_Start(object sender, EventArgs e)
// Code that runs when a new session is started
int userCount = int.Parse(Application.Get(“userCount”).ToString());
Application.Set(“userCount”, userCount);

void Session_End(object sender, EventArgs e)
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
int userCount = int.Parse(Application.Get(“userCount”).ToString());
Application.Set(“userCount”, userCount);

The VB code to retrieve user session count is:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sIPAddress
sIPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If sIPAddress = "" Then
sIPAddress = Request.ServerVariables("REMOTE_ADDR")
End If

Label_userCount.Text = “There are ” & Application.Get(“userCount”) & ” user(s) online now”
Label_IP.Text = sIPAddress
End Sub

Javascript alert box and confirmation box in ASP.NET

In HTML, the code will be:

<input type="submit" name="ButtonNote" value="Note" id="ButtonNote"
onclick="alert('Alert message appears in here.');" />

<input type="submit" name="ButtonDelete" value="Delete" id="ButtonDelete"
onclick="return confirm('Are you sure you want to delete?');" />

In ASP.NET, the VB code to accomplish the same thing will be:

Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
   If (Not Page.IsPostBack) Then
      Me.ButtonNote.Attributes.Add("onclick", _
      "alert('Alert message appears in here.');")
      Me.ButtonDelete.Attributes.Add("onclick", _
      "return confirm('Are you sure you want to delete?');")
   End If
End Sub