dataset function is used before been assigned a value - asp.net

I am trying to correct some of the warnings a ASP.NET application is throwing. I see many warnings of the type
"Warning 1 Variable 'ListPostFrom' is used before it has been assigned
a value. A null reference exception could result at runtime."
From functions like:
Public Function ListPostFrom(Optional ByVal SortCol As String = "dept", Optional ByVal SortOrder As String = "ASC", _
Optional ByVal ActiveOnly As Boolean = False) As DataSet
Try
Dim objDepartmentDA As New DepartmentDA
'Fill dataset
ListPostFrom = objDepartmentDA.ListPostFrom(SortCol, SortOrder, ActiveOnly)
Catch ex As Exception
'Dataset may be empty
Return ListPostFrom << This is the line with the error
End Try
'Return dataset
Return ListPostFrom
End Function
My question is, what is the best way to correct these type of warnings?
Many thanks for your help.

This way you have a dataset that is Nothing(assigned value) so if it does not fill then it returns Nothing so just check for that before using. Since a function returns something you need to make sure it has a value.
Public Function ListPostFrom(Optional ByVal SortCol As String = "dept", Optional ByVal SortOrder As String = "ASC", _
Optional ByVal ActiveOnly As Boolean = False) As DataSet
Dim result As DataSet = Nothing
Try
Dim objDepartmentDA As New DepartmentDA
'Fill dataset
result = objDepartmentDA.ListPostFrom(SortCol, SortOrder, ActiveOnly)
Catch ex As Exception
'do nothing
End Try
Return result 'may be nothing
End Function
Usage:
Dim ds = ListPostFrom()
If Not ds Is Nothing Then
'use ds in here
End If

Related

vb.net How do to display DB values on a listbox?

I'm trying to do display multiple rows with two column values on a list box so when a user selects an option they have a little extra information.
It should look like this:
ej. 3 BestBuy
I use the same method to output data to my GridViews but it doesn't display anything on the listbox. What is the correct method to output data from a db to a listbox.
SQL Control Class Functions
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
How im trying to add data to the listbox
Protected Sub DivisionListBox_DataBinding(sender As Object, e As EventArgs) Handles DivisionListBox.DataBinding
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, GROUP_DESC
FROM Store_Group_Desc ")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
DivisionListBox.DataSource = dt
DivisionListBox.DataBind()
End Sub
What I would do is return the STR_GRP_ID as well as create an aliased column that concatenated the STR_GRP_ID and GROUP_DESC fields.
Then you would bind the DataTable to the ListBox like you're doing but specifying that the ListBox's DisplayMember is your aliased column and the ValueMember is the id:
Try
dt = SQL.ExecQuery("Select STR_GRP_ID, CONCAT_WS(' ', STR_GRP_ID, GROUP_DESC GROUP_DESC) AS DisplayText FROM Store_Group_Desc;")
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
With DivisionListBox
.DataSource = dt
.DisplayMember = "DisplayText"
.ValueMember = "STR_GRP_ID"
End With
I don't think the DataBinding event will ever be triggered in you code. You can set a break point inside the event and see if it is ever triggered.
I chose to use the Page.Load event to fill the list box. I separated the user interface code that actually fills the list box from the data access code.
I had the server do the work to build the string your want to display. I assumed the id field was some type of number field so I cast it to a varchar. Then added a space and the description field. This new select field is called IDDesc.
IDDesc is the field name that I want to display in the list box.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillListBox()
End If
End Sub
Private Sub FillListBox()
Dim ListBoxData = GetListBoxData()
ListBox1.DataTextField = "IDDesc"
ListBox1.DataSource = ListBoxData
ListBox1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim DBDT = New DataTable
Dim Query = "Select Cast(STR_GRP_ID As varchar) + ' ' + GROUP_DESC As IDDesc
FROM Store_Group_Desc "
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(Query, DBCon)
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function

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.

Adding a ReplyTo within a function for Sendgrid

I have a working function for using sendgrid web api. The function worked without any issue but now i would like to add in the ability to have a "ReplyTo" email address. The working code is as follows:
Private Function CreateMailMessage(ByVal fromAddr As String, fromName As String, ByVal toAddr As String, ByVal ccAddr As String, ByVal bccAddr As String, ByVal subject As String, ByVal contents As String) As SendGrid.IMail
Dim returnVar As SendGrid.IMail = SendGrid.Mail.GetInstance
returnVar.From = New System.Net.Mail.MailAddress(fromAddr, fromName)
returnVar.Subject = subject
If contents.Contains("<html") Then
returnVar.Html = contents
Else
returnVar.Text = contents
End If
For Each aStr As String In toAddr.Split(CChar(";"))
returnVar.AddTo(aStr)
Next
If Not (String.IsNullOrWhiteSpace(ccAddr)) Then
For Each aStr As String In ccAddr.Split(CChar(";"))
'Sendgrid doesnt support CC via the webapi so we need to use Bcc
returnVar.AddBcc(aStr)
Next
End If
If Not (String.IsNullOrWhiteSpace(bccAddr)) Then
For Each aStr As String In bccAddr.Split(CChar(";"))
returnVar.AddBcc(aStr)
Next
End If
Return returnVar
End Function
and when adding the in the ReplyTo i tried the following:
Private Function CreateMailMessage(ByVal replytoAddr As String, ByVal fromAddr As String, fromName As String, ByVal toAddr As String, ByVal ccAddr As String, ByVal bccAddr As String, ByVal subject As String, ByVal contents As String) As SendGrid.IMail
Dim returnVar As SendGrid.IMail = SendGrid.Mail.GetInstance
If Not (String.IsNullOrWhiteSpace(replytoAddr)) Then
returnVar.ReplyToList.Add(New System.Net.Mail.MailAddress(replytoAddr))
End If
returnVar.From = New System.Net.Mail.MailAddress(fromAddr, fromName)
returnVar.Subject = subject
If contents.Contains("<html") Then
returnVar.Html = contents
Else
returnVar.Text = contents
End If
For Each aStr As String In toAddr.Split(CChar(";"))
returnVar.AddTo(aStr)
Next
If Not (String.IsNullOrWhiteSpace(ccAddr)) Then
For Each aStr As String In ccAddr.Split(CChar(";"))
'Sendgrid doesnt support CC via the webapi so we need to use Bcc
returnVar.AddBcc(aStr)
Next
End If
If Not (String.IsNullOrWhiteSpace(bccAddr)) Then
For Each aStr As String In bccAddr.Split(CChar(";"))
returnVar.AddBcc(aStr)
Next
End If
Return returnVar
End Function
it would seem Replytolist is not part of sendgrid? Anyone seen this?
I maintain the SendGrid library. Sorry, this is a known issue that I haven't gotten around to fixing yet. In the meantime you can use the obsolete ReplyTo.

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.

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

Resources