Navigation

Search

Categories

On this page

Creating and Using a VB Class
How to stream a file
Comparison of VB.NET and C#
How to return the SqlDataReader object to a different method from the original data access method
Formatting a field or string in sentence case
Calling in a function in a class file
How to encrypt/decrypt text
LINQ to SQL Samples In VB.NET
How to generate a random password
Updating or Deleting a List of Records
Calling a Function in VB.NET
Removing Duplicate Values from a List
How to generate a random number
Clearing Form Fields
Removing Duplicate Values from a String

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Wednesday, December 28, 2011
Wednesday, December 28, 2011 7:06:29 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )

 

This is kind of a basic overview of how to create a class file in VB.NET and use it in your Web application.

image

Here is the code for the CallHistory class.  Notice where the file needs to be located in the application.

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient

Public Class CallHistory

    Public Sub AddCallHistory(ByVal ReviewID As Integer, ByVal UserID As Integer, ByVal EventName As String)
        Dim strSQLConn As SqlConnection
        Dim cmd As SqlCommand

        strSQLConn = New SqlConnection(ConfigurationManager.ConnectionStrings("CCMConnectionString").ConnectionString)
        cmd = New SqlCommand("p_AddCallHistory", strSQLConn)
        cmd.CommandType = CommandType.StoredProcedure

        cmd.Parameters.AddWithValue("@ReviewID", ReviewID)
        cmd.Parameters.AddWithValue("@UserID", UserID)
        cmd.Parameters.AddWithValue("@DateChanged", Now())
        cmd.Parameters.AddWithValue("@EventName", EventName)

        Try
            strSQLConn.Open()
            cmd.Connection = strSQLConn
            cmd.ExecuteNonQuery()
        Finally
            strSQLConn.Close()
        End Try
    End Sub

End Class

Now we can use this class anywhere in our web application using the following technique.

First import our CallHistory namespace

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="CallHistory" %>

Next, we create an instance of the class:

'Add the call to the CallHistory table
Dim newCallHistory As New CallHistory
then we call the method
newCallHistory.AddCallHistory(ReviewID, lblUserID.Text, "Call Added")
Comments [0] | | # 
# Thursday, October 20, 2011
Thursday, October 20, 2011 8:27:22 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | VB.NET )

OtherPage.aspx:

<a href="StreamDoc.aspx?FileName=fish.bmp">Test</a>

StreamDoc.aspx:

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

       

        Dim strFileName = Request.QueryString("FileName")

        Dim strFilePrefix As String = strFileName.Substring(strFileName.IndexOf(".") + 1)

               

        Dim s As New FileStream("C:\Inetpub\wwwroot\VandV\docs\" & strFileName & "", FileMode.Open)

        Dim bytes() As Byte

        ReDim bytes(s.Length)

        s.Read(bytes, 0, s.Length)

        'output file to the browser

        Response.Clear()

        Response.ContentType = GetFileExtension(strFilePrefix) & "; " & strFileName

        Response.AddHeader("content-transfer-encoding", "binary")

        Response.ContentEncoding = System.Text.Encoding.GetEncoding(1251)

        Response.BinaryWrite(bytes)

        Response.End()

        s.Close()

        s = Nothing

    End Sub

   

    Function GetFileExtension(ByVal FileExtension As String) As String

        Dim strFileType As String = ""

        Select Case FileExtension

            Case "xls"

                strFileType = "application/vnd.ms-excel"

            Case "xlsx"

                strFileType = "application/vnd.ms-excel"

            Case "doc"

                strFileType = "application/msword"

            Case "docx"

                strFileType = "application/msword"

            Case "pdf"

                strFileType = "application/pdf"

            Case "jpg"

                strFileType = "image/jpeg"

            Case "jpeg"

                strFileType = "image/jpeg"""

            Case "gif"

                strFileType = "image/gif"

            Case "bmp"

                strFileType = "image/bmp"

            Case "png"

                strFileType = "image/png"

            Case "zip"

                strFileType = "application/zip"

            Case "txt"

                strFileType = "application/text"

           

        End Select

        Return strFileType

    End Function

Comments [0] | | # 
# Friday, March 18, 2011
Friday, March 18, 2011 7:30:20 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | C# | VB.NET )
 
Nice comparison of VB.NET and C#

http://networkedblogs.com/e7zId

Comments [0] | | # 
# Wednesday, February 16, 2011
Wednesday, February 16, 2011 2:26:08 PM (GMT Standard Time, UTC+00:00) ( C# | VB.NET )

VB.NET

Public Function CreateMySqlDataReader() As SqlDataReader

                Dim myConnection As New SqlConnection(myConnectionString)

                Dim myCommand As New SqlCommand("Select * from Employee", myConnection)

                myConnection.Open()

                Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

                Return myReader

End Function

Public Sub GetEmployees()

                Dim dr As SqlDataReader = CreateMySqlDataReader()

                                                'Do your operations

                While dr.Read()

                End While

                'Closing Datareader will implicitly close the connection

                dr.Close()

End Sub

C#

public SqlDataReader CreateMySqlDataReader()
{
   SqlConnection myConnection = new SqlConnection(myConnectionString);
   SqlCommand myCommand = new SqlCommand("Select * from Employee", myConnection);
   myConnection.Open();
   SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

   return myReader;    
}

public void GetEmployees()
{
SqlDataReader dr = CreateMySqlDataReader();
while(dr.Read())
   {
      //Do your operations
   }
   //Closing Datareader will implicitly close the connection
   dr.Close();   

}

Comments [0] | | # 
# Tuesday, February 01, 2011
Tuesday, February 01, 2011 10:46:47 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )


A client asked me to format a database field (a person’s last name) so that it is properly formatted with a upper-case first letter and then followed by lower-case letters. This function in VB.NET does the trick. 
Function PCase(ByVal strInput As String) As String
        Dim I As Integer
        Dim CurrentChar, PrevChar As String
        Dim strOutput As String

        PrevChar = ""
        strOutput = ""

        For I = 1 To Len(strInput)
            CurrentChar = Mid(strInput, I, 1)

            Select Case PrevChar
                Case "", " ", ".", "-", ",", """", "'"
                    strOutput = strOutput & UCase(CurrentChar)
                Case Else
                    strOutput = strOutput & LCase(CurrentChar)
            End Select

            PrevChar = CurrentChar
        Next I

        PCase = strOutput
    End Function

<asp:Label ID="lblBorrower_LName" runat="server" Text='<%# PCase(Eval("Borrower_LName")) %>' />
Comments [0] | | # 
# Thursday, December 23, 2010
Thursday, December 23, 2010 5:42:46 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )
 
<%@ Page Language="VB" Inherits="MyBaseClass" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then

'Check for the user's login credentials 
lblLogin.Text = CheckLogin().ToString()


'Check if user is an administrator
lblUserType.Text = CheckUserType(lblLogin.Text).ToString()

End If
End Sub
</script>
I placed these functions in App_Code/MyBaseClass.vb

Public Class MyBaseClass

Inherits System.Web.UI.Page
Public Function CheckLogin() As String
Dim strLogin As String = String.Empty
If Not IsNothing(Request.Cookies("MyCookie")) Then
strLogin = Request.Cookies(
"MyCookie")("Login").ToString()
Else

Response.Redirect("/default.aspx")
End If
Return strLogin
End Function
Public Shared Function CheckUserType(ByVal Login As String) As String
Dim result As String = String.Empty
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
Dim cmd As New SqlCommand("p_CheckUserType", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Login", Login)
Using con
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.Read() Then
result = CType(dr("Administrator"), String)
End If
End Using
Return result
End Function
End Class
Comments [0] | | # 
# Monday, September 20, 2010
Monday, September 20, 2010 3:00:05 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | VB.NET )


I wanted to come up with a way to store sensitive data encrypted in a database and came across these functions.

First you need to add the right namespaces:

<%@ Page Language="VB"  %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Security.Cryptography" %>

The function used to encrypt the text:

'The function used to encrypt the text
    Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
        Dim byKey() As Byte = {}
        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
   
        Try
            byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
            Dim des As New DESCryptoServiceProvider()
            Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Convert.ToBase64String(ms.ToArray())
                
        Catch ex As Exception
            Return ex.Message
        End Try
  
    End Function

The function used to decrypt the text:

'The function used to decrypt the text
    Private Shared Function Decrypt(ByVal strText As String, ByVal sDecrKey As String) As String
        Dim byKey() As Byte = {}
        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
        Dim inputByteArray(strText.Length) As Byte
      
        Try
            byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
            Dim des As New DESCryptoServiceProvider()
            inputByteArray = Convert.FromBase64String(strText)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
 
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
         
            Return encoding.GetString(ms.ToArray())
       
        Catch ex As Exception
            Return ex.Message
        End Try
    
    End Function

Examples of function used to call the Encrypt and Decrypt functions:

'Encrypt the text
 Public Shared Function EncryptText(ByVal strText As String) As String
            Return Encrypt(strText, “&%#@?,:*")
 End Function

'Decrypt the text 
Public Shared Function DecryptText(ByVal strText As String) As String
            Return Decrypt(strText, "&%#@?,:*")
End Function

Finally, how to call the EncryptText and DecryptText functions:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        TextBox2.Text = EncryptText(TextBox1.Text)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        TextBox1.Text = DecryptText(TextBox2.Text)
End Sub
Comments [0] | | # 
# Monday, June 14, 2010
Monday, June 14, 2010 9:27:21 PM (GMT Daylight Time, UTC+01:00) ( LINQ | VB.NET )


I’m trying to learn LINQ and came across this page of useful examples in VB

http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx

Comments [0] | | # 
# Tuesday, June 01, 2010
Tuesday, June 01, 2010 8:52:04 PM (GMT Daylight Time, UTC+01:00) ( VB.NET )


Public Function GeneratePassword(ByVal PwdLength As Integer) As String
    Dim _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
    Dim rndNum As New Random()
    Dim chars(PwdLength - 1) As Char
    Dim strLength As Integer = _allowedChars.Length
    For i As Integer = 0 To PwdLength - 1
        chars(i) = _allowedChars.Chars(CInt(Fix((_allowedChars.Length) * rndNum.NextDouble())))
    Next i
    Return New String(chars)
End Function

 
Comments [0] | | # 
# Wednesday, March 31, 2010
Wednesday, March 31, 2010 3:51:30 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | SQL | VB.NET )


This is a nice example of how to pass a delimitted list of values to SQL Server and perform some kind of dbase function with those whether that be an UPDATE, DELETE or whatever.

First here is the sample stored procedure we are going to call updating each company sent to it by the PK value, id_company

USE [my_dbase]
GO
CREATE PROCEDURE [dbo].[p_UpdateCompany] 
    @id_assign int = NULL
AS
BEGIN

    SET NOCOUNT ON;

    UPDATE Companies 
    SET markedfordeletion = 1 --or whatever could be a delete statement as well    

END

Next, here is the VB.NET code used to call the sproc

Protected Sub btnCompanySubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim strConnection As SqlConnection
        Dim strSql As String
        Dim cmd As SqlCommand
        Dim CompanyValues As String = txtid_company.Text
        
        Dim CompanyList As New ArrayList
        CompanyList.AddRange(Split(CompanyValues, ","))
        
        strConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString_Repository").ConnectionString)
        strSql = "p_UpdateCompany"
        cmd = New SqlCommand(strSql)
        cmd.CommandType = CommandType.StoredProcedure
        
        For i As Integer = 0 To CompanyList.Count - 1
            Dim CompanyVal As Integer = CompanyList(i)
            
            cmd.Parameters.Add("@id_Company", SqlDbType.Int, CompanyVal)
            Try
                strConnection.Open()
                cmd.Connection = strConnection
                cmd.ExecuteNonQuery()
            Finally
                strConnection.Close()
            End Try
        Next
    End Sub

<form id="form1" runat="server">
    <div>
        <table id="Companies">
            <tr>
                <td>Enter id_company values:<br />
                    (separated by commas)</td>
                <td><asp:TextBox ID="txtid_company" runat="server" TextMode="MultiLine" Rows="5" Columns="25" /></td>
            </tr>           
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnCompanySubmit" runat="server" onclick="btnCompanySubmit_Click" Text="Submit" />
                </td>
            </tr>           
        </table>
    </div>
    
    </form>
Comments [0] | | # 
# Wednesday, March 17, 2010
Wednesday, March 17, 2010 6:06:50 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )


lblCompanyName.Text = GetCompanyName(intid_company).ToString()


Public Shared Function GetCompanyName(ByVal id_company As Integer) As String
        Dim result As String = String.Empty
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnString").ConnectionString)

        Dim cmd As New SqlCommand("getCompanyName", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@id_company", id_company)
        Using con
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            If reader.Read() Then
                result = CType(reader("CompanyName"), String)
            End If
        End Using
        Return result
End Function
Comments [0] | | # 
# Wednesday, January 06, 2010
Wednesday, January 06, 2010 6:39:30 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )


This is an example of how to remove duplicate values from a list or string separated by commas. You will also need to import the System.IO namespace to use the StringBuilder method: <%@ Import Namespace="System.IO" %>

'lblIDList contains a list of values separated by commas
'12,58,102,12,99,87,87

Dim values As String
values = lblIDList.Text
                
'Remove duplicates
values = RemoveDuplicates(values)                
                
'Reassign the lblIDList value without the duplicates
lblIDList.Text = values

Public Function RemoveDuplicates(ByVal items As String) As String
            Dim Result As StringBuilder = New StringBuilder()
            Dim newArray As Array
    
            newArray = Split(items, ",")
            For i As Integer = 0 To newArray.Length - 1
                If Result.ToString.IndexOf(newArray(i).ToString()) = -1 Then
                    Result.Append(newArray(i).ToString() & ",")
                End If
            Next
            Return Result.ToString.Substring(0, Result.ToString.LastIndexOf(","))
End Function
Comments [0] | | # 
Wednesday, January 06, 2010 6:32:18 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )


An example of how to generate a random number in VB.NET

intLowerBound = 0
intUpperBound = 1000      
'Get the random number and display it in lblRandomNumber
lblRandomNumber.Text = GetRandomNumberInRange(intLowerBound, intUpperBound)

Function GetRandomNumberInRange(intLowerBound As Integer, intUpperBound As Integer)
                
    Dim RandomGenerator As Random
    Dim intRandomNumber As Integer

    ' Create and init the randon number generator
    RandomGenerator = New Random()

    ' Get the next random number
        intRandomNumber = RandomGenerator.Next(intLowerBound, intUpperBound + 1)
                
    ' Return the random # as the functions return value
    GetRandomNumberInRange = intRandomNumber
                        
End Function
Comments [0] | | # 
# Friday, December 04, 2009
Friday, December 04, 2009 3:26:50 AM (GMT Standard Time, UTC+00:00) ( ASP.NET | VB.NET )

 

Here is a server-side approach to clearing all form fields on a form when a button is clicked.

    Protected Sub btnClearFields_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'First clear all form fields of any existing values
        EmptyTextBoxValues(Me)
    End Sub

    Private Sub EmptyTextBoxValues(ByVal parent As Control)
        For Each c As Control In parent.Controls
            If (c.Controls.Count > 0) Then
                EmptyTextBoxValues(c)
            Else
                If TypeOf c Is TextBox Then
                    CType(c, TextBox).Text = ""
                End If
            
                If TypeOf c Is Dropdownlist Then
                    CType(c, Dropdownlist).SelectedValue = ""
                End If
                
                If TypeOf c Is ListBox Then
                    CType(c, ListBox).SelectedValue = ""
                End If
                
                If TypeOf c Is CheckBox Then
                    CType(c, CheckBox).Checked = False
                End If
            End If
        Next
    End Sub
Comments [0] | | # 
# Wednesday, September 02, 2009
Wednesday, September 02, 2009 2:04:06 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | VB.NET )


I’ve been working on a project recently where I needed to prevent users from adding the same value twice to a string.

Here is a working demo.

<script runat="server" type="text/VB">

    Sub btnRemoveDupes_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim dupeValues As String
        dupeValues = lblWithDupes.Text
                
        'Remove duplicates
        dupeValues = RemoveDuplicates(dupeValues)
                
        'Reassign the label value without the duplicates
        lblNoDupes.Text = dupeValues
    End Sub


    Public Function RemoveDuplicates(ByVal items As String) As String
        Dim Result As StringBuilder = New StringBuilder()
        Dim newArray As Array
    
        newArray = Split(items, ",")
        For i As Integer = 0 To newArray.Length - 1
            If Result.ToString.IndexOf(newArray(i).ToString()) = -1 Then
                Result.Append(newArray(i).ToString() & ",")
            End If
        Next
        Return Result.ToString.Substring(0, Result.ToString.LastIndexOf(","))
    End Function

</script>

<form id="form1" runat="server">
    <div>
    
    Enter a comma delimited string with some duplicate values:<br />
    <asp:TextBox runat="server" ID="lblWithDupes" Width="400px" />
    <br /><br />
    
    The result without the duplicate values is:<br />
    <asp:Label runat="server" ID="lblNoDupes" /> <br /><br />
       
    <asp:Button ID="btnRemoveDupes" runat="server" Text="Button" OnClick="btnRemoveDupes_Click" /> 
    </div>
</form>
Comments [0] | | #