I'm trying to get thee previous page visited in ASP.NET using VB.NET using the following code:
Partial Class _Default Inherits Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If (Request.UrlReferrer <> Nothing) Then
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
Else
lblUsername.Text = "Welcome, Guest"
End If
End If
End Sub
End Class
I get this error:
Object reference not set to an instance of an object.
at:
Dim previousPage As String = Page.Request.UrlReferrer.ToString
What I want to do is get the previous page visited so I can get a session variable.
Try This code.
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If (Request.UrlReferrer <> Nothing) Then
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
End If
Else
lblUsername.Text = "Welcome, Guest"
End If
End Sub
End Class
Unsure what you are trying to do but while its easy enough to answer your specific question, you should take a step back and review why you are doing things that way.
It seems you are trying to control flow based on some authentication. If so, consider ASP.Net Forms Authentication +/- Login Controls. You can "plug" this architecture into your existing auth mechanism (meaning you don't have to uproot your existing stuff to implement it).
(If you still want to reinvent the wheel) Consider cookies instead of trying to figure out "where the user came from" prior to landing on "this" page - both of which can vary by x - the more web pages your web site has or will have, you'll have more spaghetti.
Related
When I open a page from another web application on same domain I am trying to read the cookie that was created on the original page, But it I cant read the cookie. If I move that page in to the same web application then it works, but thats not what I want.
[Domain: MyCompany.mobi]
[WebApp A] - create cookie and launch page
Protected Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim aCookie As New HttpCookie("TestCookie")
aCookie.Value = "Hello World"
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
Dim script = "window.open('http://MyCompany.mobi/webappB/default.aspx?id=TestCookie')"
'open page in WebsiteB
ScriptManager.RegisterStartupScript(Me, Me.GetType, "OpenPage", script, True)
End Sub
[Domain: MyCompany.mobi]
[WebApp B] - read the cookie and display in label
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim id As String = ""
If Request.QueryString("id") IsNot Nothing Then id = Request.QueryString("id").ToString
If Request.Cookies(id) IsNot Nothing Then
Dim aCookie As HttpCookie = Request.Cookies(id)
Label1.Text = aCookie.Name & " : " & aCookie.Value
Else
Label1.Text = "Cannot read cookie"
End If
End Sub
Cookies are associated with domain names; not the physical servers that are pointed to by DNS.
For security reasons, you cannot read cookies from a different domain name.
You need to pass the information in the URL.
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
Working over 5 hours on the following problem:
Private Sub ModulEdit_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
Dim modulid As Integer = 1
loadeditors(modulid)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub loadeditors(modulID As Integer)
PlaceHolder1.Controls.Clear()
Using dbContext As New EntitiesModel()
Dim mps As List(Of ef.Modulparameter) = dbContext.Modulparameters.Where(Function(c) c.ModulID = modulID).ToList
Dim mmid As Int16
If EditMode.Checked = True Then
mmid = RadComboBox3.SelectedValue
End If
Dim mp As ef.Modulparameter
For Each mp In mps
Dim lbl As New Label
lbl.Text = "<BR>" & mp.Name & "<BR>"
PlaceHolder1.Controls.Add(lbl)
Select Case mp.Editor.Name
Case "textbox1line"
Dim con As New TextBox
con.ID = mp.ID
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Text = mpa.Valuestring
Catch ex As Exception
con.Text = "AAAA"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
Case "radeditor"
Dim con As New RadEditor
con.ID = mp.ID
con.ToolsFile = "\admin\controls\ToolsFile.xml"
'con.CssFiles.Add("\Content\frenzy\css\frenzy-orange.css")
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Content = mpa.Valuestring
Catch ex As Exception
con.Content = "BBBB"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
End Select
Next
End Using
End Sub
I add the control dynamicly, calling the codepart above in pre_init (tryed in load and init too with same result)
The value (text) for the control is there until that line PlaceHolder1.Controls.Add(con)
After the con.text is empty.
The control is added after, but with no value.
Strange, that in the same proc i add another control (label), where the text value is on the page after.
Adding additional info:
the control value (text or content), when debugging the LoadEditors), is allways correctly set. But then on the page both (textbox and radeditor) are empty
The routing is called from pre init, as described in a lot of related posts.
You are calling loadeditors in ModulEdit_Init. Shouldn't this be LoadControls ?
I fixed it myself:
Adding "con.ViewStateMode = System.Web.UI.ViewStateMode.Disabled" before adding control to placeholder
Calling "loadeditors()" in RadComboBox3 too
much probably the problem was, that i loaded editors in page-load or init, which got the correct values, but then the RadComboBox3.SelectedIndexChanged event was called, which overwrote the values somehow
So my answer is not a real answer, but it works now (I hate such: it works, but i dont know why) ;)
i have a project where i need to use the active directory for login to a website made in asp.net, i follow this tutorial....
Active Directory Authentication from ASP .NET
now i want to get the groups of the user, i tried the next code in the default.aspx.vb page but doesn't work..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write("Hello, " + Server.HtmlEncode(User.Identity.Name))
Dim id As FormsIdentity = CType(User.Identity, FormsIdentity)
If id IsNot Nothing Then
Dim ticket As FormsAuthenticationTicket = id.Ticket
Response.Write("<p/>TicketName: " + ticket.Name)
Response.Write("<br/>Cookie Path: " + ticket.CookiePath)
Response.Write("<br/>Ticket Expiration: " + ticket.Expiration.ToString())
Response.Write("<br/>Expired: " + ticket.Expired.ToString())
Response.Write("<br/>Persistent: " + ticket.IsPersistent.ToString())
Response.Write("<br/>IssueDate: " + ticket.IssueDate.ToString())
Response.Write("<br/>UserData: " + ticket.UserData)
Response.Write("<br/>Version: " + ticket.Version.ToString())
End If
End Sub
I find a better solution, is more easy than any answer that i find on the internet.
First i create a class to validate if an user is in a group in the active directory:
Imports System.Security.Principal
Public Class AutorizationFun
Dim access As Boolean = False
Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
Public User As WindowsPrincipal = New WindowsPrincipal(id)
Region "Groups Verification"
'Belongs to sample group
Private Function inSampleGroup() As Boolean
Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP")
End Function
Private Function inSampleGroup2() As Boolean
Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP2")
End Function
End Region
Public Function ProgramsAccsess(ByVal vPage As String) As Boolean
access = False
Select Case vPage
Case "~/Sample.aspx"
If inSampleGroup() Then
access = True
End If
'---------------------------------------------------------------------
End Select
'*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
'access = True
'*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Return access
End Function
End Class
Then you have to create a function in the code behind of all pages:
'create var
Dim ValidateUser As New AutorizationFun
Protected Sub VerifyAccessPage()
If ValidateUser.ProgramsAccsess(Request.AppRelativeCurrentExecutionFilePath) = False Then
Response.Redirect("~/DeniedAccess.aspx")
End If
End Sub
And to finish to have to use the function in the Page_load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'check whether page is postback or not
If Not Page.IsPostBack Then
VerifyAccessPage()
End If
End Sub
If your server is in a Windows Domain it should be connected to Active Directory, so by using windows authentication you already login with AD credentials (since the user has to be in the domain before, or it will be asked for AD credentials by the browser)
To get the user groups you could use the DirectorySearcher class, obviously when you
I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen. please help!
Public Sub GetCustomers()
db.RunProcedure("usp_customers_get_all")
db.doSort(radList.SelectedValue)
gvCustomers.DataSource = db.MyView
End Sub
Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged
If radList.SelectedValue = 0 Then
db.doSort(0)
gvCustomers.DataSource = db.MyView
End If
If radList.SelectedValue = 1 Then
db.doSort(1)
gvCustomers.DataSource = db.MyView
End If
End Sub
Public Sub doSort(ByVal strIn As Integer)
If strIn = 0 Then
MyView.Sort = "lastname, firstname"
Else
MyView.Sort = "username"
End If
End Sub
Public Sub RunProcedure(ByVal strName As String)
Dim objConnection As New SqlConnection(mstrConnection)
Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection)
Try
mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
Me.mDataset.Clear()
mdbDataAdapter.Fill(mDataset, "tblCustomers")
MyView.Table = mDataset.Tables("tblCustomers")
Catch ex As Exception
Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message)
End Try
End Sub
You could store the dataset in one of the following places and then when the post back happens just load it again from there. I have done many of these on a corporate intranet.
Session Variable
ViewState
QueryString
Cache
I cant really provide more help as you didn't specify if this is done in Ajax or if you do a full postback etc. If you provide more info I would love to help you.