Calling Methods dynamically - asp.net

I am trying to call methods dynamically and I have issues. Could some one please help
I have the following vb code
Module
Sub Main
if user-input = RP1 then
createRP1()
elseif user-input = RP2 then
createRP2()
end if
end sub
sub createRP1()
...
end sub
sub createRP2()
,...
end sub
End Module
The CreateRP1/CreateRP2 method does not have any arguments. There are some n number of reports. So I do not want to write all those if or switch conditions for this. I want to write some thing simple so I tried this
1 Dim type As Type = "["GetType"]"()
2 Dim method As MethodInfo = type.GetMethod("Create" + user-input)
3 If method IsNot Nothing Then
4 method.Invoke(Me, Nothing)
5 End If
Line 1 and 4 are not working
Line 4 is not working because "me" does not go with module. But how to rewrite 1? I saw this somewhere in StackOverflow site

You can get the Type of the current Module like this:
Dim myType As Type = MethodBase.GetCurrentMethod().DeclaringType
Since it's a Module, all of the methods are essentially Shared (e.g. static, non-instance methods), so you can just pass Nothing for the obj parameter of the MethodInfo.Invoke method:
Dim methodName As String = "Create" & userInput
Dim method As MethodInfo = myType.GetMethod(methodName)
method.Invoke(Nothing, Nothing)
However, rather than using reflection, you may also want to consider using a dictionary of delegates so that it would be more deterministic and type-checked at compile time. For instance:
Dim methods As New Dictionary(Of String, Action)
methods.Add("RP1", AddressOf CreateRP1)
methods.Add("RP2", AddressOf CreateRP1)
' ...
methods(userInput).Invoke()

I think the best solution would be to create a "Report" object through designing a class. Then you could easily make things on the fly.
function (byRef user-input As String) As Report
if not "s" & user-input = "s"
Dim user-report As Report = new Report(user-input)
end if
end function
Then your Report class
Private reportNumber As String
Private data As String
Public Sub New(byVal reportNumber As String)
Sub createRP(byRef repotNumber As String)
// use report # here to select the correct data...
// so if it was sql....
// "SELECT data FROM report_table where report_num =" & reportNumber
end Sub
end Sub

Related

Parallel one Optional AND one ParamArray in a sub

I'm not so professional in asp .net vs2012 vb, and now I've a problem:
This is the declaration of the sub:
Public Sub DocFill(ByVal DocName As String, ByVal Optional OK As Boolean=False, ByVal ParamArray BmValues() As String)
And the error message is:
Error 7 'BmValues' is not declared. It may be inaccessible due to its protection level.
I tried change the order, but the last value always drop this error
Is possible to declare soehow parallely this two params or not?
Thanks for the help!
A possible solution is to cook up something like this:
Public Sub DocFill(ByVal DocName As String, ByVal ParamArray BmValues() As Object) ' Declare BmValues as an array of Object.
Dim OK As Boolean = False ' Declare the OK Boolean within the method.
If BmValues.Length > 0 Then ' Check whether BmValues contains anything.
If BmValues(0).GetType() is GetType(Boolean) Then ' Check whether BmValues' first value is a Boolean.
OK = CBool(BmValues(0)) ' If so, set OK to the first value in BmValues.
End If
...
End If
...
End Sub

How can I pass a variable value from one sub to another

I am new to the programming world. I have got the chance to work and develop in a project built with vb.net and asp.net.
In my coding I have stored a value in a variable under one sub btn_Click(). I want to use that variable value from another sub - AddCategory(). Both are written under same class.
Protected Sub btn_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim sale = Guid.NewGuid().ToString()
Dim SaleID As String = sale
Core.DB.Insert("insert into survey(id,title, detail) values(#id,#title, #detail);", Core.DB.SIP("title", Title), Core.DB.SIP("detail", Detail), Core.DB.SIP("id", sale))
Call AddCategory1()
Response.Redirect("profile.aspx")
End
As you can see in the above code the ID value for sale table is a GUID value and I am converting into a string to store it one variable SaleID.
And you can also see I have called AddCategory1(). Now I want to pass the value of SaleID (string) into AddCategory(). And I want to do another insert query to category table under AddCategory()
Private Sub AddQuestionCategory1()
Core.DB.Insert("insert into SaleCategory(title, detail, saleid) values(#title, #detail, #sid)", Core.DB.SIP("title", CategoryTitle), Core.DB.SIP("detail", CategoryDetail), Core.DB.SIP("sid", sale))
End Sub
To be able to do so I have to pass the value stored under the variable SaleID.
How can I do that?
The usual way to pass a value to a method (Sub or Function) is to make it an argument. Set up the method to expect the SaleID as an argument and then call the method with that argument.
Private Sub AddCategory1(SaleID as String)
'You can use SaleID in your code
End Sub
Call this sub from your Click handler like this
AddCategory1(SaleID)

Decoding Encrypted Query string

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.

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