|
intergrating with custom login (VB.NET)
Last post 10-06-2005, 9:07 AM by prawlings. 4 replies.
-
10-04-2005, 10:50 AM |
-
prawlings
-
-
-
Joined on 10-03-2005
-
-
Posts 3
-
-
|
intergrating with custom login (VB.NET)
Has anyone managed to intergrating with custom login (VB.NET) and have any source code available. It would be much apprciated if they could post it in here or at least point me in the right direction as i am really struggling and need to get it operational. I know about looking in the DNN example but i cant follow it, Please help.
Thanks in advance,
Paul
|
|
-
10-04-2005, 5:24 PM |
-
Adam
-
-
-
Joined on 09-23-2003
-
Aurora, ON
-
Posts 18,678
-
-
|
Re: intergrating with custom login (VB.NET)
Paul,
Are you familar with dotnetnuke? A open source portal written with VB.NET.
Here is the provider for DNN.
DotNetNukeDataProvider.vb
Public Class DotNetNukeDataProvider Inherits CuteSoft.Chat.DataProvider
Protected Function GetUser(ByVal uniquename As String) As DotNetNuke.Entities.Users.UserInfo Dim userid As Integer = Integer.Parse(uniquename) Dim ps As DotNetNuke.Entities.Portals.PortalSettings = CType(System.Web.HttpContext.Current.Items("PortalSettings"), DotNetNuke.Entities.Portals.PortalSettings) Return New DotNetNuke.Entities.Users.UserController().GetUser(ps.PortalId, userid) End Function
Public Overrides Function GetUserDisplayName(ByVal useruniquename As String) As String Return GetUser(useruniquename).UserName End Function
Public Overrides Function IsAdministrator(ByVal useruniquename As String) As Boolean Dim user As DotNetNuke.Entities.Users.UserInfo = GetUser(useruniquename) If user.IsSuperUser Then Return True End If
Dim ps As DotNetNuke.Entities.Portals.PortalSettings = CType(System.Web.HttpContext.Current.Items("PortalSettings"), DotNetNuke.Entities.Portals.PortalSettings) Dim roles() As String = New DotNetNuke.Security.Roles.RoleController().GetRolesByUser(user.UserID, ps.PortalId)
Return Array.IndexOf(roles, "Administrators") <> -1
'For Each roleid As String In roles ' Dim role As DotNetNuke.Security.Roles.RoleInfo = New DotNetNuke.Security.Roles.RoleController().GetRole(Integer.Parse(roleid), ps.PortalId) ' If role.RoleName = "Administrators" Then ' Return True ' End If 'Next
'Return False
End Function
Public Overrides Function ListUserUniqueName() As String() Dim ps As DotNetNuke.Entities.Portals.PortalSettings = CType(System.Web.HttpContext.Current.Items("PortalSettings"), DotNetNuke.Entities.Portals.PortalSettings) Dim names As New System.Collections.ArrayList For Each user As DotNetNuke.Entities.Users.UserInfo In New DotNetNuke.Entities.Users.UserController().GetUsers(ps.PortalId, False, False) names.Add(user.UserID.ToString()) Next Return CType(names.ToArray(GetType(String)), String()) End Function
Public Overrides Function SearchUserUniqueNameByDisplayName(ByVal userDisplaName As String) As String() Return SearchUserUniqueNamesByProperty("FirstName", userDisplaName) End Function
Public Overrides Function GetUserPropertyCategories() As CuteSoft.Chat.UserCategory() Dim categories() As CuteSoft.Chat.UserCategory = {New CuteSoft.Chat.UserCategory("UserName", "UserName"), New CuteSoft.Chat.UserCategory("Country", "Country")} Return categories End Function
Public Overrides Function SearchUserUniqueNamesByProperty(ByVal category As String, ByVal keyword As String) As String() Dim ps As DotNetNuke.Entities.Portals.PortalSettings = CType(System.Web.HttpContext.Current.Items("PortalSettings"), DotNetNuke.Entities.Portals.PortalSettings) keyword = keyword.ToLower() Dim names As New System.Collections.ArrayList For Each user As DotNetNuke.Entities.Users.UserInfo In New DotNetNuke.Entities.Users.UserController().GetUsers(ps.PortalId, False, False) Dim prop As String Select Case category Case "FirstName" prop = user.FirstName Exit Select Case "UserName" prop = user.Username Exit Select Case "Country" prop = user.Profile.Country Exit Select End Select If prop <> Nothing Then If prop.ToLower().IndexOf(keyword) <> -1 Then names.Add(user.UserID.ToString()) End If End If Next Return CType(names.ToArray(GetType(String)), String()) End Function
End Class
DotNetNukeUserAdapter.vb
Public Class DotNetNukeUserAdapter Inherits CuteSoft.Chat.UserAdapter
Public Overrides Function GetUserUniqueName(ByVal context As System.Web.HttpContext) As String If Not context.Request.IsAuthenticated Then Return Nothing End If
'DotNetNuke3 use username.. Dim ps As DotNetNuke.Entities.Portals.PortalSettings = CType(System.Web.HttpContext.Current.Items("PortalSettings"), DotNetNuke.Entities.Portals.PortalSettings)
Return New DotNetNuke.Entities.Users.UserController().GetUserByUsername(ps.PortalId, context.User.Identity.Name).UserID.ToString()
End Function
End Class
Hope it helps.
Let me know if you have any further questions.
asp.net Chat http://cutesoft.net/ASP.NET+Chat/default.aspx Web Messenger: http://cutesoft.net/Web-Messenger/default.aspx asp.net wysiwyg editor: http://cutesoft.net/ASP.NET+WYSIWYG+Editor/default.aspx asp wysiwyg html editor: http://cutesoft.net/ASP asp.net Image Gallery: http://cutesoft.net/ASP.NET+Image+Gallery/default.aspx Live Support: http://cutesoft.net/live-support/default.aspx
|
|
-
10-04-2005, 7:50 PM |
-
prawlings
-
-
-
Joined on 10-03-2005
-
-
Posts 3
-
-
|
Re: intergrating with custom login (VB.NET)
Hi adam,
I have a simple user table in my sql database with username and password, i havent used DNN before. I want to intergrate with this table as when a user logs into this they are effectively logged into my site.
Thanks in advance,
Paul
|
|
-
10-06-2005, 8:18 AM |
-
grisbi
-
-
-
Joined on 09-05-2005
-
-
Posts 10
-
-
|
Re: integrating with custom login (VB.NET)
Hi Paul, I am not an administrator or anything but I had a similar problems integrating my login, because I write in VB.net and I am not familiar with the .Net Nuke portal so here is the code that I put together after using a C# Convertor:
Imports System Imports System.Net Imports System.IO Imports System.Web.UI.WebControls Imports System.Data Imports System.Data.SqlClient Imports System.Collections Imports System.ComponentModel Imports System.Web Imports System.Security.Principal Imports microsoft.visualbasic Imports System.Web.Caching Imports System.Configuration Imports System.Web.Mail Imports System.Diagnostics.Debug Imports System.XML Imports System.Drawing Imports System.Security.Cryptography Imports System.Text
Namespace SamplePortal.Components _ '/ <summary> '/ Summary description for GridResusecode. '/ </summary> Public Class GridUtils Public Shared Function OnGridSort(oGrid As DataGrid) As String ' Get Order by clause Dim sOrderBy As String = "" Dim oCol As DataGridColumn For Each oCol In oGrid.Columns If oCol.SortExpression.IndexOf(" ASC") > 1 Or oCol.SortExpression.IndexOf(" DESC") > 1 Then If sOrderBy.Length > 0 Then sOrderBy += ", " End If sOrderBy += oCol.SortExpression End If Next oCol Return sOrderBy End Function 'OnGridSort Public Shared Function OnColSortSelection(oGrid As DataGrid, e As DataGridSortCommandEventArgs) As String Dim oCol As DataGridColumn For Each oCol In oGrid.Columns ' Find the right column If e.SortExpression.ToLower().CompareTo(oCol.SortExpression.ToLower()) = 0 Then oCol.HeaderText = oCol.HeaderText.Replace(" (ASC)", "").Replace(" (DESC)", "") If e.SortExpression.IndexOf(" ASC") > 1 Then oCol.SortExpression = e.SortExpression.Replace(" ASC", " DESC") oCol.HeaderText = oCol.HeaderText + " (DESC)" Return oCol.SortExpression Else If e.SortExpression.IndexOf(" DESC") > 1 Then oCol.SortExpression = e.SortExpression.Replace(" DESC", "") Return e.SortExpression Else oCol.SortExpression = e.SortExpression + " ASC" oCol.HeaderText = oCol.HeaderText + " (ASC)" Return oCol.SortExpression End If End If End If Next oCol Return "" End Function 'OnColSortSelection Public Shared Sub ResetColumnHeadersSort(oGrid As DataGrid) Dim oCol As DataGridColumn For Each oCol In oGrid.Columns oCol.HeaderText = oCol.HeaderText.Replace(" (ASC)", "").Replace(" (DESC)", "") Next oCol End Sub 'ResetColumnHeadersSort End Class 'GridUtils Public Class JSHelper Private Sub New() End Sub 'New '/ <summary> '/ Show a JS message box. '/ </summary> '/ <param name="msg"></param> Public Shared Sub MsgBox(msg As [String]) System.Web.HttpContext.Current.Response.Write(("<script language='javascript'>alert('" + msg + "');</script>")) End Sub 'MsgBox End Class 'JSHelper Public Enum RegNewUserResult Success UsernameAlreadyExists DatabaseFail End Enum 'RegNewUserResult Public Class RoleData Public Sub New() End Sub 'New Private ReadOnly Property ConnectionString() As [String] Get Return System.Configuration.ConfigurationSettings.AppSettings("Conn1") End Get End Property Private Function CreateConnection() As SqlConnection Return New SqlConnection(Me.ConnectionString) End Function 'CreateConnection Public Sub AddUserToRole(roleName As [String], username As [String]) If Me.IsUserInRole(roleName, username) Then Return End If Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("Insert into UserRole (Username, RoleName) values (@Username, @RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'AddUserToRole Public Function IsUserInRole(roleName As [String], username As [String]) As [Boolean] Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("select Username from UserRole where (Username=@Username) and (RoleName=@RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() Return cmd.ExecuteNonQuery() > 0 Finally conn.Close() End Try End Function 'IsUserInRole Public Function GetRolesOfUser(username As [String]) As [String]() Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("select RoleName from UserRole where Username=@Username", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Dim roles As New ArrayList() While reader.Read() roles.Add(reader.GetString(0)) End While Return CType(roles.ToArray(GetType([String])), [String]()) Finally conn.Close() End Try End Function 'GetRolesOfUser End Class 'RoleData Public Class UserData Public Sub New() End Sub 'New Private ReadOnly Property ConnectionString() As [String] Get Return System.Configuration.ConfigurationSettings.AppSettings("Conn1") End Get End Property '/ <summary> '/ if LastOnlineTime before this time, then offline '/ </summary> Private ReadOnly Property OnlineTimeoutTime() As DateTime Get Dim iTimeoutSecond As Int32 = Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings("OnlineTimeout")) Return DateTime.Now.AddSeconds((0 - iTimeoutSecond)) End Get End Property Private Function CreateConnection() As SqlConnection Return New SqlConnection(Me.ConnectionString) End Function 'CreateConnection Public Function Login(username As [String], password As [String]) As [Boolean] Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("select Password from Users where Username=@Username", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() Dim sPassword As [String] = CType(cmd.ExecuteScalar(), [String]) Return sPassword = password Catch Finally conn.Close() End Try End Function 'Login Public Sub UpdateLastLoginTime(username As [String]) Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("update Users set LastLoginTime=@LastLoginTime where Username=@Username", conn) Dim paraLastLoginTime As SqlParameter = cmd.Parameters.Add("@LastLoginTime", SqlDbType.DateTime) paraLastLoginTime.Value = DateTime.Now Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'UpdateLastLoginTime Public Function RegNewUser(username As [String], password As [String], location As [String], occupation As [String], interests As [String], age As Integer, gender As [Boolean]) As RegNewUserResult If Me.IsUsernameExists(username) Then Return RegNewUserResult.UsernameAlreadyExists End If Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("insert into Users (Name, Username, Password, Location, Occupation, Interests, Age, Gender) values (@Name, @Username, @Password, @Location, @Occupation, @Interests, @Age, @Gender)", conn) Dim paraName As SqlParameter = cmd.Parameters.Add("@Name", SqlDbType.NVarChar) paraName.Value = username Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim md5Hasher as New MD5CryptoServiceProvider() Dim encoder as New UTF8Encoding() Dim hashedBytes as Byte() = md5Hasher.ComputeHash(encoder.GetBytes(Password)) Dim paraPassword As SqlParameter = cmd.Parameters.Add("@Password", SqlDbType.NVarChar) paraPassword.Value = Convert.ToBase64String(HashedBytes) Dim paraLocation As SqlParameter = cmd.Parameters.Add("@Location", SqlDbType.NVarChar) paraLocation.Value = location Dim paraOccupation As SqlParameter = cmd.Parameters.Add("@Occupation", SqlDbType.NVarChar) paraOccupation.Value = occupation Dim paraInterests As SqlParameter = cmd.Parameters.Add("@Interests", SqlDbType.NVarChar) paraInterests.Value = interests Dim paraAge As SqlParameter = cmd.Parameters.Add("@Age", SqlDbType.Int, 4) paraAge.Value = age Dim paraSex As SqlParameter = cmd.Parameters.Add("@Gender", SqlDbType.Bit) paraSex.Value = gender Try conn.Open() cmd.ExecuteNonQuery() Catch x As Exception Return RegNewUserResult.DatabaseFail Finally conn.Close() End Try ' Add new user to "Members" role Dim roleData As New RoleData() roleData.AddUserToRole(username, "Users") Return RegNewUserResult.Success End Function 'RegNewUser Public Function IsUsernameExists(username As [String]) As [Boolean] Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand("select Username from Users where Username=@Username", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() Return cmd.ExecuteNonQuery() > 0 Finally conn.Close() End Try End Function 'IsUsernameExists Public Function GetOnlineUsers() As DataSet Dim conn As SqlConnection = Me.CreateConnection() Dim cmd As New SqlCommand() cmd.Connection = conn cmd.CommandText = "select * from Users where LastLoginTime>=@LastLoginTime" Dim paraLastLoginTime As SqlParameter = cmd.Parameters.Add("@LastLoginTime", SqlDbType.DateTime) paraLastLoginTime.Value = Me.OnlineTimeoutTime Dim ada As New SqlDataAdapter(cmd) Dim result As New DataSet() Try conn.Open() ada.Fill(result) Finally conn.Close() End Try Return result End Function 'GetOnlineUsers Public Shared Function GetAllUsers() As DataSet Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select * from Users order by Location", conn) Dim ada As New SqlDataAdapter(cmd) Dim result As New DataSet() Try conn.Open() ada.Fill(result) Finally conn.Close() End Try result.Tables(0).Columns.Add("SexString", GetType([String])) result.Tables(0).Columns.Add("Roles", GetType([String])) Dim row As DataRow For Each row In result.Tables(0).Rows If CType(row("Gender"), [Boolean]) Then row("SexString") = "Male" Else row("SexString") = "Female" End if 'row("SexString") = (If CType(row("Gender"), [Boolean]) Then "Male" Else "Female") 'ToDo: Unsupported feature: conditional (?) operator. row("Roles") = [String].Join(",", Global.GetRolesOfUser(row("Username").ToString())) Next row Return result End Function 'GetAllUsers Public Shared Function GetUserInfo(username As [String]) As DataSet Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand() cmd.Connection = conn cmd.CommandText = "select * from Users where Username=@Username" Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim ada As New SqlDataAdapter(cmd) Dim result As New DataSet() Try conn.Open() ada.Fill(result) Finally conn.Close() End Try Return result End Function 'GetUserInfo End Class 'UserData End Namespace 'SamplePortal.Components
Namespace SamplePortal.CuteChatIntegration _ '/ <summary> '/ Data Provider for CuteChat '/ </summary> Public Class DataProvider Inherits CuteSoft.Chat.DataProvider Public Sub New() End Sub 'New Public Overrides Function GetUserDisplayName(useruniquename As String) As String Return useruniquename End Function 'GetUserDisplayName Public Overrides Function IsAdministrator(useruniquename As String) As Boolean Dim roles As [String]() = Global.GetRolesOfUser(useruniquename) Return Array.IndexOf(roles, "Administrator") > - 1 End Function 'IsAdministrator Public Overrides Function ListUserUniqueName() As String() Dim ds As DataSet = SamplePortal.Components.UserData.GetAllUsers() Dim result(ds.Tables(0).Rows.Count) As [String] Dim i As Int32 While i < ds.Tables(0).Rows.Count result(i) = ds.Tables(0).Rows(i)("Username").ToString() End While Return result End Function 'ListUserUniqueName Public Overrides Function SearchUserUniqueNameByDisplayName(userDisplaName As String) As String() Return SearchUserUniqueNamesByProperty("Username", userDisplaName) End Function 'SearchUserUniqueNameByDisplayName Public Overrides Function GetUserPropertyCategories() As CuteSoft.Chat.UserCategory() Return New CuteSoft.Chat.UserCategory() {New CuteSoft.Chat.UserCategory("Gender", "Gender", New String() {"Male", "Female", "NotSet"}), New CuteSoft.Chat.UserCategory("Interests", "Interests"), New CuteSoft.Chat.UserCategory("Location", "Location"), New CuteSoft.Chat.UserCategory("Occupation", "Occupation")} End Function 'GetUserPropertyCategories Overloads Public Overrides Function GetUserProperty(category As String, useruniquename As String) As Object Dim ds As DataSet = SamplePortal.Components.UserData.GetUserInfo(useruniquename) Return GetUserProperty(category, ds.Tables(0).Rows(0)) End Function 'GetUserProperty Overloads Private Function GetUserProperty(category As String, user As DataRow) As Object If user Is Nothing Then Return Nothing End If Select Case category Case "Username" Return user("Username").ToString() Case "Gender" If user.IsNull("Gender") Then Return "NotSet" End If If Convert.ToBoolean(user("Gender")) Then Return "Male" Else Return "Female" End if Case "Interests" Return user("Interests").ToString() Case "Location" Return user("Location").ToString() Case "Occupation" Return user("Occupation").ToString() End Select Return Nothing End Function 'GetUserProperty Public Overrides Function SearchUserUniqueNamesByProperty(category As String, keyword As String) As String() If keyword Is Nothing Or keyword = "" Then Return New String(0) {} End If keyword = keyword.ToLower() Dim names As New ArrayList() Dim table As New DataTable() Dim sda As New SqlDataAdapter("select * from Users", Global.ConnectionString) Try sda.Fill(table) Finally sda.Dispose() End Try Dim row As DataRow For Each row In table.Rows Dim val As String = Convert.ToString(GetUserProperty(category, row)) If val Is Nothing Or val = "" Then GoTo ContinueForEach1 End If If val.ToLower().IndexOf(keyword) <> - 1 Then names.Add(row("Username").ToString()) End If ContinueForEach1: Next row Return CType(names.ToArray(GetType(String)), String()) End Function 'SearchUserUniqueNamesByProperty End Class 'DataProvider End Namespace 'SamplePortal.CuteChatIntegration
Namespace SamplePortal _ '/ <summary> '/ Summary description for ConnectionStringProvider. '/ </summary> Public Class ConnectionStringProvider Inherits CuteSoft.Chat.ConnectionStringProvider Protected Overrides Function GetConnectionString(user As CuteSoft.Chat.UserIdentity) As String Return System.Configuration.ConfigurationSettings.AppSettings("Conn1") End Function 'GetConnectionString End Class 'ConnectionStringProvider Public Class JSHelper Private Sub New() End Sub 'New '/ <summary> '/ Show a JS message box. '/ </summary> '/ <param name="msg"></param> Public Shared Sub MsgBox(msg As [String]) System.Web.HttpContext.Current.Response.Write(("<script language='javascript'>alert('" + msg + "');</script>")) End Sub 'MsgBox End Class 'JSHelper '/ <summary> '/ Global Application Handler '/ </summary> Public Class Global Inherits System.Web.HttpApplication Private components As System.ComponentModel.IContainer = Nothing Public Sub New() InitializeComponent() End Sub 'New Public Shared ReadOnly Property ConnectionString() As [String] Get Return System.Configuration.ConfigurationSettings.AppSettings("Conn1") End Get End Property '/ <summary> '/ if LastOnlineTime before this time, then offline '/ </summary> Public Shared ReadOnly Property OnlineTimeoutTime() As DateTime Get Dim iTimeoutSecond As Int32 = Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings("OnlineTimeout")) Return DateTime.Now.AddSeconds((0 - iTimeoutSecond)) End Get End Property Protected Sub Application_Start(sender As [Object], e As EventArgs) End Sub 'Application_Start Protected Sub Application_EndRequest(sender As [Object], e As EventArgs) End Sub 'Application_EndRequest Protected Sub Application_AuthenticateRequest(sender As [Object], e As EventArgs) If Me.Request.IsAuthenticated Then Dim currUser As New GenericPrincipal(Me.User.Identity, GetRolesOfUser(Me.User.Identity.Name)) Me.Context.User = currUser Global.UpdateLastLoginTime(currUser.Identity.Name, DateTime.Now) End If End Sub 'Application_AuthenticateRequest Protected Sub Application_Error(sender As [Object], e As EventArgs) End Sub 'Application_Error Protected Sub Session_End(sender As [Object], e As EventArgs) If Me.Request.IsAuthenticated Then Global.UpdateLastLoginTime(Me.User.Identity.Name, DateTime.Now.AddMonths(- 1)) End If End Sub 'Session_End Protected Sub Application_End(sender As [Object], e As EventArgs) End Sub 'Application_End Public Shared Sub UpdateLastLoginTime(username As [String], lastLoginTime As DateTime) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("update Users set LastLoginTime=@LastLoginTime where Username=@Username", conn) Dim paraLastLoginTime As SqlParameter = cmd.Parameters.Add("@LastLoginTime", SqlDbType.DateTime) paraLastLoginTime.Value = lastLoginTime Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'UpdateLastLoginTime Public Shared Function GetRolesOfUser(username As [String]) As [String]() Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select RoleName from UserRole where Username=@Username", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Dim roles As New ArrayList() While reader.Read() roles.Add(reader.GetString(0)) End While Return CType(roles.ToArray(GetType([String])), [String]()) Finally conn.Close() End Try End Function 'GetRolesOfUser Public Shared Function GetAllRoles() As [String]() Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select RoleName from Roles order by RoleName", conn) Try conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Dim result As New ArrayList() While reader.Read() result.Add(reader.GetString(0)) End While Return CType(result.ToArray(GetType([String])), [String]()) Finally conn.Close() End Try End Function 'GetAllRoles Public Shared Sub AddUserToRole(roleName As [String], username As [String]) If Global.IsUserInRole(roleName, username) Then Return End If Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("Insert into UserRole (Username, RoleName) values (@Username, @RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() cmd.ExecuteNonQuery() Catch Finally conn.Close() End Try End Sub 'AddUserToRole Public Shared Sub RemoveUserFromRole(roleName As [String], username As [String]) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("delete from UserRole where (Username=@Username) and (RoleName=@RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'RemoveUserFromRole Public Shared Sub RemoveUserFromAllRoles(username As [String]) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("delete from UserRole where (Username=@Username)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'RemoveUserFromAllRoles Public Shared Function IsUserInRole(roleName As [String], username As [String]) As [Boolean] Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select Username from UserRole where (Username=@Username) and (RoleName=@RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() Return cmd.ExecuteNonQuery() > 0 Finally conn.Close() End Try End Function 'IsUserInRole ' 'ToDo: Error processing original source shown below ' ' '-----^--- Pre-processor directives not translated '/ <summary> ' 'ToDo: Error processing original source shown below ' ' '--^--- Unexpected pre-processor directive '/ Required method for Designer support '/ do not modify this method '/ </summary> Private Sub InitializeComponent() End Sub 'InitializeComponent End Class 'Global Public Class ModifyUserProfile Inherits System.Web.UI.UserControl Public Event AfterUpdate As EventHandler Public Event AfterCancel As EventHandler Protected WithEvents btnCancel As System.Web.UI.WebControls.Button Protected WithEvents btnReg As System.Web.UI.WebControls.Button Protected RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator Protected txtPassword As System.Web.UI.WebControls.TextBox Protected RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator Protected txtPassword2 As System.Web.UI.WebControls.TextBox Protected rbtBoy As System.Web.UI.WebControls.RadioButton Protected rbtGirl As System.Web.UI.WebControls.RadioButton Protected txtAge As System.Web.UI.WebControls.TextBox Protected Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator Protected rangeValInteger As System.Web.UI.WebControls.RangeValidator Protected txtLocation As System.Web.UI.WebControls.TextBox Protected txtOccupation As System.Web.UI.WebControls.TextBox Protected CompareValidator1 As System.Web.UI.WebControls.CompareValidator Protected txtInterests As System.Web.UI.WebControls.TextBox Public Property Username() As [String] Get Return Me.ViewState("Users") End Get Set Me.ViewState("Users") = value End Set End Property Public Property ParentPageRelativePath() As [String] Get If Me.ViewState("ParentPageRelativePath") Is Nothing Then Return "" End If Return CType(Me.ViewState("ParentPageRelativePath"), [String]) End Get Set Me.ViewState("ParentPageRelativePath") = value End Set End Property Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load If Me.Username Is Nothing Then Me.Visible = False Return End If If Not Me.IsPostBack Then Me.FillUserProfile() End If End Sub 'Page_Load Private Sub FillUserProfile() Dim ds As DataSet = SamplePortal.Components.UserData.GetUserInfo(Me.Username) Dim row As DataRow = ds.Tables(0).Rows(0) Me.txtLocation.Text = row("Location").ToString() Me.txtOccupation.Text = row("Occupation").ToString() Me.txtInterests.Text = row("Interests").ToString() Me.txtAge.Text = row("Age").ToString() If CType(row("Gender"), [Boolean]) Then rbtBoy.Checked = True Else rbtGirl.Checked = True End If End Sub 'FillUserProfile Public Sub DoModifyUserProfile(username As [String], password As [String], location As [String], occupation As [String], interests As [String], gender As Boolean, age As Integer) Dim bChangePassword As [Boolean] = Not (password Is Nothing) And password.Length > 0 Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("", conn) If bChangePassword Then cmd.CommandText = "update Users set Password1=@Password, Location=@Location, Occupation=@Occupation, Interests=@Interests, Age=@Age where Users=@Username" Else cmd.CommandText = "update Users set Location=@Location, Occupation=@Occupation, Interests=@Interests, Age=@Age where Users=@Username" End If If bChangePassword Then Dim paraPassword As SqlParameter = cmd.Parameters.Add("@Password", SqlDbType.NVarChar) paraPassword.Value = password End If Dim paraLocation As SqlParameter = cmd.Parameters.Add("@Location", SqlDbType.NVarChar) paraLocation.Value = location Dim paraOccupation As SqlParameter = cmd.Parameters.Add("@Occupation", SqlDbType.NVarChar) paraOccupation.Value = occupation Dim paraInterests As SqlParameter = cmd.Parameters.Add("@Interests", SqlDbType.NVarChar) paraInterests.Value = interests Dim paraAge As SqlParameter = cmd.Parameters.Add("@Age", SqlDbType.Int, 4) paraAge.Value = age Dim paraGender As SqlParameter = cmd.Parameters.Add("@Gender", SqlDbType.Bit) paraGender.Value = gender Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Catch Finally conn.Close() End Try End Sub 'DoModifyUserProfile
Protected Overrides Sub OnInit(e As EventArgs) InitializeComponent() MyBase.OnInit(e) End Sub Private Sub InitializeComponent() AddHandler btnReg.Click, AddressOf Me.btnReg_Click AddHandler btnCancel.Click, AddressOf Me.btnCancel_Click AddHandler Load, AddressOf Page_Load End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Not (AfterCancelEvent Is Nothing) Then AfterCancelEvent(Me, EventArgs.Empty) End If End Sub Private Sub btnReg_Click(sender As Object, e As System.EventArgs) Handles btnReg.Click If Not Me.Page.IsValid Then Return End If Dim sPassword As [String] = Me.txtPassword.Text Dim sLocation As [String] = Me.txtLocation.Text Dim sOccupation As [String] = Me.txtOccupation.Text Dim sInterests As [String] = Me.txtInterests.Text Dim dAge As Integer = Int32.Parse(Me.txtAge.Text) Dim male As Boolean = True If rbtGirl.Checked Then male = False End If Me.DoModifyUserProfile(Me.Username, sPassword, sLocation, sOccupation, sInterests, male, dAge) 'If Not (Me.AfterUpdate Is Nothing) Then 'Me.AfterUpdate(Me, EventArgs.Empty) 'End If End Sub 'btnReg_Click End Class 'ModifyUserProfile End Namespace 'SamplePortal
And here is the Global.asax class:
Public Class Global Inherits System.Web.HttpApplication Private components As System.ComponentModel.IContainer = Nothing Public Sub New() InitializeComponent() End Sub 'New Public Shared ReadOnly Property ConnectionString() As [String] Get Return System.Configuration.ConfigurationSettings.AppSettings("Conn1") End Get End Property Public Shared ReadOnly Property OnlineTimeoutTime() As DateTime Get Dim iTimeoutSecond As Int32 = Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings("OnlineTimeout")) Return DateTime.Now.AddSeconds((0 - iTimeoutSecond)) End Get End Property Protected Sub Application_AuthenticateRequest(sender As [Object], e As EventArgs) If Me.Request.IsAuthenticated Then Dim currUser As New GenericPrincipal(Me.User.Identity, GetRolesOfUser(Me.User.Identity.Name)) Me.Context.User = currUser Global.UpdateLastLoginTime(currUser.Identity.Name, DateTime.Now) End If End Sub 'Application_AuthenticateRequest Protected Sub Session_End(sender As [Object], e As EventArgs) If Me.Request.IsAuthenticated Then Global.UpdateLastLoginTime(Me.User.Identity.Name, DateTime.Now.AddMonths(- 1)) End If End Sub 'Session_End Public Shared Sub UpdateLastLoginTime(username As [String], lastLoginTime As DateTime) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("update Users set LastLoginTime=@LastLoginTime where Username=@Username", conn) Dim paraLastLoginTime As SqlParameter = cmd.Parameters.Add("@LastLoginTime", SqlDbType.DateTime) paraLastLoginTime.Value = lastLoginTime Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'UpdateLastLoginTime Public Shared Function GetRolesOfUser(username As [String]) As [String]() Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select RoleName from UserRole where Username=@Username", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Dim roles As New ArrayList() While reader.Read() roles.Add(reader.GetString(0)) End While Return CType(roles.ToArray(GetType([String])), [String]()) Finally conn.Close() End Try End Function 'GetRolesOfUser Public Shared Function GetAllRoles() As [String]() Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select RoleName from Roles order by RoleName", conn) Try conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Dim result As New ArrayList() While reader.Read() result.Add(reader.GetString(0)) End While Return CType(result.ToArray(GetType([String])), [String]()) Finally conn.Close() End Try End Function 'GetAllRoles Public Shared Sub AddUserToRole(roleName As [String], username As [String]) If Global.IsUserInRole(roleName, username) Then Return End If Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("Insert into UserRole (Username, RoleName) values (@Username, @RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() cmd.ExecuteNonQuery() Catch Finally conn.Close() End Try End Sub 'AddUserToRole Public Shared Sub RemoveUserFromRole(roleName As [String], username As [String]) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("delete from UserRole where (Username=@Username) and (RoleName=@RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'RemoveUserFromRole Public Shared Sub RemoveUserFromAllRoles(username As [String]) Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("delete from UserRole where (Username=@Username)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Try conn.Open() cmd.ExecuteNonQuery() Finally conn.Close() End Try End Sub 'RemoveUserFromAllRoles Public Shared Function IsUserInRole(roleName As [String], username As [String]) As [Boolean] Dim conn As New SqlConnection(Global.ConnectionString) Dim cmd As New SqlCommand("select Username from UserRole where (Username=@Username) and (RoleName=@RoleName)", conn) Dim paraUsername As SqlParameter = cmd.Parameters.Add("@Username", SqlDbType.NVarChar) paraUsername.Value = username Dim paraRoleName As SqlParameter = cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar) paraRoleName.Value = roleName Try conn.Open() Return cmd.ExecuteNonQuery() > 0 Finally conn.Close() End Try End Function 'IsUserInRole Private Sub InitializeComponent() End Sub 'InitializeComponent
Unfortunately you are still going to have make some changes to your database layout to make it fit with the Cute Chat Database model above, but don't panic it's easier than it looks, just take it slow! Hope this helps.
Grisbi
|
|
-
10-06-2005, 9:07 AM |
-
prawlings
-
-
-
Joined on 10-03-2005
-
-
Posts 3
-
-
|
Re: integrating with custom login (VB.NET)
Hi Grisbi
Many thanks for the code. I am not really an expert at this, is there anyway you could send me the VS solution or files i would need. I do not mean to be cheeky and understand if you cant but i would really appreciate it as at this moment am stuck.
Paul
|
|
|
|
|