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

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

Syntax Highlighting In BlogEngine.NET

by wizbay 9. September 2010 17:25

Syntax Highlighting In BlogEngine.NET

 
It is not obvious that BlogEngine.NET has a built-in syntax highlighting extension. I mean the current versions 1.3.1, I'm not sure about the old versions though. Anyway you can find it in the extensions settings, it is enabled by default.

So, if you need to paste a code snipped, just paste it in the text area and surround it with the [ code:<language>][/code ] tags

<language> may has one of the following values:

c#
vb
js
html
xml
tsql
msh (Windows PowerShell script language)


It can take some other parameters, like ln for toggling line numbers, however if you set this parameter your layout will get broken for some reasons

Tags: , , ,

General | SQL Server

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

How to configure SQL Server 2005/2008 to allow remote connections

by wizbay 29. August 2010 21:07

This article is from MSDN http://support.microsoft.com/?scid=kb;en-us;914277&x=3&y=11

To enable remote connections on the instance of SQL Server 2005 and to turn on the SQL Server Browser service, use the SQL Server 2005 Surface Area Configuration tool. The Surface Area Configuration tool is installed when you install SQL Server 2005.

Enable remote connections for SQL Server 2005 Express or SQL Server 2005 Developer Edition

You must enable remote connections for each instance of SQL Server 2005 that you want to connect to from a remote computer. To do this, follow these steps:

  1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point toConfiguration Tools, and then click SQL Server Surface Area Configuration.
  2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
  3. On the Surface Area Configuration for Services and Connections page, expandDatabase Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply

    Note Click OK when you receive the following message:
    Changes to Connection Settings will not take effect until you restart the Database Engine service.
  4. On the Surface Area Configuration for Services and Connections page, expandDatabase Engine, click Service, click Stop, wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.

Enable the SQL Server Browser service

If you are running SQL Server 2005 by using an instance name and you are not using a specific TCP/IP port number in your connection string, you must enable the SQL Server Browser service to allow for remote connections. For example, SQL Server 2005 Express is installed with a default instance name of Computer Name\SQLEXPRESS. You are only required to enable the SQL Server Browser service one time, regardless of how many instances of SQL Server 2005 you are running. To enable the SQL Server Browser service, follow these steps.

Important These steps may increase your security risk. These steps may also make your computer or your network more vulnerable to attack by malicious users or by malicious software such as viruses. We recommend the process that this article describes to enable programs to operate as they are designed to, or to implement specific program capabilities. Before you make these changes, we recommend that you evaluate the risks that are associated with implementing this process in your particular environment. If you choose to implement this process, take any appropriate additional steps to help protect your system. We recommend that you use this process only if you really require this process.

  1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point toConfiguration Tools, and then click SQL Server Surface Area Configuration.
  2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
  3. On the Surface Area Configuration for Services and Connections page, click SQL Server Browser, click Automatic for Startup type, and then click Apply

    Note When you click the Automatic option, the SQL Server Browser service starts automatically every time that you start Microsoft Windows.
  4. Click Start, and then click OK.

Note When you run the SQL Server Browser service on a computer, the computer displays the instance names and the connection information for each instance of SQL Server that is running on the computer. This risk can be reduced by not enabling the SQL Server Browser service and by connecting to the instance of SQL Server directly through an assigned TCP port. Connecting directly to an instance of SQL Server through a TCP port is beyond the scope of this article. For more information about the SQL Server Browser server and connecting to an instance of SQL Server, see the following topics in SQL Server Books Online:

  • SQL Server Browser Service
  • Connecting to the SQL Server Database Engine
  • Client Network Configuration

Create exceptions in Windows Firewall

These steps apply to the version of Windows Firewall that is included in Windows XP Service Pack 2 (SP2) and in Windows Server 2003. If you are using a different firewall system, see your firewall documentation for more information. 

If you are running a firewall on the computer that is running SQL Server 2005, external connections to SQL Server 2005 will be blocked unless SQL Server 2005 and the SQL Server Browser service can communicate through the firewall. You must create an exception for each instance of SQL Server 2005 that you want to accept remote connections and an exception for the SQL Server Browser service.

SQL Server 2005 uses an instance ID as part of the path when you install its program files. To create an exception for each instance of SQL Server, you must identify the correct instance ID. To obtain an instance ID, follow these steps:

  1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point toConfiguration Tools, and then click SQL Server Configuration Manager.
  2. In SQL Server Configuration Manager, click the SQL Server Browser service in the right pane, right-click the instance name in the main window, and then click Properties.
  3. On the SQL Server Browser Properties page, click the Advanced tab, locate the instance ID in the property list, and then click OK.

To open Windows Firewall, click Start, click Run, type firewall.cpl, and then click OK

.

Create an exception for SQL Server 2005 in Windows Firewall

To create an exception for SQL Server 2005 in Windows Firewall, follow these steps:

  1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
  2. In the Add a Program window, click Browse.
  3. Click the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe executable program, click Open, and then click OK

    Note The path may be different depending on where SQL Server 2005 is installed.MSSQL.1 is a placeholder for the instance ID that you obtained in step 3 of the previous procedure.
  4. Repeat steps 1 through 3 for each instance of SQL Server 2005 that needs an exception.

Create an exception for the SQL Server Browser service in Windows Firewall

To create an exception for the SQL Server Browser service in Windows Firewall, follow these steps:

  1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
  2. In the Add a Program window, click Browse.
  3. Click the C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe executable program, click Open, and then click OK

    Note The path may be different depending on where SQL Server 2005 is installed.

 

Tags: , , , , , ,

SQL Server