Server Transfer with Session - asp.net

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;

Related

Passing Parameters from one page to another VB.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

Downloading html as string

I am trying to download a webpage as string. Can someone please explain why the following code doesn't work?
Dim URL As String = "http://stackoverflow.com/"
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
When I run it it never goes inside the loop.
Give this a shot...
Dim URL As String = "http://stackoverflow.com/"
Dim html As String = New WebClient().DownloadString(URL)
Better Solution (Releases resources that the network stack is using. Also ensure's (hope) the CLR cleans these up when needed.)
Using client As New WebClient()
html = client.DownloadString(URL)
End Using

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"

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

How to pass parameters to SSRS report programmatically

I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.
Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?
Thanks.
You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)
LocalReport myReport = new LocalReport();
myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc");
ReportParameter myParam = new ReportParameter("ParamName", "ParamValue");
myReport.SetParameters(new ReportParameter[] { myParam });
// more code here to render report
If the Report server is directly accessible, you can pass parameters in the Querystring if you are accessing the repoort with a URL:
http://MyServer/ReportServer/?MyReport&rs:Command=Render&Param1=54321&Param2=product
You can add output formatting by adding the following on the end of the URL:
&rs:Format=Excel
or
&rs:Format=PDF
It's been a while since I did this code, but it may help:
Your web project has to be a Web Site, and not a project of type "ASP.Net Web Application", or you won't be able to add the reference mentioned below.
Right click on the project and add an ASP.Net folder - App_WebReferences. You'll have to specify the server where your SRS is; choose the .asmx.
Once it's added, the folder under that level is called RSService, and under that are 2 things: reportservice.discomap & .wsdl.
In my VB, I do Imports RSService and Imports System.Web.Services.Protocols, then...
Dim MyRS As New ReportingService
The reporting service is on a different server than the webserver the app is on, so I can't do the following: MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials
Instead: MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3),
where the rs1/2/3 are the login to SRS box, password to SRS box, & domain name". (These are encrypted in my web.config.)
Then, a mass-paste:
MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)
Dim ReportByteArray As Byte() = Nothing
Dim ReportPath As String = "/SRSSiteSubFolder/ReportNameWithoutRDLExtension"
Dim ReportFormat As String = "PDF"
Dim HistoryID As String = Nothing
Dim DevInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
'Dim x As ReportParameter - not necessary
Dim ReportParams(0) As ParameterValue
ReportParams(0) = New ParameterValue()
ReportParams(0).Name = "TheParamName"
ReportParams(0).Value = WhateverValue
Dim Credentials As DataSourceCredentials() = Nothing
Dim ShowHideToggle As String = Nothing
Dim Encoding As String
Dim MimeType As String
Dim ReportHistoryParameters As ParameterValue() = Nothing
Dim Warnings As Warning() = Nothing
Dim StreamIDs As String() = Nothing
'Dim sh As New SessionHeader() - not necessary
''MyRS.SessionHeaderValue = sh - not necessary
ReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _
ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)
'(Yay! That line was giving "HTTP error 401 - Unauthorized", until I set the credentials
' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)
'Write the contents of the report to a PDF file:
Dim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)
fs.Write(ReportByteArray, 0, ReportByteArray.Length)
fs.Close()
Call EmailTheReport(FullReportPath)
If IO.File.Exists(FullReportPath) Then
IO.File.Delete(FullReportPath)
End If
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.Reset();
Label1.Visible = false;
ReportViewer1.Visible = true;
DataSet dataSet = new DataSet();
dataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text,
ddlType.SelectedValue, levelcode, fields);
ReportDataSource datasource = new ReportDataSource("DataSet_StoreprocedureName",
dataSet.Tables[0]);
if (dataSet.Tables[0].Rows.Count == 0)
{
ReportViewer1.Visible = false;
}
ReportViewer1.LocalReport.ReportPath = Server.MapPath("") + #"\Report.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
string fields="name,girish,Z0117";
string[] filedName = fields.Split(',');
ReportParameter[] param = new ReportParameter[2];
//for (int i = 0; i < filedName.Length; i++)
//{
param[0] = new ReportParameter(filedName[0], filedName[0], true);
param[1] = new ReportParameter(filedName[3], filedName[3], true);
// }
ReportViewer1.LocalReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();

Resources