Thursday 26 April 2012

Manage User Role in aspnet membership

Manage User Role in aspnet membership








ManageUserRole.aspx

 <h3>
        Role Membership</h3>
    <asp:Label ID="Msg" ForeColor="maroon" runat="server" /><br />
    <table cellpadding="3" border="0">
        <tr>
            <td valign="top">
                Roles:
            </td>
            <td valign="top">
                <asp:ListBox ID="RolesListBox" runat="server" Rows="5" AutoPostBack="true" Width="150px" />
            </td>
            <td valign="top">
                Users:
            </td>
            <td valign="top">
                <asp:ListBox ID="UsersListBox" DataTextField="Username" Rows="5" SelectionMode="Multiple"
                    runat="server" Width="150px" />
            </td>
            <td valign="top">
                <asp:Button Text="Add User(s) to Role" ID="AddUsersButton" runat="server" OnClick="AddUsers_OnClick" />
            </td>
        </tr>
        <tr>
            <td valign="top">
                Users In Role:
            </td>
            <td valign="top">
                <asp:GridView runat="server" CellPadding="4" ID="UsersInRoleGrid" AutoGenerateColumns="false"
                    GridLines="None" CellSpacing="0" OnRowCommand="UsersInRoleGrid_RemoveFromRole">
                    <HeaderStyle BackColor="navy" ForeColor="white" />
                    <Columns>
                        <asp:TemplateField HeaderText="User Name">
                            <ItemTemplate>
                                <%# Container.DataItem.ToString() %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:ButtonField Text="Remove From Role" ButtonType="Link" />
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>



ManageUserRole.aspx.vb

Imports System.Web.Security
Imports System.Web.UI

Public Class ManageUser
    Inherits System.Web.UI.Page

    Dim rolesArray() As String
    Dim users As MembershipUserCollection
    Dim usersInRole() As String

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Msg.Text = ""

        If Not IsPostBack Then
            ' Bind roles to ListBox.
            rolesArray = Roles.GetAllRoles()
            RolesListBox.DataSource = rolesArray
            RolesListBox.DataBind()

            ' Bind users to ListBox.
            users = Membership.GetAllUsers()
            UsersListBox.DataSource = users
            UsersListBox.DataBind()
        End If

        If Not RolesListBox.SelectedItem Is Nothing Then
            ' Show users in role. Bind user list to GridView.
            usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)
            UsersInRoleGrid.DataSource = usersInRole
            UsersInRoleGrid.DataBind()
        End If
    End Sub

    Public Sub AddUsers_OnClick(ByVal sender As Object, ByVal args As EventArgs) Handles AddUsersButton.Click

        ' Verify that a role is selected.
        If RolesListBox.SelectedItem Is Nothing Then
            Msg.Text = "Please select a role."
            Return
        End If

        ' Verify that at least one user is selected.
        If UsersListBox.SelectedItem Is Nothing Then
            Msg.Text = "Please select one or more users."
            Return
        End If

        ' Create list of users to be added to the selected role.
        Dim newusers(UsersListBox.GetSelectedIndices().Length - 1) As String
        For i As Integer = 0 To newusers.Length - 1
            newusers(i) = UsersListBox.Items(UsersListBox.GetSelectedIndices(i)).Value
        Next

        ' Add the users to the selected role.
        Try
            Roles.AddUsersToRole(newusers, RolesListBox.SelectedItem.Value)

            ' Re-bind users in role to GridView.
            usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)
            UsersInRoleGrid.DataSource = usersInRole
            UsersInRoleGrid.DataBind()
        Catch e As Exception
            Msg.Text = e.Message
        End Try
    End Sub

    Public Sub UsersInRoleGrid_RemoveFromRole(ByVal sender As Object, ByVal args As GridViewCommandEventArgs)

        ' Get the selected user name to remove.
        Dim index As Integer = Convert.ToInt32(args.CommandArgument)
        Dim username As String = (CType(UsersInRoleGrid.Rows(index).Cells(0).Controls(0), DataBoundLiteralControl)).Text

        ' Remove the user from the selected role.
        Try
            Roles.RemoveUserFromRole(username, RolesListBox.SelectedItem.Value)
        Catch e As Exception
            Msg.Text = "An exception of type " & e.GetType().ToString() & _
                       " was encountered removing the user from the role."
        End Try

        ' Re-bind users in role to GridView.
        usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)
        UsersInRoleGrid.DataSource = usersInRole
        UsersInRoleGrid.DataBind()
    End Sub
End Class

Reset password In ASPNET membership VB

Reset password In ASPNET membership VB





ResetPassword.aspx

 <h3> Retrieve Password</h3>
    <p><asp:Label ID="Msg" runat="server" ForeColor="maroon" /><br />
    </p> Username:
    <asp:TextBox ID="UsernameTextBox" Columns="30" runat="server" AutoPostBack="True" />
    <asp:RequiredFieldValidator ID="UsernameRequiredValidator" runat="server" ControlToValidate="UsernameTextBox"
        ForeColor="red" Display="Static" ErrorMessage="Required" /><br />
    <asp:Button ID="ResetPasswordButton" Text="Reset Password" OnClick="ResetPassword_OnClick" runat="server" Enabled="False" />
    <br />
    <asp:Label ID="lblPassword" runat="server" ForeColor="maroon" Style="font-weight: 700;
        color: #FF0000; font-size: x-large" /><br />


ResetPassword.aspx.vb

Imports System.Web.Security

Public Class ResetPassword
    Inherits System.Web.UI.Page

    Dim u As MembershipUser

    Public Sub Page_Load(sender As Object, args As EventArgs) Handles Me.Load

        If Not Membership.EnablePasswordReset Then
            FormsAuthentication.RedirectToLoginPage()
        End If

        Msg.Text = ""

        If Not IsPostBack Then
            Msg.Text = "Please supply a username."
        Else
            VerifyUsername()
        End If
    End Sub

    Public Sub VerifyUsername()
        u = Membership.GetUser(UsernameTextBox.Text, False)

        If u Is Nothing Then
            Msg.Text = "Username " & Server.HtmlEncode(UsernameTextBox.Text) & " not found. Please check the value and re-enter."

            ResetPasswordButton.Enabled = False
        Else
            ResetPasswordButton.Enabled = True
        End If
    End Sub

    Protected Sub ResetPassword_OnClick(sender As Object, args As EventArgs) Handles ResetPasswordButton.Click
        Dim newPassword As String
        u = Membership.GetUser(UsernameTextBox.Text, False)

        If u Is Nothing Then
            Msg.Text = "Username " & Server.HtmlEncode(UsernameTextBox.Text) & " not found. Please check the value and re-enter."
            Return
        End If

        Try
            newPassword = u.ResetPassword()
        Catch e As MembershipPasswordException
            Msg.Text = "Invalid password answer. Please re-enter and try again."
            Return
        Catch e As Exception
            Msg.Text = e.Message
            Return
        End Try

        If Not newPassword Is Nothing Then
            Msg.Text = "Password reset. Your new password is: "
            lblPassword.Text = "" & Server.HtmlEncode(newPassword)
        Else
            Msg.Text = "Password reset failed. Please re-enter your values and try again."
        End If
    End Sub

End Class

Friday 6 April 2012

Using a Custom Action to Create a Database at Installation

Note: 1. This walkthrough requires SQL Server on the computer where you will deploy the application.
2.The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu.
3.The following instructions demonstrate creating a deployment project using a Visual Basic project; the general principles apply to all Visual Studio language projects that support deploying Windows-based applications.

To create an installer class

  1. On the File menu, click New Project.
  2. In the New Project dialog box, select Visual Basic Projects in the Project Type pane, and then choose Class Library in the Templates pane. In the Name box, type DBCustomAction.
  3. On the Project menu, click Add New Item.
  4. In the Add New Item dialog box, choose Installer Class. In the Name box, type VbDeployInstaller.vb.

To create a data connection object

  1. In Server Explorer, select Data Connections. Right-click and choose Add Connection.
  2. In the Choose Data Source dialog box, select Microsoft SQL Server.
  3. In the Add Connection dialog box, do the following:
    1. In the Server name drop-down list, type or select a server name.
    2. Select Use Windows Authentication.
    3. In the database box, type master.
    4. Click OK to close the dialog box.
  4. From the Data menu, click Add New Data Source, then use the wizard to add the connection that you established in the previous steps. To verify that the data source is in the project, click Show Data Sources on the Data menu.

To create a text file that contains a SQL statement to create a database

  1. In Solution Explorer, select the DBCustomAction project. On the Project menu, choose Add New Item.
  2. In the Add New Item dialog box, choose Text File. In the Name box, type sql.txt (must be in lower case).
  3. Add the following to the sql.txt file:
    ------------------------------------------------------------------------------------------------------------
    CREATE TABLE [dbo].[Employees] (
    [Name] [char] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    [Rsvp] [int] NULL ,
    [Requests] [nvarchar] (4000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY];
    
    ALTER TABLE [dbo].[Employees] WITH NOCHECK ADD 
    CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED 
    (
    [Name]
    ) ON [PRIMARY];
    ------------------------------------------------------------------------ 
  4. In Solution Explorer, select sql.txt. In the Properties window, set the BuildAction property to Embedded Resource.

To add code to the installer class to read the text file

  1. In Solution Explorer, select VbDeployInstaller.vb. On the View menu, choose Code.
  2. Add the following Imports statement at the top of the module:

Imports System.IO
Imports System.Reflection
Imports System.Data.SqlClient
Imports System.ComponentModel
Imports System.Configuration.Install
Public Class VbDeployInstaller Dim masterConnection As New System.Data.SqlClient.SqlConnection()
Public Sub New() MyBase.New() 'This call is required by the Component Designer.
InitializeComponent()
'Add initialization code after the call to InitializeComponent
End Sub
Private Function GetSql(ByVal Name As String) As String
Try
' Gets the current assembly.
Dim Asm As [Assembly] = [Assembly].GetExecutingAssembly() ' Resources are named using a fully qualified name.
Dim strm As Stream = Asm.GetManifestResourceStream( _ Asm.GetName().Name + "." + Name) ' Reads the contents of the embedded file.
Dim reader As StreamReader = New StreamReader(strm) Return reader.ReadToEnd()
Catch ex As Exception MsgBox("In GetSQL: " & ex.Message)
Throw ex End Try
End Function
Private Sub ExecuteSql(ByVal DatabaseName As String, ByVal Sql As String) Dim Command As New SqlClient.SqlCommand(Sql, masterConnection) ' Initialize the connection, open it, and set it to the "master" database
masterConnection.ConnectionString = DBCustomAction.My.Settings.masterConnectionString
Command.Connection.Open()
Command.Connection.ChangeDatabase(DatabaseName)
Try
Command.ExecuteNonQuery()
Finally
' Closing the connection should be done in a Finally block
Command.Connection.Close()
End Try
End Sub
Protected Sub AddDBTable(ByVal strDBName As String) Try
' Drop Database if exists.
ExecuteSql("master", "ALTER DATABASE TrainTrack SET SINGLE_USER WITH ROLLBACK IMMEDIATE") ExecuteSql("master", "Drop database TrainTrack")
Catch ex As Exception ' Reports any errors and abort.
End Try
Try
' Creates the database.
ExecuteSql("master", "CREATE DATABASE " + strDBName) ' Creates the tables.
ExecuteSql(strDBName, GetSql("sql.txt")) Catch ex As Exception ' Reports any errors and abort.
MsgBox("In exception handler: " & ex.Message) Throw ex End Try
End Sub
Public Overrides Sub Install(ByVal stateSaver As _ System.Collections.IDictionary)
MyBase.Install(stateSaver) 'AddDBTable(Me.Context.Parameters.Item("dbname"))
AddDBTable("TrainTrack") 
 End Sub 
 End Class


  1. On the Build menu, choose Build DBCustomAction.

To create a deployment project

  1. On the File menu, click Add, and then click New Project.
  2. In the Add New Project dialog box, open the Other Project Types node and select Setup and Deployment Projects in the Project Type pane. Then select Setup Project in the Templates pane. In the Name box, type DBCustomAction_Setup.
  3. In the Properties window, select the ProductName property and type DB Installer.
  4. In the File System Editor, select the Application Folder. On the Action menu, click Add, and then click Project Output.
  5. In the Add Project Output Group dialog box, select Primary output for the DBCustomAction project.

To create a custom installation dialog

  1. Select the DBCustomAction_Setup project in Solution Explorer. On the View menu, point to Editor, and choose User Interface.
  2. In the User Interface Editor, select the Start node under Install. On the Action menu, choose Add Dialog.
  3. In the Add Dialog dialog box, select the Textboxes (A) dialog, then click OK.
  4. On the Action menu, choose Move Up. Repeat until the Textboxes (A) dialog is above the Installation Folder node.
  5. In the Properties window, select the BannerText property and type Specify Database Name.
  6. Select the BodyText property and type This dialog allows you to specify the name of the database to be created on the database server.
  7. Select the Edit1Label property and type Name of database:.
  8. Select the Edit1Property property and type CUSTOMTEXTA1.
  9. Select the Edit2Visible, Edit3Visible, and Edit4Visible properties and set them to False.

To create a custom action

  1. Select the DBCustomAction_Setup project in Solution Explorer. On the View menu, point to Editor, and then click Custom Actions.
  2. In the Custom Actions Editor, select the Install node. On the Action menu, choose Add Custom Action.
  3. In the Select item in project dialog box, double-click the Application Folder.
  4. Select Primary output from DBCustomAction (Active), then click OK to close the dialog box.
  5. Make sure that Primary output from DBCustomAction (Active) item is selected in the Custom Actions Editor. In the Properties window, select the CustomActionData property and type /dbname=[CUSTOMTEXTA1].
  6. On the Build menu, choose Build DBCustomAction_Setup.

To install on your development computer

Select the DBCustomAction_Setup project in Solution Explorer. On the Project menu, choose Install.