In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Tuesday, July 22, 2008

RadioButtonList control - Array binding

Script that builds the list and binds the values in the list to the RadioButtonList control

Sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New ArrayList
  mycountries.Add("Norway")
  mycountries.Add("Sweden")
  mycountries.Add("France")
  mycountries.Add("Italy")
  mycountries.TrimToSize()
  mycountries.Sort()
  rb.DataSource=mycountries
  rb.DataBind()
end if
end sub


In ASPX page add a radio control and see if properties are as mentioned below
asp:RadioButtonList id="rb" runat="server" 

The Page.IsPostBack Property

The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in the Page_Load subroutine only the FIRST time the page is loaded, you can use the Page.IsPostBack property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true, the page is posted back to the server (i.e. from a button click on a form):

Sub Page_Load
if Not Page.IsPostBack then
  lbl1.Text="The date and time is " & now()
end if
End Sub

Friday, July 18, 2008

Set SQL Password Policy OFF for set of users at once

 

Declare @MinUID as integer

-- Query ‘select * from sysusers’ and choose the minimum UID from where you would like to set password policy off

select @MinUID = 4

Declare @MaxUID as integer

-- Choose the maximum UID up to where you would like to set password policy off

select @MaxUID= 16384

declare @NextLoginName as varchar(30)

declare @strQuery as varchar(50)

 

DECLARE Login_name CURSOR FOR

select name from sysusers where   uid > @MinUID and uid < @MAxUID order by name

 

open login_name

 

fetch next from login_name into @NextLoginName

While @@fetch_status = 0

      Begin

            --print @NextLoginName

            set @strquery = 'alter login ' +  @NextLoginName + ' with check_policy = off'

            exec (@strquery )

      fetch next from login_name into @NextLoginName

      end

 

close login_name

deallocate login_name

Thursday, July 17, 2008

SQL SERVER 2005 - Fixed Server Roles

Fixed server role Server-level permission

1.       bulkadmin

Members of the bulkadmin fixed server role can run the BULK INSERT statement.

2.       dbcreator

Members of the dbcreator fixed server role can create databases, and can alter and restore their own databases.

3.       diskadmin

The diskadmin fixed server role is used for managing disk files.

4.       processadmin

Members of the processadmin fixed server role can terminate processes that are running in an instance of SQL Server.

5.       securityadmin

Members of the securityadmin fixed server role manage logins and their properties. They can GRANT, DENY, and REVOKE server-level permissions. They can also GRANT, DENY, and REVOKE database-level permissions. Additionally, they can reset passwords for SQL Server logins.

6.       serveradmin

Members of the serveradmin fixed server role can change server-wide configuration options and shut down the server.

7.       setupadmin

Members of the setupadmin fixed server role can add and remove linked servers, and also execute some system stored procedures.

8.       sysadmin

Members of the sysadmin fixed server role can perform any activity in the server. By default, all members of the Windows BUILTIN\Administrators group, the local administrator's group, are members of the sysadmin fixed server role.

Monday, July 14, 2008

Create SQL 2000 Database Login and User By a script

/****** Add Login [Newuserid]    ******/

EXEC master.dbo.sp_addlogin @loginame = N'Newuserid', @passwd = 'Newuserid', @defdb = N'master', @deflanguage = N'us_english'

 

USE [DBname]

GO

/****** Grant User [Newuserid]     ******/

 

EXEC dbo.sp_grantdbaccess @loginame = N'Newuserid', @name_in_db = N'Newuserid'

 

USE [DBname]

GO

/******Add DatabaseRole [db_NewuseridRole]    ******/

EXEC dbo.sp_addrole @rolename = N'db_NewuseridRole', @ownername = N'dbo'

Exec sp_addrolemember  @rolename =  'db_NewuseridRole' ,

     @membername = 'Newuserid'

 

/****** Grant Permissions [db_NewuseridRole]    ******/

GRANT EXECUTE ON [dbo].PurgeAPLExtract TO [db_NewuseridRole]

Add new DSN

You can add new DSN by utilizing the script I posted earlier. You need to save following entries from Registry settings [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources] [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo]

DSN update through a script

The code available below might help you tweak the DSN update through a script. Do the following steps

  1. Save the new updated DSN settings
  2. Create a BAT file. Example mentioned below
  3. Run the BAT file to update the registry settings

 

This comes in handy when you are looking to updates many user desktops.

 

Here is the example:

 

cls

echo off

cls

 

- Create directory for backup

if not exist c:\temp\DSN\nul md c:\temp\DSN

 

- Backup host file

if not exist c:\temp\DSN\hosts copy %windir%\system32\drivers\etc\hosts c:\temp\DSN\hosts

 

- Backup registry settings

if not exist c:\temp\DSN\DSN_restore.reg regedit /e c:\temp\DSN\DSN_restore.reg "HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI"

 

- Copy new Host file

Copy C:\NewRegFiles\hosts %windir%\system32\drivers\etc\hosts

 

- Add registry settings

regedit.exe /s C:\NewRegFiles\Newregistrysettings.reg

Process files on disk from ASP.NET code

This function would provide you an idea about how to process files on disk from ASP.NET code. It is a function which is quering some network location to get the number of files processed today.

Thanks

 

   Protected Function GetTotalTransactionsfromBackupLocation() As Integer

        Dim objShell = CreateObject("Shell.Application")

        Dim objFSO = CreateObject("Scripting.FileSystemObject")

        Dim objItem, objFile

        -- Set network location you would like to poll

        Dim objFolder = objShell.NameSpace("\\servername\location")

        Dim colItems = objFolder.Items

        Dim NumberOfFilesProcessed = 0

        For Each objItem In colItems

            objFile = objFSO.GetFile(objItem.Path)

            If Day(objItem.ModifyDate) = Day(Today()) Then

                NumberOfPDFProcessed = NumberOfPDFProcessed + 1

            End If

        Next

        Return NumberOfFilesProcessed

    End Function

How to get connection string from web.config file

Following function can get the connection string from web.config file. Please let me know your comments if it helped and saved your time. Thanks


    Public Shared Function GetConnectionString() As String

        Dim settings As ConnectionStringSettingsCollection = ConfigurationManager.ConnectionStrings

        ' Return No connection string found if there is nothing found

        Dim Constr = "No ConnectionString Found"

        If Not settings Is Nothing Then

            For Each cs As ConnectionStringSettings In settings

                If cs.Name = "XYZConnectionString" Then

                    Constr = cs.ConnectionString

                    Exit For

                End If

            Next

        End If

        Return Constr

    End Function

Thursday, July 3, 2008

How to execute SQL Query from ASP.NET page

Following example would show how to execute SQL Query from ASP.NET. You may create a function using code below and it anywhere in program.

Please let me know your comments on this. Thanks

Here is the example:  

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports System.Configuration

 -- Get connection string from web.config file. Please see my next post to see how to get connection string from web.config.

 Dim connectionString As String = GetConnectionString1()

 

        Dim queryString As String

         -- Set query here

        queryString = "Select * from application_users"

         -- Declare connection       

        Using connection As New SqlConnection(connectionString)

            Dim command As SqlCommand = connection.CreateCommand()

            command.CommandText = queryString

            Try

                connection.Open()

                 -- Declare data reader to read the result set    

                Dim dataReader As SqlDataReader = command.ExecuteReader()

                Do While dataReader.Read()

                    msgbox dataReader(0)

                    --msgbox dataReader(1)

                Loop

                dataReader.Close()

 

            Catch ex As Exception

                Console.WriteLine(ex.Message)

            End Try

        End Using

Subroutine to get date in format 12/26/2008

 Public Sub LabelUIDate()
        Dim TodayDay = Day(Today())
        Dim TodayMonth = Month(Today())
        Dim TodayYear = Year(Today())
        Dim TodayDate = TodayMonth & "/" & TodayDay & "/" & TodayYear
        'LabelDate.Visible = False
        LabelDate.Text = TodayDate

    End Sub

Calling Stored Procedure from ASP.NET page

Following is the function which I wrote to execute the stored procedure on SQL 2005 database. The stored procedure returns the result set which is parsed in the following code. Result set is count of number of records based on some criteria. In the end stored procedure returns the number of records to calling procedure. This function would provide you insight about how to make a stored procedure call and then parse the result set.

Please let me know if it helped. Thanks

 

Protected Function TiffMonitorGetTotalTransactionsfromDB() As Integer

        -- Declare connection variables. Getconnectionstring is a custom function to get connection string from web.config file.

        Dim sqlConnection1 As New SqlConnection(GetConnectionString())

        Dim cmd As New SqlCommand

        Dim NumberOfDatabaseRecords = 0

        Dim reader As SqlDataReader

        -- Set stored procedure name here

        cmd.CommandText = "XyzStoredProcedure"

        -- set parameters in stored procedure.

        cmd.Parameters.Add(New SqlParameter("@labeldate", Data.SqlDbType.DateTime, 10))

        -- here one of the SP parameter @labeldate is set to label value

        cmd.Parameters("@labeldate").Value = LabelDate.Text

        cmd.CommandType = CommandType.StoredProcedure

        cmd.Connection = sqlConnection1

        sqlConnection1.Open()

        -- Execute reader to read the result set

        reader = cmd.ExecuteReader()

        Do While reader.Read()

            NumberOfDatabaseRecords = reader(0)

        Loop

        sqlConnection1.Close()

        Return NumberOfDatabaseRecords

    End Function

Wednesday, July 2, 2008

Get

Imports Microsoft.VisualBasic
Imports DL_DatasetTableAdapters


Public Class BL_Product


Private _productsAdapter As ProductsTableAdapter = Nothing
Protected ReadOnly Property Adapter() As ProductsTableAdapter
Get
If _productsAdapter Is Nothing Then
_productsAdapter = New ProductsTableAdapter
End If

Return _productsAdapter
End Get
End Property
Public Function GetProducts() As DL_Dataset.ProductsDataTable
Return Adapter.GetData()
End Function

Email user in VB script

Below mentioned module would show you how to email user in VB script.

Const strFrom = ""
Const strTo = ""
'Const strTo = ""

Const strSMTPServer = ""
Dim objMail
objMail = CreateObject("CDO.Message")
objMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPServer
objMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMail.Configuration.Fields.Update()
objMail.From = strFrom
objMail.To = strTo

objMail.Subject = "Subject goes here...."
objMail.Textbody = " Text body goes here..."
objMail.Send()

objMail = Nothing

Tuesday, July 1, 2008

How To Display HTML Tag on HTML Page

You can easily display HTML Tags on HTML page by using the table below. Just replace the characters as suggested in table below.

<
>
&
 
"
®
©
<
>
&

"
®
©
less than
greater than
ampersand
non breaking space
double quote
registered trade mark
copyright 


AutoRefresh ASP.NET Page after few interval

AutoRefresh ASP.NET Page after few interval

You can acheive this by simply adding a meta tag in source code as mentioned below. 

<head runat="server">
           <meta http-equiv="refresh" content="500">
</head>

Page would refresh after every 500 Sec. 

Please leave comments if you like it. Thanks