Passing Parameters from one page to another VB.net - asp.net

I have two pages, Act_Summary and Details. On the Summary page they will be clicking a link that will take them to the details page. I am wanting 3 parameters, UserName, StartDate, and EndDate to pass to the details page whenever they click the link. But every time I click the link it is giving me this error:
Object Reference Is not set to an instance of an object
This is my code on the Summary page:
Dim SD As String = StartWebDatePicker.Value
Dim ED As String = EndWebDatePicker.Value
Dim UserName As String = e.Row.Items.FindItemByKey("UserName").Value
ActSumm = "<b>Summary</b>"
and this is my code on the Details page:
Dim UserName As String = Encryption64.Decrypt(Request.QueryString("UserName"))
Dim StartDate As String = Encryption64.Decrypt(Request.QueryString("SD"))
Dim EndDate As String = Encryption64.Decrypt(Request.QueryString("ED"))
Page.Title = "" & UserName & "'s Activity Summary"
Dim SqlString As String = "Select Username, SD, ED"
Dim MyDataTable As DataTable = OleFun.GetMyDataTableString(SqlString)
WebDataGrid1.DataSource = MyDataTable
WebDataGrid1.DataBind()
Thanks in advance for your responses.

Haha wow, the whole time was because I had the parameter named "user" in the URL and was decrypting it as UserName... Face Palm

Related

Pull Outlook OfficeLocation using Alias

While referencing Return list of names and email address from outlook to vb.net listbox I am trying to fill in a ASP:Textbox with the Office Location of the user.
Currently I pull the current logged in user. The user's username on their PC is also their Outlook Alias. With that being said, I am trying to use the username/Alias to pull the Office location within Outlook. I currently have the following issue with my coding:
'get logged in user(works)
Dim username As String
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
username = User.Identity.Name.Substring(3)
'Office Location of User
Dim itemx As String
'Create an Outlook application.
Dim oApp As Outlook._Application = New Outlook.Application()
'Get the MAPI namespace.
Dim oNS As Outlook.NameSpace = oApp.Session
'Get the Global Address List.
Dim oALs As Outlook.AddressLists = oNS.AddressLists
Dim oGal As Outlook.AddressList = oALs.Item(1)
'Get all the entries.
Dim oEntries As Outlook.AddressEntries = oGal.AddressEntries
For Each entry In oEntries
If oEntries.GetExchangeUser.Alias = username Then
itemx = oEntries.GetExchangeUser.OfficeLocation
End If
Next
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article in MSDN.
As a workaround you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information. Or just a low-level API on which Outlook is based on - Extended MAPI.
Main thing that I learned was that you need a password and username to access outlook.
Get user ID from PC (Alias for Outlook):
Dim usernameQuery As String
Dim UserQ As System.Security.Principal.IPrincipal
UserQ = System.Web.HttpContext.Current.User
usernameQuery = User.Identity.Name.Substring(3).ToUpper
UserText.Text = usernameQuery
Then:
Call function like so:
'outlook office location **************************************************
LocationText.Text = GetUserInfo(usernameQuery, "physicaldeliveryofficename")
'OTHER OPTIONS YOU CAN QUERY
'Dim svalue As String = GetUserInfo(UserAccount, "mail")
'Dim svalue As String = GetUserInfo(UserAccount, "givenName")
'Dim svalue As String = GetUserInfo(UserAccount, "sn")
'Dim svalue As String = GetUserInfo(UserAccount, "l")
'Dim svalue As String = GetUserInfo(UserAccount, "st")
'Dim svalue As String = GetUserInfo(UserAccount, "streetAddress")
'Dim svalue As String = GetUserInfo(UserAccount, "postalCode")
'Dim svalue As String = GetUserInfo(UserAccount, "telephoneNumber")
'Dim svalue As String = GetUserInfo(useraccount, "co")
'txtName.Text = GetUserInfo(UserAccount, "givenName") & " " & GetUserInfo(UserAccount, "sn")
'txtPhone.Text = GetUserInfo(UserAccount, "telephoneNumber")
'********************************************************************************
Function:
Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
Try
Dim sPath As String = "LDAP://"full_path"/DC="path_value",DC="path_value",DC="path_value" "
Dim SamAccount As String = Right(inSAM, Len(inSAM) - InStr(inSAM, "\"))
Dim myDirectory As New DirectoryEntry(sPath, "username", "password") 'pass the user account and password for your Enterprise admin.
Dim mySearcher As New DirectorySearcher(myDirectory)
Dim mySearchResultColl As SearchResultCollection
Dim mySearchResult As SearchResult
Dim myResultPropColl As ResultPropertyCollection
Dim myResultPropValueColl As ResultPropertyValueCollection
'Build LDAP query
mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")
mySearchResultColl = mySearcher.FindAll()
'I expect only one user from search result
Select Case mySearchResultColl.Count
Case 0
Return "Null"
Exit Function
Case Is > 1
Return "Null"
Exit Function
End Select
'Get the search result from the collection
mySearchResult = mySearchResultColl.Item(0)
''Get the Properites, they contain the usefull info
myResultPropColl = mySearchResult.Properties
If myResultPropColl.Contains(inType) Then
myResultPropValueColl = myResultPropColl.Item(inType)
Return CStr(myResultPropValueColl.Item(0))
End If
'displayname, mail
'Retrieve from the properties collection the display name and email of the user
'myResultPropValueColl = myResultPropColl.Item(inType)
'Return CStr(myResultPropValueColl.Item(0))
Catch ex As System.Exception
End Try
Return "Null"
End Function
FYI-
full_path = "value"."value"."value"

Scrape information from asp.net gridview with paging

I'm trying to scrape some schedules off of a website. the information is displayed in a GridView with paging.
The url is:
http://www.landmarkworldwide.com/when-and-where/register/search-results.aspx?prgid=0&pgID=270&crid=0&ctid=&sdt=0
My Issue is when I want to scrape pages other then #1 in the grid view.
The best post I found so far was This One, but it doesn't work and that topic is not complete. I tried to use Fiddler and Chrome to get the post data and use it, but I can't get it to work for me. Can you guys see what's missing?
Here's the code I am using. it's in VB, but you can answer in C# and I'll translate -) (sorry)
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim lcUrl As String = "http://www.landmarkworldwide.com/when-and-where/register/search-results.aspx?prgid=0&pgID=270&crid=0&ctid=&sdt=0"
' first, request the login form to get the viewstate value
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(lcUrl), HttpWebRequest)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
' extract the viewstate value and build out POST data
Dim viewState As String = ExtractViewState(responseData)
Dim loHttp As HttpWebRequest = DirectCast(WebRequest.Create(lcUrl), HttpWebRequest)
' *** Send any POST data
Dim lcPostData As String = [String].Format("__VIEWSTATE={0}&__EVENTTARGET={1}&__EVENTARGUMENT={2}", viewState, HttpUtility.UrlEncode("contentwrapper_0$maincontent_0$maincontentfullwidth_0$ucSearchResults$gvPrograms"), HttpUtility.UrlEncode("Page$3"))
loHttp.Method = "POST"
Dim lbPostBuffer As Byte() = System.Text.Encoding.GetEncoding(1252).GetBytes(lcPostData)
loHttp.ContentLength = lbPostBuffer.Length
Dim loPostData As Stream = loHttp.GetRequestStream()
loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length)
loPostData.Close()
Dim loWebResponse As HttpWebResponse = DirectCast(loHttp.GetResponse(), HttpWebResponse)
Dim enc As Encoding = System.Text.Encoding.GetEncoding(1252)
Dim loResponseStream As New StreamReader(loWebResponse.GetResponseStream(), enc)
Dim lcHtml As String = loResponseStream.ReadToEnd()
loWebResponse.Close()
loResponseStream.Close()
Response.Write(lcHtml)
End Sub
Private Function ExtractViewState(s As String) As String
Dim viewStateNameDelimiter As String = "__VIEWSTATE"
Dim valueDelimiter As String = "value="""
Dim viewStateNamePosition As Integer = s.IndexOf(viewStateNameDelimiter)
Dim viewStateValuePosition As Integer = s.IndexOf(valueDelimiter, viewStateNamePosition)
Dim viewStateStartPosition As Integer = viewStateValuePosition + valueDelimiter.Length
Dim viewStateEndPosition As Integer = s.IndexOf("""", viewStateStartPosition)
Return HttpUtility.UrlEncodeUnicode(s.Substring(viewStateStartPosition, viewStateEndPosition - viewStateStartPosition))
End Function
To make it work you need to send all input fields to the page, not only viewstate. Other critical data is the __EVENTVALIDATION for example that you do not handle it. So:
First you need to make scrape on the #1 page. So load it and use the Html Agility Pack to convert it to a usable struct.
Then extract from that struct the input data that you need to post. From this answer HTML Agility Pack get all input fields here is a code sniped on how you can do that.
foreach (HtmlNode input in doc.DocumentNode.SelectNodes("//input"))
{
// use this to create the post string
// input.Attributes["value"];
}
Then when you have the post data that is needed to be a valid post, you move to the next step. Here is an example How to pass POST parameters to ASP.Net web request?
You can also read: How to use HTML Agility pack

Server Transfer with Session

I have a site contains login page and Default this is part of my code when trying to server transfer from login to Default
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim wrapper As New Simple3Des(MyKey)
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim user As String = wrapper.EncryptData(userNamePlan)
Dim pass As String = wrapper.EncryptData(PasswordPlan)
Session("un") = user.ToString
Session("pw") = PassWorldTextBox.Text
Server.Transfer("Default.aspx")
...
if I change Session("un") = user.ToString to UserNameTextBox.text it will transfer, if not, fail. And no Error Messages. Don't know why
I hope user is already string..Then you can write..
System.Web.HttpContext.Current.Session(“un”)=user;

Asp.Net Identity PasswordHasher not hashing

The following is the code I am using to effect a password change. I am following the pattern in the Manage.aspx page that comes in the Asp>net web application template for changing the password.
Using that method does NOT hash the password, which is odd since the registration DOES hash it. So, i added the passwordhasher. The problem is the IdentityResult is returning false every time even though the three parameters are correct. Every code line produces the correct result until this line, which produces false every time
UPDATE: The usr.ID in the ChangePassword method is the culprit. The username passed in is the ONLY entry in the users table BUT the usr.Id doesn't match the users id in the table. How is it even retrieving an id?
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
Here is the method
Private Sub btnSubmitPasswordChange_Click(sender As Object, e As EventArgs) Handles btnSubmitPasswordChange.Click
Dim db As New MySQLDatabase("MyConnString")
Dim ut As New UserTable(db)
Dim username As String = EncryptDecrypt.DecryptQueryString(Request.QueryString("rtu"))
Dim userId As String = ut.GetUserId(username)
Dim currentPass As String = ut.GetPasswordHash(userId)
Dim usr As New IdentityUser(username)
Dim manager = New UserManager()
manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False}
Dim phasher As New PasswordHasher
Dim newhash As String = phasher.HashPassword(Password.Text)
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
If result.Succeeded Then
Response.Redirect("~/Account/Login.aspx")
Else
lblResetSuccess.Text = "Password change failed!"
End If
Dim changed As Integer = ut.SetPasswordHash(userId, newhash)
End Sub

Get Data from One Table and Insert to Another Via Form Submission

How do I get a UserID from one database table (Users) to be inserted into another table (Ticket)? Both columns in each table has the same datatype (int). Please take a look:
Users
UserID
UserName
Password
FirstName
LastName
Email
Updated
Deleted
Ticket
TicketID
DateCreated
UserIDNum FK
FullName
Email
Subject
Message
Deleted
These are all of the codes involved:
Partial Public Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
MaintainScrollPositionOnPostBack = True
SetFocus(helpTopicDDL)
Else
SetFocus(fullNameTXTBOX)
End If
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select * from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#Username", Data.SqlDbType.VarChar)
cmdCheckEmail.Parameters.Add("#Username", SqlDbType.VarChar)
cmdCheckEmail.Parameters.Item("#Username").Value = Session("Ticket")
Dim obj As Object = cmdCheckEmail.ExecuteScalar()
If obj IsNot Nothing Then
mailLBL.Text = Convert.ToString(obj)
End If
End If
sConnection.Close()
End Sub
Protected Sub submitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitBTN.Click
Dim sdConnection As String = ConfigurationManager.AppSettings("TrackTicketsConnectionString2")
Dim iRowCount As Integer
Dim cmdInsertTicket As New Data.SqlClient.SqlCommand
Dim conticket As New Data.SqlClient.SqlConnection
conticket.ConnectionString = sdConnection
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "Insert Into Ticket " _
& "( DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values( #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
'Dim appUserName As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.NVarChar)
'cmdInsertTicket.Parameters.Add(appUserName)
'cmdInsertTicket.Parameters.Item("#UserName").Value = User.Identity.Name
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
Dim appFullName As New Data.SqlClient.SqlParameter("#FullName", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appFullName)
cmdInsertTicket.Parameters.Item("#FullName").Value = fullNameTXTBOX.Text
Dim appEmail As New Data.SqlClient.SqlParameter("#Email", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appEmail)
cmdInsertTicket.Parameters.Item("#Email").Value = emailAddTXTBOX.Text
Dim appTicketType As New Data.SqlClient.SqlParameter("#TicketType", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appTicketType)
cmdInsertTicket.Parameters.Item("#TicketType").Value = helpTopicDDL.SelectedValue
Dim appSubject As New Data.SqlClient.SqlParameter("#Subject", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appSubject)
cmdInsertTicket.Parameters.Item("#Subject").Value = subjectTXTBOX.Text
Dim appMessage As New Data.SqlClient.SqlParameter("#Message", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appMessage)
cmdInsertTicket.Parameters.Item("#Message").Value = messageTXTBOX.Text
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
conticket.Open()
Try
iRowCount = cmdInsertTicket.ExecuteScalar()
statusLBL.Text = "Ticket has been submitted successfully."
Catch
statusLBL.Text = "Ticket has not been submitted. Please try again."
End Try
conticket.Close()
End Sub
What I really wanted is for a person's UserID to be stored in Ticket table after he has logged in to fill out a form and submitted it. I'm at a loss in how to pull the data from Users table to insert into Ticket table. Any help is much appreciated as I'm still learning.
EDIT:
Inserting the UserID into the Tickets table when adding a record first requires that you have access to the UserID value. You then need to pass this value in your INSERT statement.
Looks like we first need to retrieve the UserId. Since you are using FormsAuthentication we can retrieve the UserName from the User.Identity.Name object and use that as the value in our first query to retrieve the UserId.
Dim cmdS As String = "Select [UserID] from Users Where Deleted='N' AND UserName=#UserName"
Dim cmdGetUserId As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.VarChar)
cmdGetUserId.Parameters.Add("#UserName", SqlDbType.VarChar)
cmdGetUserId.Parameters.Item("#UserName").Value = User.Identity.Name
Dim obj As Object = cmdGetUserId.ExecuteScalar
Dim myUserId As Integer = Integer.Parse(obj)
Now that we have the UserId value for our current user we can modify our INSERT statement and parameters.
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "INSERT INTO Ticket " _
& "(UserID, DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values(#UserID, #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
Dim appUserId As New Data.SqlClient.SqlParameter("#UserID", Data.SqlDbType.Int)
cmdInsertTicket.Parameters.Add(appUserId)
cmdInsertTicket.Parameters.Item("#UserID").Value = myUserId
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
...
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
You can access authentication information through the User.Identity object once the user has been authenticated. Might also want to think about implementing a custom IIdentity class to store the UserID if you will need access to it often. Here's a good MSDN article about Custom Authentication: http://msdn.microsoft.com/en-us/library/ms172766(v=vs.80).aspx
UPDATE:
In regards to the comment below, you are retrieving the UserID because the SqlCommand is being executed with the ExecuteScalar method which returns the value of the first column of the first row. I would recommend taking a closer look at the SqlCommand object: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx and this ADO.NET primer on MSDN: http://msdn.microsoft.com/en-us/library/e80y5yhx(v=vs.80).aspx

Resources