Custom Inherited DropDownList class in ASP.Net using SQL Stored Procedure

by wizbay 10. September 2010 13:28

 

Created a custom dropdownlist that is inherited from System.Web.UI.WebControls.DropDownList.

The class accepts an additional property (CCSdesc) to get data from lookup table in sql database. And the class calls a stored procedure to get lookup data (value and text).

Once you set up this class, you can just use <cc:DropDownList runat="server" ID="ddl_country" CCSdesc="country"></cc:DropDownList> without additional codes.


-----------------------Web.Config---------------------------------------
-- Register the class for whole application
    <pages>
      <controls>
        <add assembly="CustomControl" tagPrefix ="cc" namespace ="CustomControl"/>
      </controls>
    </pages>
-- Or you can just register the class in each aspx page
<%@ Register Assembly="CustomControl" Namespace="CustomControl" TagPrefix="cc" %>

-----------------------Default.aspx-------------------------------------
-- This is how you use a new dropdownlist
<cc:DropDownList runat="server" ID="ddl_country" CCSdesc="country"></cc:DropDownList>

-----------------------SQL Server table---------------------------------
CREATE TABLE [dbo].[Lookup](
 [LookupCategory] [varchar](20) NULL,
 [LookupCode] [varchar](50) NULL,
 [LookupShortDesc] [varchar](200) NULL,
 [LookupLongDesc] [varchar](500) NULL,
 [LookupSort] [varchar](10) NULL,
 [LookupSortDirection] [varchar](10) NULL,
 [LookupIcon] [varchar](50) NULL
) ON [PRIMARY]

--Sample Data--
LookupCategory LookupCode LookupShortDesc LookupLongDesc LookupSort LookupSortDirection LookupIcon
country                 VU Vanuatu                   NULL          1                ASC       NULL
country                 VE Venezuela                   NULL          2                ASC       NULL
country                 VN Vietnam                   NULL          3                ASC       NULL

------------------------Stored Procedure--------------------------------------
CREATE PROCEDURE [dbo].[sp_Dropdownlist]
 @LookupCategory varchar(50),
 @sort varchar(20) = null,
 @order varchar(10) = null
AS

BEGIN
 Declare @orderby varchar(50)
 IF (@order = 'desc')
 begin
 Select *
 From [lookup]
 where LookupCategory = @LookupCategory
 order by Case @sort When 'code' then LookupCode 
 When 'sort' then LookupSort 
 Else  LookupShortDesc end desc 
 end
 else
 begin
 Select *
 From [lookup]
 where LookupCategory = @LookupCategory
 order by Case @sort When 'code' then LookupCode 
 When 'sort' then LookupSort 
 Else LookupShortDesc end asc 
 end
END
-----------------------DropDownList.vb ----------------------
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient


Public Class DropDownList
    Inherits System.Web.UI.WebControls.DropDownList

    Dim _CCSdesc As String = String.Empty
    Public Property CCSdesc() As String
        Get
            Return _CCSdesc.ToLower
        End Get
        Set(ByVal Value As String)
            _CCSdesc = Value.ToLower
        End Set
    End Property

    Dim _CCSort As String = String.Empty
    Public Property CCSort() As String
        Get
            Return _CCSort.ToLower
        End Get
        Set(ByVal Value As String)
            _CCSort = Value.ToLower
        End Set
    End Property

    Dim _CCOrder As String = String.Empty
    Public Property CCOrder() As String
        Get
            Return _CCOrder.ToLower
        End Get
        Set(ByVal Value As String)
            _CCOrder = Value.ToLower
        End Set
    End Property

    Dim _CCShowDefault As Boolean = False
    Public Property CCShowDefault() As Boolean
        Get
            Return _CCShowDefault
        End Get
        Set(ByVal Value As Boolean)
            _CCShowDefault = Value
        End Set
    End Property

    Dim _CCShowDefaultText As String = "Please Select..."
    Public Property CCShowDefaultText() As String
        Get
            Return _CCShowDefaultText
        End Get
        Set(ByVal Value As String)
            _CCShowDefaultText = Value
        End Set
    End Property

    Dim _CCSelectedValue As String = String.Empty
    Public Property CCSelectedValue() As String
        Get
            Return _CCSelectedValue
        End Get
        Set(ByVal Value As String)
            _CCSelectedValue = Value
        End Set
    End Property

    Dim maxParams As Int16 = 3
    Dim paramIndex As Int16 = 0

    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
        MyBase.OnPreRender(e)
        GetItems()
    End Sub

    Private Sub GetItems()
        If CCSort = String.Empty Then maxParams -= 1
        If CCOrder = String.Empty Then maxParams -= 1

        Dim param(maxParams - 1) As SqlParameter
        Dim sql As String = String.Empty

        sql = "sp_Dropdownlist"
        param(paramIndex) = New SqlParameter("@LookupCategory", CCSdesc)
        param(paramIndex).SqlDbType = SqlDbType.VarChar

        If CCSort <> String.Empty Then
            paramIndex += 1
            param(paramIndex) = New SqlParameter("@sort", CCSort)
            param(paramIndex).SqlDbType = SqlDbType.VarChar
        End If
        If CCOrder <> String.Empty Then
            paramIndex += 1
            param(paramIndex) = New SqlParameter("@order", CCOrder)
            param(paramIndex).SqlDbType = SqlDbType.VarChar
        End If

        Using db As New Database
            DataSource = db.ExecuteReader(sql, param)
            DataTextField = "LookupShortDesc"
            DataValueField = "LookupCode"
            DataBind()
        End Using

        If CCSelectedValue <> String.Empty AndAlso Not Me.Items.FindByValue(CCSelectedValue) Is Nothing Then
            SelectedValue = CCSelectedValue
        End If
    End Sub

    Private Sub DropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DataBound
        If CCShowDefault Then
            Me.Items.Insert(0, New ListItem(CCShowDefaultText, 0))
        End If
    End Sub
End Class

 

Tags: , , , , , , , ,

ASP.Net | SQL Server | VB.Net

How to use Captcha with ASP.NET

by wizbay 10. September 2010 13:14

I was trying to find a solution to block spammers adding data to our database using VB.Net.

Here's a good captcha image implementation. Easy and simple.

 

Default.aspx

<img src="JpegImage.aspx" alt="CAPTCHA IMAGE" title="Captcha Image" style="border:1px solid #c1c1c1; width:135px; height:26px;" />
<asp:TextBox runat="server" ID="txt_captcha" MaxLength="50" Width="125" CssClass="textbox" style="margin-top:15px;"></asp:TextBox>

<asp:CustomValidator ID="valCaptcha" runat="server" ControlToValidate="txt_captcha" ValidationGroup="signupVal" 
Display="Dynamic" OnServerValidate="valCaptcha_ServerValidate" CssClass="validator" ></asp:CustomValidator>

 

Default.aspx.vb

Protected Sub valCaptcha_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        If txt_captcha.Text.Trim <> Me.Session("CaptchaImageText").ToString() Then
            args.IsValid = False
            valCaptcha.ErrorMessage = "The security code does not match. Try again."
        Else
            args.IsValid = True
        End If
End Sub

JpegImage.aspx // this doesn't really do anything. just for code behind.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="JpegImage.aspx.vb" Inherits="JpegImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Captcha Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
 

JpegImage.aspx.vb //You can resize image and font name here

Partial Class JpegImage
    Inherits System.Web.UI.Page

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Create a CAPTCHA image using the text stored in the Session object.
        If IsNothing(Me.Session("CaptchaImageText")) Then
            Me.Session("CaptchaImageText") = GetRandomNumber(3)
        End If

        Dim ci As CaptchaImage = New CaptchaImage(Me.Session("CaptchaImageText").ToString(), 135, 26, "Tahoma")

        ' Change the response headers to output a JPEG image.
        Me.Response.Clear()
        Me.Response.ContentType = "image/jpeg"

        ' Write the image to the response stream in JPEG format.
        ci.Image.Save(Me.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)

        ' Dispose of the CAPTCHA image object.
        ci.Dispose()
    End Sub
End Class

Function GetRandomNumber(ByVal length As Int16) As String
        Dim randomM As Random = New Random()

        Dim s As String = ""
        For i As Integer = 0 To length
            s = [String].Concat(s, randomM.[Next](10).ToString())
        Next
        Return s
End Function 

AppCode/CapchaImage.vb

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Text

''' <summary>
''' Summary description for CaptchaImage
''' </summary>
Public Class CaptchaImage
    '
    ' TODO: Add constructor logic here
    '
    Public Sub New()
    End Sub

    ' Public properties (all read-only).
    Public ReadOnly Property Text() As String
        Get
            Return Me.m_text
        End Get
    End Property
    Public ReadOnly Property Image() As Bitmap
        Get
            Return Me.m_image
        End Get
    End Property
    Public ReadOnly Property Width() As Integer
        Get
            Return Me.m_width
        End Get
    End Property
    Public ReadOnly Property Height() As Integer
        Get
            Return Me.m_height
        End Get
    End Property

    ' Internal properties.
    Private m_text As String
    Private m_width As Integer
    Private m_height As Integer
    Private familyName As String
    Private m_image As Bitmap

    ' For generating random numbers.
    Private random As New Random()

    ' ====================================================================
    ' Initializes a new instance of the CaptchaImage class using the
    ' specified text, width and height.
    ' ====================================================================
    Public Sub New(ByVal s As String, ByVal width As Integer, ByVal height As Integer)
        Me.m_text = s
        Me.SetDimensions(width, height)
        Me.GenerateImage()
    End Sub

    ' ====================================================================
    ' Initializes a new instance of the CaptchaImage class using the
    ' specified text, width, height and font family.
    ' ====================================================================
    Public Sub New(ByVal s As String, ByVal width As Integer, ByVal height As Integer, ByVal familyName As String)
        Me.m_text = s
        Me.SetDimensions(width, height)
        Me.SetFamilyName(familyName)
        Me.GenerateImage()
    End Sub
    Protected Overrides Sub Finalize()
        Try

            ' ====================================================================
            ' This member overrides Object.Finalize.
            ' ====================================================================
            Dispose(False)
        Finally
            MyBase.Finalize()
        End Try
    End Sub

    ' ====================================================================
    ' Releases all resources used by this object.
    ' ====================================================================
    Public Sub Dispose()
        GC.SuppressFinalize(Me)
        Me.Dispose(True)
    End Sub

    ' ====================================================================
    ' Custom Dispose method to clean up unmanaged resources.
    ' ====================================================================
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            Me.m_image.Dispose()
            ' Dispose of the bitmap.
        End If
    End Sub

    ' ====================================================================
    ' Sets the image width and height.
    ' ====================================================================
    Private Sub SetDimensions(ByVal width As Integer, ByVal height As Integer)
        ' Check the width and height.
        If width <= 0 Then
            Throw New ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.")
        End If
        If height <= 0 Then
            Throw New ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.")
        End If
        Me.m_width = width
        Me.m_height = height
    End Sub

    ' ====================================================================
    ' Sets the font used for the image text.
    ' ====================================================================
    Private Sub SetFamilyName(ByVal familyName As String)
        ' If the named font is not installed, default to a system font.
        Try
            Dim font As New Font(Me.familyName, 12.0F)
            Me.familyName = familyName
            font.Dispose()
        Catch ex As Exception
            Me.familyName = System.Drawing.FontFamily.GenericSerif.Name
        End Try
    End Sub

    ' ====================================================================
    ' Creates the bitmap image.
    ' ====================================================================
    Private Sub GenerateImage()
        ' Create a new 32-bit bitmap image.
        Dim bitmap As New Bitmap(Me.m_width, Me.m_height, PixelFormat.Format32bppArgb)

        ' Create a graphics object for drawing.
        Dim g As Graphics = Graphics.FromImage(bitmap)
        g.SmoothingMode = SmoothingMode.AntiAlias
        Dim rect As New Rectangle(0, 0, Me.m_width, Me.m_height)

        ' Fill in the background.
        Dim hatchBrush As New HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White)
        g.FillRectangle(hatchBrush, rect)

        ' Set up the text font.
        Dim size As SizeF
        Dim fontSize As Single = rect.Height + 1
        Dim font As Font
        ' Adjust the font size until the text fits within the image.
        Do
            fontSize -= 1
            font = New Font(Me.familyName, fontSize, FontStyle.Bold)
            size = g.MeasureString(Me.m_text, font)
        Loop While size.Width > rect.Width

        ' Set up the text format.
        Dim format As New StringFormat()
        format.Alignment = StringAlignment.Center
        format.LineAlignment = StringAlignment.Center

        ' Create a path using the text and warp it randomly.
        Dim path As New GraphicsPath()
        path.AddString(Me.m_text, font.FontFamily, CInt(font.Style), font.Size, rect, format)
        Dim v As Single = 4.0F
        Dim points As PointF() = {New PointF(Me.random.[Next](rect.Width) / v, Me.random.[Next](rect.Height) / v), New PointF(rect.Width - Me.random.[Next](rect.Width) / v, Me.random.[Next](rect.Height) / v), New PointF(Me.random.[Next](rect.Width) / v, rect.Height - Me.random.[Next](rect.Height) / v), New PointF(rect.Width - Me.random.[Next](rect.Width) / v, rect.Height - Me.random.[Next](rect.Height) / v)}
        Dim matrix As New Matrix()
        matrix.Translate(0.0F, 0.0F)
        path.Warp(points, rect, matrix, WarpMode.Perspective, 0.0F)

        ' Draw the text.
        hatchBrush = New HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray)
        g.FillPath(hatchBrush, path)

        ' Add some random noise.
        Dim m As Integer = Math.Max(rect.Width, rect.Height)
        For i As Integer = 0 To CInt((rect.Width * rect.Height / 30.0F)) - 1
            Dim x As Integer = Me.random.[Next](rect.Width)
            Dim y As Integer = Me.random.[Next](rect.Height)
            Dim w As Integer = Me.random.[Next](m / 50)
            Dim h As Integer = Me.random.[Next](m / 50)
            g.FillEllipse(hatchBrush, x, y, w, h)
        Next

        ' Clean up.
        font.Dispose()
        hatchBrush.Dispose()
        g.Dispose()

        ' Set the image.
        Me.m_image = bitmap
    End Sub
End Class

Tags: , , , , , , ,

ASP.Net | VB.Net

Generate a random alpha-numeric code with any length in VB.Net

by wizbay 10. September 2010 02:53

Simple function to Generate a random alpha-numeric code with any length in VB.Net

 

'Generate a random alpha-numeric code with any length.
    Shared Function GetRandomCode(ByVal length As Int16) As String
        Dim num_characters As Integer
        Dim i As Integer
        Dim txt As String = String.Empty
        Dim ch As Integer

        num_characters = length
        Randomize()

        For i = 1 To num_characters
            ch = Int((26 + 26 + 10) * Rnd())
            If ch < 26 Then
                txt = txt & Chr(ch + Asc("A"))
            ElseIf ch < 2 * 26 Then
                ch = ch - 26
                txt = txt & Chr(ch + Asc("a"))
            Else
                ch = ch - 26 - 26
                txt = txt & Chr(ch + Asc("0"))
            End If
        Next i

        Return txt
    End Function

Tags: , , , , , , ,

VB.Net

Function To Remove HTML Tags From String In .Net

by wizbay 10. September 2010 02:49

Following function remove all html tags using regular expressions and just return text string.

 

 'Remove HTML tags from string.
    Shared Function RemoveHTML(ByVal str As String) As String
        Return Regex.Replace(str, "<(.|\n)*?>", String.Empty)
    End Function

Tags: , , , , , , ,

ASP.Net | VB.Net

Function to parse querystring into nameValueCollection in VB.Net

by wizbay 10. September 2010 02:46

Use following function to parse querystring into nameValueCollection and easily retrieve its values using parameter names.

 

 

'Get URL with querystring and parse it into NameValueCollection with keys and names.
    Shared Function ParseQueryString(ByVal url As String)
        Dim queryStringBegin As Integer = url.IndexOf("?")
        Dim queryString As String = url.Substring(queryStringBegin + 1)
        Dim nvc As System.Collections.Specialized.NameValueCollection = New System.Collections.Specialized.NameValueCollection
        Dim sections() As String = queryString.Split("&")
        For Each section As String In sections
            Dim pair() As String = section.Split("=")
            nvc.Add(pair(0).ToString, pair(1).ToString)
        Next
        Return nvc
    End Function

Tags: , , , , ,

ASP.Net | VB.Net

Function to get a random number in VB.Net

by wizbay 10. September 2010 02:45

simple function to get a random number in VB.Net

 

Shared Function GetRandomNumber(ByVal length As Int16) As String
        Dim randomM As Random = New Random()

        Dim s As String = ""
        For i As Integer = 0 To length
            s = [String].Concat(s, randomM.[Next](10).ToString())
        Next
        Return s
    End Function

 

Tags: , , , ,

VB.Net

Find Server Control Inside Of Other Server Control in Recursive / Iterative way

by wizbay 10. September 2010 02:41

Built-in "findcontrol" doesn't really find controls deep inside of other controls. 

Use either one of following method to find server controls.

 

 

'Find any server control inside of a server control.
    Shared Function FindControlIterative(ByVal root As Control, ByVal id As String) As Control
        Dim Ctl As Control = root
        Dim Ctls As LinkedList(Of Control) = New LinkedList(Of Control)

        Do While (Ctl IsNot Nothing)
            If Ctl.ID = id Then
                Return Ctl
            End If
            For Each child As Control In Ctl.Controls
                If child.ID = id Then
                    Return child
                End If
                If child.HasControls Then
                    Ctls.AddLast(child)
                End If
            Next
            Ctl = Ctls.First.Value
            Ctls.Remove(Ctl)
        Loop

        Return Nothing
    End Function

    Shared Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
        If root.ID = id Then
            Return root
        End If

        For Each ctl As Control In root.Controls
            Dim FoundCtl As Control = FindControlRecursive(ctl, id)
            If FoundCtl IsNot Nothing Then
                Return FoundCtl
            End If
        Next

        Return Nothing
    End Function

Tags: , , , , , , ,

VB.Net

Encrypt and Decrypt string in VB.Net

by wizbay 10. September 2010 02:36

 

Use "encrypt" function to encrypt string and "decrypt" function to decrypt string.

Please change "key" something to yours.

 

Sample Usage:

 

dim str as string = encryptString("stringtoencrypt") 

dim str2 as string = descriptString(str)

 

String 'str' will be some string you can never understand.

String 'str2' will display "stringtoencrypt"

 

 

-------------------Source Code---------------------

 

 

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class Security

    Protected key As String = "&/?@*>:>"

    Public Sub New()
        'constructor
    End Sub

    Public Function encryptString(ByVal strtext As String) As String
        Return Encrypt(strtext, key)
    End Function

    Public Function decryptString(ByVal strtext As String) As String
        Return Decrypt(strtext, key)
    End Function

    'The function used to encrypt the text
    Private 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
    Private 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
End Class

 

 

Tags: , , ,

ASP.Net | VB.Net

Consuming asp.net webservice using jquery

by wizbay 10. September 2010 02:29

Created a simple way to consume asp.net webservice using jquery. The webservice gets data from sql database and return result back as json data type.

Hope this help!

 

----------default.aspx------------------

 

<button type="button" onclick="button_onclick">Click</button>
<input type="text" id="txt_username" />
<input type="text" id="txt_email" />

 

----------main.js-----------------------

 

<script type="text/javascript">
  function button_onclick() {
        $.ajax({
            type: "POST",
            url: "../webservice.asmx/checkUserExist",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{username:'" + $("input#txt_username").val() + "',email:'" + $("input#txt_email").val() + "'}",
            timeout: 10000,
            success: function (result) {
                if (result.d != null) {
                   var value = eval("(" + result.d + ")");
                }
		alert(value[0].result);
            },
            error: function (evt) {
                alert(evt.status + "(" + evt.statusText + ")");
            }
        });
  };
</script>

 

--------webservice.asmx------------------

 

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Imports System.Web.Script
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://domain.com")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class OPResume
    Inherits System.Web.Services.WebService
    Dim sql As String = String.Empty
    Dim rs As SqlDataReader

    <WebMethod()> _
    Public Function checkUserExist(ByVal username As String, ByVal email As String) As String
        Dim param(1) As SqlParameter
	Dim result as string = string.empty
  
        sql = "sp_checkUserExist"
        param(0) = New SqlParameter("@username", username)
        param(0).SqlDbType = SqlDbType.VarChar

        param(1) = New SqlParameter("@email", email)
        param(1).SqlDbType = SqlDbType.VarChar

        Using db As New Database
            rs = db.ExecuteReader(sql, param)
	    if rs.hasrow() then
		rs.read()
		result("[{")
            	result("""result"":""")
            	result(rs("result").ToString)
            	result("""}]")
	    end if
        End Using

        return result
    End Function
End Class

 

Tags: , , , , , ,

Jquery | SQL Server | VB.Net

Custom Database Class in VB.Net

by wizbay 9. September 2010 01:59

 

'----------------------------------Usage in Default.aspx.vb--------------------------------

 Private Sub readFromDatabase()        
    Using db As New Database            
       Dim param(0) As SqlParameter            
       Dim rs As SqlDataReader            
       sql = "sp_getCustomerData"            
       param(0) = New SqlParameter("@type", 1)            
       param(0).SqlDbType = SqlDbType.Int            
       rs = db.ExecuteReader(sql, param)            
       rpt_Sections.DataSource = rs            
       rpt_Sections.DataBind()        
    End Using    
End Sub

'----------------------------------------Database.vb--------------------------------------

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

Public Class Database
    Implements IDisposable

    Dim settings As ConnectionStringSettings = Nothing
    Dim dsn As String = String.Empty
    Dim oConn As SqlConnection
    Dim sSql As SqlCommand

    Public Sub New(Optional ByVal name As String = "OPResumeDB")
        settings = ConfigurationManager.ConnectionStrings(name)
        dsn = settings.ConnectionString
        oConn = New SqlConnection(dsn)
        oConn.Open()
    End Sub


    Public Function GetConnectionString() As String
        Return dsn
    End Function

    Public Function ExecuteNonQuery(ByVal sql As String, Optional ByVal param() As SqlParameter = Nothing) As Integer
        sSql = New SqlCommand(sql, oConn)
        If Not param Is Nothing Then
            sSql.CommandType = CommandType.StoredProcedure
            sSql.Parameters.AddRange(param)
        Else
            sSql.CommandType = CommandType.Text
        End If
        Return sSql.ExecuteNonQuery()
    End Function

    Public Function ExecuteScalar(ByVal sql As String, Optional ByVal param() As SqlParameter = Nothing) As Integer
        sSql = New SqlCommand(sql, oConn)
        If Not param Is Nothing Then
            sSql.CommandType = CommandType.StoredProcedure
            sSql.Parameters.AddRange(param)
        Else
            sSql.CommandType = CommandType.Text
        End If

        Return sSql.ExecuteScalar()
    End Function

    Public Function ExecuteReader(ByVal sql As String, Optional ByVal param() As SqlParameter = Nothing) As SqlDataReader
        sSql = New SqlCommand(sql, oConn)

        If Not param Is Nothing Then
            sSql.CommandType = CommandType.StoredProcedure
            sSql.Parameters.AddRange(param)
        Else
            sSql.CommandType = CommandType.Text
        End If
        Return sSql.ExecuteReader()
    End Function


    Private disposedValue As Boolean = False

   ' IDisposable

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                oConn.Close()
            End If
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

This class is for simplifying and accelerating working with SQL, using this class is very simple; there is a sample below for this class, which I hope is useful.

 

Tags: , , , , ,

ASP.Net | SQL Server | VB.Net