Decoding Encrypted Query string - asp.net

I am using the method described in the following LINK and I am using the following code to encrypt:
'Page1.aspx
Protected Sub butEncrypt_Click(sender As Object, e As EventArgs) Handles butEncrypt.Click
Dim QueryString As String = "type=Int&pk=" & _primaryKey
QueryString = Tools.encryptQueryString(QueryString)
Response.Redirect(/SearchResults.aspx?Val=" & QueryString)
End Sub
and then finally de-encrypt:
'SearchResults.aspx
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If Not String.IsNullOrEmpty(HttpContext.Current.Request(CIAppGlobals.GlobalVar.Val)) Then
Dim qs As String = Request.QueryString(CIAppGlobals.GlobalVar.Val)
qs = Tools.decryptQueryString(qs)
Dim Values As String() = qs.Split(CChar("&"))
_imageType = String.Empty
_primaryKey = 0
For Each value As String In Values
Dim data As String() = value.Split(CChar("="))
Select Case data(0).ToUpper
Case "TYPE"
_imageType = data(1)
Case "PK"
_primaryKey = CInt(data(1))
End Select
Next
Else
_imageType = HttpContext.Current.Request("type")
_primaryKey = CInt(HttpContext.Current.Request("pk"))
End If
End If
End Sub
My question is should I being using a different method to extract the decoded query string values other than what I am doing? Thanks in advance for your constructive responses.
Solution
After looking at Darin's response I have decided to incorporate it into my project, here is my updated code:
'Page1.aspx
Protected Sub butEncrypt_Click(sender As Object, e As EventArgs) Handles butEncrypt.Click
Dim query = HttpUtility.ParseQueryString(String.Empty)
query("type") = "Int"
query("pk") = CStr(_primaryKey)
Dim QueryString As String = Tools.encryptQueryString(query.ToString())
Response.Redirect(/SearchResults.aspx?Val=" & QueryString)
End Sub
I still want to encrypt the query string because I want to prevent users from changing the Query String Values manually

You are incorrectly building the query string in the first place. You are using string concatenations and not properly encoding them. What if _primaryKey contains a & or = characters? You could use the ParseQueryString method to properly build a query string:
Dim query = HttpUtility.ParseQueryString(String.Empty)
query("type") = "Int"
query("pk") = _primaryKey
Dim queryString = query.ToString()
The same method could be used for parsing the decoded query string:
Dim values = HttpUtility.ParseQueryString(qs)
Dim type = query("type")
Dim primaryKey = query("pk")
' work with the type and primaryKey values
Never use string concatenations and splitting when dealing with urls. Always use the right tool for the right job.
That's as far as creating/parsing query strings is concerned. As far as encrypting/decryption the values is concerned, you haven't shown/told us anything about the Tools class that you are using so I cannot provide you with any constructive comments about it.
You know that the best encryption is to never send the actual value to the client. So you could store it in some backend storage on the server and then use an unique id in the url. This id could be used on the target page to fetch the original value. This way you don't need to be encrypting/decrypting anything.

Related

parameters not passing to ssrs ServerReport - rendering report to pdf using ServerReport.Render

My code that sets up a ServerReport object on a web forms page, and then renders the report from SSRS to a pdf. Parameter and report name is passed by URL.
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim reportname As String
'Dim parameter(0) As ReportParameter
reportname = Request("reportname").ToString
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim serverreport As New ServerReport
serverreport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
'now print
Response.Redirect("reports.ashx?fileName=" & reportname)
End Sub
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(Bytes, 0, Bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
The report renders and saves as a pdf but the parameter value does not seem to be getting used in the report.
I have confirmed over and over that there is a value in paramBlock.
I don't know what I am doing wrong.
Am I missing a step or something?
Ryan
As your report is being rendered and saved, I'm assuming the credentials are set up correctly.
You can use the ServerReport.GetParameters function before saving the report to check what the parameters (and their values/properties) actually are.
Also, make sure you're setting every parameter required by the report (even those hidden or internal), and that every parameter value is within the allowed values of the parameter (if limits are set).
If the problem doesn't lie in passing the parameters, you might want to take a look at the report itself and how it handles its parameters.
From your recent comment about a "Parameter validation failed" error, it sounds like your issue is not with your calling code structure, but rather matching the parameters to the report definition.
The most common issue is hidden or internal parameters which you are ignoring. You need to carefully review the parameter design in SSRS Report Designer, and make sure your passed parameters comply with what it expects.
Consider following suggestions. It might help you to resolve your issue. After considering every point, you can try your code
Place following code just above the Select Case reportname statement line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
You can also try changing code line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
To
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
If your report has default parameters, then remove default parameters and test your code
And also remove exception handling from your method
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
You can try following code:
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim reportname As String = Request("reportname").ToString
'Dim parameter(0) As ReportParameter
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim ServerReport As ServerReport
ServerReport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
End Sub
Public Sub Save(ByRef sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(bytes, 0, bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
Maybe this is not the case, but I remember that Parameters value can be lost during PostBack.
So I would try a syntax like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.IsPostBack Then
'your code to setup and print report
End If
End Sub
If this solution doesn't work please provide the code used in Report Definition.

Convert String into integer in asp.net

I have a gridview in which I insert a checkbox on check_changed even I write the following codes to get the value of Issue Id as mentioned in image also showing values in textbox, but when I use these string in SQL:
Select * from IssueBook Where IssueId IN (values)
It shows error converting varchar to numeric on check_changed I write these codes I have take IssueId (numeric)
Protected Sub CheckBox1_CheckedChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim x As String = ""
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = row.FindControl("checkbox1")
If cb IsNot Nothing AndAlso cb.Checked Then
If x <> "" Then
x += ","
End If
x += row.Cells(1).Text
End If
Next
RwId.Text = x
Session("SelctdIsuedBokNo") = RwId.Text
In data table I used numeric value.
How can I convert above codes into integers such as 4,5,6, with comma separator?
The IN statement requires a list of comma separated values, not a "string" with those values.
You should create a dynamic SQL and pass it to your Command (SqlCommand or whatever method you are using to execute SQL)... something like: (If you are using SqlClient)
SqlCommand cmd = new SqlCommand(String.Format("Select * from IssueBook Where IssueId IN ({0})", values), your_connection);
Hope it helps.
How about use Convert.ToInt32(); function
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
you can use an array :
http://msdn.microsoft.com/en-us/library/vstudio/wak0wfyt.aspx
and convert values into Integer with
Integer.TryParse
http://www.dotnetperls.com/array-vbnet
Try to use
Integer.Parse()
or
Integer.TryParse()
Hope it works.
You can't convert the string "4,5,6" into a single integer value.
Your best bet is to change the select to accept a varchar value.
In this case to avoid sql injection and as long as your IDs (Cells(1).Text values) are integers you should collect your IDs from cells and type safe them in an integer list, then join them with a comma into a string at the end
I've adjusted your code accordingly.
Protected Sub CheckBox1_CheckedChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Values As List(Of Integer)'your integer list of IDs
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = row.FindControl("checkbox1")
If cb IsNot Nothing AndAlso cb.Checked Then
Values.Add(Integer.convert(row.Cells(1).Text))'add the ID
End If
Next
RwId.Text = String.Join(",", Values)'pull out the list into a comma delimited string eg "2,45,67,87"
Session("SelctdIsuedBokNo") = RwId.Text

compare functionality issue asp.net

I need to compare two string and get both duplicate and original value .
On calling chkDuplicateValue function i need to get both duplicate and original in the return value ?
, acts as delimeter for both the string .
Dim oldStr As String = "test1,test2,test"
Dim newStr As String = "test,test53"
Example out put : Original Value :test1,test2,test,test53 duplicate Value : test
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oldStr As String = "test1,test2,test"
Dim newStr As String = "test,test53"
Dim refinedString As String = chkDuplicateValue(newStr, oldStr)
'On calling this function i need to get both duplicate and original in the return value ?
Response.Write("Original Value" & refinedString(0))
Response.Write("duplicate Value" & refinedString(1))
'Example out put : Original Value :test1,test2,test,test53 duplicate Value : test
End Sub
Function chkDuplicateValue(ByVal newStr As String, ByVal oldStr As String) As String
Dim duplicate As String = ""
End Function
return oldStr.Split(',').Union(newStr.Spit(','));
and if that doesn't work using the Join linq extension method
Use Linq Intersect to return duplicates and Union to return Distinctlist. Pass newStr ByRef, so, that unduplicated string will be returned on newStr. Also, remeber to reference System.Linq
Function chkDuplicateValue(ByRef newStr As String, ByVal oldStr As String) As String
Dim duplicate As String = ""
duplicate = String.Join(",",(newStr.Split(',').Intersect(oldStr.Split(','))).ToArray())
newStr = String.Join(",",(newStr.Split(',').Union(oldStr.Split(','))).ToArray())
return uplicate
End Function

VB.NET - Easiest way to Export / Convert WinForm App to Web ASP.NET App

Background: I have a winform application written in VB.NET that uses a WebService to send out different invitations to users based on the marketing company they select to take different interviews. The winform app is pulling string values from a variety of textboxes, listboxes, and dropdownlists to create some XML and push it to a web service called AcompServiceClient
Questions:
Is there a wizard or 3rd party application that will export winform data to webform asp.net or should I build an aspx page from scratch w/ the same namespaces for all the controls as the winform app?
Which files do I need to transport or setup to make this work besides the AcompServiceClient web service and the code-behind vb? (look at screenshot of the Project Files)
Do i have to copy over any parts of the app.config file and adapt it to the web.config file?
I was thinking:
I can start by copying the Acomp_Invitation_Form.vb to the AComp_Invitation_Web_App.aspx.vb code behind page.
Add existing webservice off the webserver
Manually re-add formatting, text boxes, list boxes, and drop down lists on the front end aspx page using the same names / id's
Here's a screenshot of the WinForm App:
Here's a screenshot of the Project Files:
Here's my code on Acomp_Invitation_Form.vb:
Imports TestClient.aCompService
Imports System.Text
Public Class Form1
Private proxy As New AcompServiceClient
Private Sub stuff()
Dim splitContractingBundle() As String
splitContractingBundle = Split(cb2.SelectedItem, "|")
Dim splitMarketingCompany() As String
splitMarketingCompany = Split(cb3.SelectedItem, "|")
Dim strDate As String = System.DateTime.Now.ToString
Dim strOpData As String = String.Format("{0}~{1}~{2}~{3}~{4}~{5}~{6}~{7}~{8}~{9}~{10}",
Trim(splitMarketingCompany(0)), txtFirstName.Text, "", txtLastName.Text,
txtEmail.Text, txtEmail.Text, "1", strDate,
"Pending", "1/1/1900", Trim(splitContractingBundle(0)))
Dim int1 As Boolean = proxy.AddContractOpportunity(strOpData, "test", "test")
txtEmail.Text = ""
txtFirstName.Text = ""
txtLastName.Text = ""
lbCarriers.Items.Clear()
cb2.Items.Clear()
cb3.Items.Clear()
cb2.SelectedItem = ""
cb3.SelectedText = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'TODO Add code to validate that all selections that are reaquired are met.
'ccemail and the additional message are not required
Dim firstname As String = txtFirstName.Text
Dim lastname As String = txtLastName.Text
Dim ccEmail As String = txtccEmail.Text
Dim sb As New StringBuilder
sb.AppendLine("<?xml version=""1.0"" encoding=""utf-8""?>")
sb.AppendLine("<root>")
sb.AppendLine("<MarketingCompany>")
sb.AppendLine("<MarketingCompanyName>")
''Get Marketing Company Short Name
Dim splitMC As String() = Split(cb3.SelectedItem, "|")
Dim MCShort As String = Trim(splitMC(0))
sb.AppendLine(String.Format("<MCNAme>{0}</MCNAme>", MCShort))
'sb.AppendLine(String.Format("<MCNAme>{0}</MCNAme>", My.Settings.MarketingCompanyShortName))
sb.AppendLine(String.Format("<ccEmail>{0}</ccEmail>", txtccEmail.Text))
sb.AppendLine(String.Format("<emailMessage>{0}</emailMessage>", txtMessage.Text))
sb.AppendLine(String.Format("<MarketerName>{0}</MarketerName>", txtMarketerName.Text))
sb.AppendLine("<agent>")
sb.AppendLine(String.Format("<FirstName>{0}</FirstName>", txtFirstName.Text))
sb.AppendLine(String.Format("<LastName>{0}</LastName>", txtLastName.Text))
sb.AppendLine(String.Format("<Email>{0}</Email>", txtEmail.Text))
sb.AppendLine("<CRMGuid>123456</CRMGuid>")
Dim spltBundles() As String
For Each item In cb2.SelectedItems
If Trim(item) <> "" Then
spltBundles = Split(item, "|")
sb.AppendLine("<ContractingOpportunity>")
sb.AppendLine(String.Format("<Carrier>{0}</Carrier>", Trim(spltBundles(0))))
sb.AppendLine(String.Format("<ContractingOpportunityName>{0}</ContractingOpportunityName>", Trim(spltBundles(1))))
sb.AppendLine("</ContractingOpportunity>")
End If
Next
sb.AppendLine("</agent>")
sb.AppendLine("</MarketingCompanyName>")
sb.AppendLine(" </MarketingCompany>")
sb.AppendLine(" </root>")
Dim xmlStr = sb.ToString
Dim int1 As Boolean = proxy.AddContractOpportunity(xmlStr.ToString, "test", "test")
MsgBox("Made It")
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCarriers()
GetMarketingCompanies()
End Sub
Private Sub GetCarriers()
Try
Dim ac1 As Array
ac1 = proxy.GetCarrierNames("test", "test")
For Each item In ac1
lbCarriers.Items.Add(String.Format("{0} | {1} | {2}", item.CarrierID, item.CarrierNameLong, item.CarrierNameShort))
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub GetMarketingCompanies()
Try
Dim ac1 As Array
ac1 = proxy.GetMarketingCompanyNames("test", "test")
For Each item In ac1
cb3.Items.Add(String.Format("{0} | {1}", item.MarketingCompanyShort, item.MarketingCompanyName))
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub lbCarriers_LostFocus(sender As Object, e As System.EventArgs) Handles lbCarriers.LostFocus
Dim splt() As String
Dim ac1 As Array
cb2.Items.Clear()
For Each item In lbCarriers.SelectedItems
splt = Split(item, "|")
ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
For Each Pitem In ac1
cb2.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
Next
Next
End Sub
End Class
Be very careful of the easy way. While ASP.NET Web Forms might look similar to Windows Forms (controls hooked up to events), the underlying mechanism is very very different. If you have not done so already I recommend you read up on how HTTP works and the life cycle of an ASP.NET page.
Yes, the way you want to do it is the way I have done this many times.
Just copy the methods from your code behind and paste them into the code behind of your asp.net page. Some of your methods are not compatible because they are not supported in asp.net but you will find that our real quick when you build the project.
Create your web page with the controls having exactly the same name as the ones in the winform. When you build, all you have to do is fix your errors and you are on your way.
It looks like you are hooked up to some service so of course you will need to reference that.
Yeah, that's the general idea. I'd pay special attention to any concerns related to using AcompServiceClient in a stateless web environment. It's hard to say whether you have to rethink how you're using that or not without knowing anything about what it is, how it works or how it's consumed.
It doesn't look like you're doing anything else that relies on running in a stateful environment. You're just pulling string values from a variety of textboxes to create some XML and push it to a service. All of that should port over smoothly. You might want to look at adding some client side validation rules, but other than that it looks straight forward.
You'll want to change how you're populating your DropDownList. Those work a little different between win and web forms. It wants to be bound to a datasource in webforms.

SQL select return value to variable

working with: ASP.net using VB.net connecting to MS SQL Server
What I'm trying to do is take the result of a SQL select query and place that in a string variable so it can be used in things like a textbox or label. code so far that doesn't work...
Imports System.Data.SqlClient
Partial Class dev_Default
Inherits System.Web.UI.Page
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
Dim cnPodaci As New SqlConnection
cnPodaci.ConnectionString = "Data Source=<server>;Initial Catalog=<DB>;User ID=<UserName>;Password=<Password>"
cnPodaci.Open()
Dim cm As New SqlCommand
cm.CommandText = "SELECT * FROM tbl1"
cm.Connection = cnPodaci
Dim dr As SqlDataReader
dr = cm.ExecuteReader
TextBox1.Text = dr.GetString(0)
cnPodaci.Close()
End Sub
End Class
Although you have executed the query by calling "ExecuteReader" on the command, what is actually returned is an object (a DataReader) that will allow you to iterate over any query results. To do this you must call the "Read" method on the DataReader (this could be called multiple times in the clause of a "while" loop). Modifying your code to something like this should work:
If dr.Read() Then
TextBox1.Text = dr.GetString(0)
End If
However, bear in mind that this will only work if the first field returned by your query is a string, otherwise a cast exception may be thrown.
If the query is supposed to return a single value, you can simply use the ExecuteScalar method:
TextBox1.Text = DirectCast(cm.ExecuteScalar(), String)
The problem is that SELECT queries will return a dataset, or at least a row from a dataset, not a string.
Do you absolutely need the entire result set as a string? Or can what you're trying to do be achieved by referencing a point in an array or dataset?

Resources