Connect asp.net(vb) to database in SQL Server - asp.net

I'm creating a login form in my asp.net page and my problem now is I don't know how to connect my asp.net (vb) to the SQL Server database.
I wanted to insert the connection code in the
<script runat="server"> </script>
Is this possible?
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Login.aspx.vb" Inherits="_Default" %>
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
lblDate.Text = Format(Now, "MMMM dd,yyyy hh:mmtt")
End Sub
</script>
<!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">
<link rel="icon" type="image/png" href="SENCOR_Logo.ico">
<title>Auto OCS System</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="date_time">
<p><asp:Label id="lblDate" runat="server" Text ="DateandTime"></asp:Label></p>
</div>
<div id="wrapper">
<div class = "container">
<div class = "login">
<h1><img src="SENCOR_Logo.jpg" height="35px;"></h1>
<form method = "post" action = "" runat="server">
<p><asp:TextBox id="txtUser" runat="server" placeholder="Username"/></p>
<p><asp:TextBox id="txtPass" runat="server" TextMode="Password" placeholder="Password"/></p>
<p class = "remember_me">
<label>
<label>
<asp:CheckBox id="chkRem" runat="server"/>
Remember me on this computer
</label>
</label>
</p>
<p class="submit"><asp:Button id="btnLogin" Text="Login" runat="server" OnClick = "btnLogin_Click" /></p>
</form>
</div>
<div class="login-help">
<p>Forget your password? <asp:HyperLink id="lnkRem" runat="server" Text="Click here to reset it." NavigateUrl ="~/Login.aspx"></asp:HyperLink></p>
</div>
</div></div>
<div class="footer">
<p>© 2016 Emilyn Pascua. All rights reserved.</p>
</div>
</body>
</html>

This may help you.change code according to your data
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Passowrd As String
Dim Passowrd2 As String
Dim userName As String
Try
If
/*change the data source and initial catalog according to your sql server engine and data base*/
con.ConnectionString = "Data Source = YOUR-PC; Initial Catalog = YOUR-DB; Integrated Security = True"
con.Open()
cmd.Connection = con
/*change the data fields names and table according to your database*/
cmd.CommandText = " SELECT UserName, Password FROM AdminDetail WHERE (UserName = '" & txtUsername.Text & "' ) AND (Password = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
//Do something here
Passowrd = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Passowrd2 = txtPassword.Text()
If Passowrd = Passowrd2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
frmMain.Show()
Me.Hide()
//Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
//Clear all fields
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() //Whether there is error or not. Close the connection.
End Try
End Sub
I hope you can embed the same in your server tags..you may refer the following link for clarification
http://www.aspsnippets.com/Articles/Different-Embedded-Code-Blocks-and-its-use-in-ASPNet.aspx

String cons = "Data Source=.; initial Catalog=SalaamUnExamSystem; Integrated Security=true";
SqlConnection con = new SqlConnection(cons);
SqlCommand cmd = new SqlCommand("insert into stdtbl values('" + StdName.Text + "','" + FName.Text + "','"+gender+"')",con);
con.Open();
int r=cmd.ExecuteNonQuery();
if (r > 0)
{
lblMessage.Text="inserted";
}
else
{
lblMessage.Text = "Not Inserted";
}

Related

Require logging in to view page

I have 2 pages:
login.aspx <Public
user.aspx <Should be locked behind a login
I have been trying to get this to work but I have not idea where to go from where I am now. Google mainly shows C# instead of vb.net.
I created a login page which works and continues to the next page.
However..
I can also type in the next page URL and I would not need to login.
How can I make it so the 2nd page tells me you need to be logged in to view this page.
What I have so far is:
login.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="login.aspx.vb" Inherits="web.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
height: 172px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="auto-style1">
Loginpage<br />
<br />
user:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
password:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Code behind:
Imports System.Data.SqlClient
Public Class WebForm1
Inherits UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "myconstring"
Dim objcon As SqlConnection = Nothing
Dim objcmd As SqlCommand = Nothing
objcon = New SqlConnection("myconstring")
objcon.Open()
Dim stmt As String = "select * from login where Username = '" & TextBox1.Text & "' AND Password = '" & TextBox2.Text & "'"
objcmd = New SqlCommand(stmt, objcon)
Dim reader As SqlDataReader = objcmd.ExecuteReader
If reader.Read Then
Response.Redirect("user\user.aspx")
Else
Label1.Visible = True
Label1.Text = "Login onjuist"
End If
End Sub
End Class
In the code behind of your users page you can check if the user is authenticated. If they are not authenticated, you can redirect them to a page that informs them they must be logged in to access the page they were trying to visit. The code below just redirects to the login page.
If HttpContext.Current.User.Identity.IsAuthenticated = False Then
Response.Redirect("~/Login.aspx")
End If
Another option is you can define a location section in your web.config. The following code denies access to users.aspx, for users that are not authenticated.
<location path="users.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

How to clear form after button pressed and show a message ASP.NET

I am learning ASP.NET 4 and i am trying to a form which the user enter details into text boxes and drop downs and then presses enter to complete form and the details go into a database in Oracle. What i would like to do is when the enter button is pressed i would like it to clear the form of anything entered and then show a message to say something like 'Thank you for your details'.
The form is working and records all the information to the database so all i need help with is clearing the form after button pressed and then to show message.
I'm not sure what code i need to show you so please ask if you do or anything else if i have not explained myself enough.
Thanks
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="navigationB">
<ul id="nav">
<li>Home</li>
<li>News</li>
<li>Contact</li>
<li>About</li>
<li>Finance Help</li>
</ul>
</div>
<div id="dform">
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<h3 id="head3"><u>Please Enter Your Details:</u></h3>
Enter Your Name:
<asp:TextBox ID="nameB" runat="server"></asp:TextBox>* <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="You Must Provide Your Name" ControlToValidate="nameB"></asp:RequiredFieldValidator>
<br />
Enter Your Age:
<asp:TextBox ID="ageB" runat="server"></asp:TextBox>* <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ageB" ErrorMessage="You Must Enter Your Age"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Age Must be Between 1-99" ControlToValidate="ageB" MaximumValue="99" MinimumValue="1" SetFocusOnError="True"></asp:RangeValidator>
<br />
<br />
Male:
<asp:CheckBox ID="cbMale" runat="server" groupname="sexB" />
<br />
Female:
<asp:CheckBox ID="cbFemale" runat="server" groupname="sexB"/>
<br />
<br />
<h3 id="header3"><u>Select Hospital Department</u></h3>
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>*
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>*
<br />
<asp:RequiredFieldValidator runat="server" ErrorMessage="You Must Select One Option" ControlToValidate="DDList"></asp:RequiredFieldValidator>
&nbsp ; <asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server" ErrorMessage="You Must Select One Option" ControlToValidate="DDList2"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="ButtonEnt" runat="server" Text="Enter"/> <asp:Button id="btnReset" onclick="btnReset_Click" runat="server" Text="Reset Form"></asp:Button>
<br />
<br />
<asp:Label ID="requiredField" runat="server" Text="(*) Denotes Required Field"></asp:Label>
<br />
</div>
</form>
</body>
</html>
My Function..
Imports Microsoft.VisualBasic
Imports Oracle.DataAccess.Client
Imports System.Data
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
Public Shared Function tableData2() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'CATEGORY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
Public Shared Function dataInsertTable(ByVal sName As String, ByVal iAge As Integer, ByVal sSelect As String, ByVal dList As String, ByVal dList2 As String) As String
Dim answer As String = "Y"
Dim conSmart As New OracleConnection
conSmart.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.CommandType = Data.CommandType.Text
oraCommand.Connection = conSmart
Dim lsSQL2 As String = ""
lsSQL2 = "INSERT INTO TEST_JC VALUES ('" & sName & "','" & iAge & "','" & sSelect & "','" & dList & "','" & dList2 & "' , sysdate )"
oraCommand.CommandText = lsSQL2
Try
conSmart.Open()
oraCommand.ExecuteNonQuery()
conSmart.Close()
Catch ex As Exception
answer = ex.Message
End Try
Return answer
End Function
End Class
put these lines like this in your button click event after saving values in database :
nameB.Text = "";
ageB.Text = "";
...
cbMale.Checked = false;
...
and bind your dropdownlists again too and finally show your message
On submit do,
call Clear();
public void Clear()
{
txtname.text="";
txtage.text="";
}
Protected void btnsubmit_click()
{
Scriptmanager.Registerstartupscript(this, GetType(), "show your alert message","showalert()", true)
Clear();
}
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
ScriptManager.RegisterStartupScript(Me, [GetType](), "displayalertmessage", "Showalert();", True)
txtname.Text = ""
txtage.Text = ""
dropdownlist.Text = ""
End Sub
This will Help you.

display image from db alongside other webpage elements

A continuation of the question on display (not download) image from db
<%# Page Language="VB" AutoEventWireup="false" CodeFile="imgTest1.aspx.vb" Inherits="imgTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="background-color: aliceblue;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div style="background-color: burlywood;">
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?id=1" />
<br />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class imgTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("id") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "filename=" & dt.Rows(0)("name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("CapstoneConnectionString1").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
End Class
I can now display the image on the aspx page but only the image is being displayed, all other web elements are missing.
I can only think of one reason for this, given that following are true:
Page used to render contents is imgTest1.aspx as well as page used to return image is also imgTest1.aspx.
imgTest1.aspx is always invoked with query parameter, id.
because of this page always returns an image.
Can you change the code as follows and tell us how it works:
...
...
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?imageId=1" />
...
...
and in code-behind
If Request.QueryString("imageId") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")

Using SqlBulkCopy SqlRowsCopied to update a label

I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

get first name from user table master_page

I'm using a masterPage.master to get the login info for my application. When the user login in with username/password it shows the username as logged in and I would like it to be more personal by pulling the firstname only. How can I do this, I tried all I know, I'm new to ASP.Net.
masterpage: `
<div id="login">
<asp:LoginView ID="MasterLoginView" runat="server">
<LoggedInTemplate>
Welcome:
<asp:LoginName ID="MasterLoginName" runat="server" Font-Bold="True" />
</LoggedInTemplate>
<AnonymousTemplate>
Welcome: Guest...
</AnonymousTemplate>
</asp:LoginView>
</div>
<div id="login2">
<asp:LoginStatus ID="LoginStatus1" runat="server"
LogoutAction="Redirect" LogoutPageUrl="access/LoggedOut.aspx"
LoginImageUrl="images/login.jpg" LogoutImageUrl="images/logout.jpg" LoginText=""
LogoutText="" />
</div>`
Login.aspx:
<asp:Label ID="Login1" runat="server" Text="Label" ForeColor="White"></asp:Label>
<p>Username:
<asp:TextBox ID="txtusername" runat="server" Width="150px"></asp:TextBox></p>
<p>Password:
<asp:TextBox ID="txtpassword" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
</p>
<asp:ImageButton ID="LoginButton" runat="server" ImageUrl="../images/lsubmit.png"
OnClick="LoginBtnClick" ValidationGroup="a" ToolTip="Submit" ImageAlign="AbsBottom" />
login.aspx.vb
Partial Public Class Login
Inherits System.Web.UI.Page
Private con As New SqlConnection()
Private adp As SqlDataAdapter
Private ds As New DataSet()
Protected Sub LoginBtnClick(sender As Object, e As System.EventArgs) Handles LoginButton.Click
Dim con As New SqlConnection("Data Source=HQDANA3A413VDB1;Initial Catalog=Sigar;User ID=Sigar_Admin;Password=$Jzpoj^6z>%y9E")
con.Open()
' here with the help of this sql query i am matching the username and password of //the user.
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from Users where username=#username and password=#password"
cmd.Connection = con
' here i am passing the parameter of username and password
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = txtusername.Text
cmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = txtpassword.Text
Dim firstName As New SqlParameter("#firstname", SqlDbType.VarChar, 50, ToString)
firstName.Value = ToString()
cmd.Parameters.Add(firstName)
Dim dr As SqlDataReader = cmd.ExecuteReader()
' here i am using hasrows to check the correct user. If the username and the password
'//of the user will be mathed with the database then it will be go to the checkuser.aspx //page otherwise it prints the message wrongusername or password
If dr.HasRows Then
dr.Read()
' here i am creating a formauthentication ticket that will be use in the whole //application.
'This is the main part of the formauthentication security, inside dr[2] //there is a role of the user
Dim tkt As New FormsAuthenticationTicket(1, txtusername.Text.ToUpper, DateTime.Now, DateTime.Now.AddHours(3), False, dr(2).ToString(), _
FormsAuthentication.FormsCookiePath)
' here i am enctypt the ticket. With the encryption of this ticket it will encrypt the //username
Dim st As [String] = FormsAuthentication.Encrypt(tkt)
' here i am creat a cookie that will we used inside the whole application
Dim ck As New HttpCookie(FormsAuthentication.FormsCookieName, st)
Response.Cookies.Add(ck)
' Validate the user against the Membership framework user store
'If Membership.ValidateUser(txtusername.Text, txtpassword.Text) Then
' Log the user into the site
'FormsAuthentication.RedirectFromLoginPage(txtusername.Text, RememberMe.Checked)
Response.Redirect("checkuser.aspx")
Else
LabelFailedAuthentication.Visible = True
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
CancelButton.Attributes.Add("onClick", "javascript:history.back(); return false;")
End Sub
End Class
You can use the LoginStatus control to set the logout text, assuming that the first name is the first part of your Username (in Master):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.LoginStatus1.LogoutText = "Logout: " & GetUserName()
End Sub
Public Function GetUserName() As String
If HttpContext.Current.User.Identity.IsAuthenticated Then
If ViewState("UserName") Is Nothing Then
Dim user As MembershipUser = Membership.GetUser()
' split user-name, assuming that the first part is the firstname '
Dim nameParts = user.ToString().Split()
ViewState("UserName") = nameParts(0)
End If
Return DirectCast(ViewState("UserName"), String)
Else
Return String.Empty
End If
End Function

Resources