compare functionality issue asp.net - 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

Related

dataset function is used before been assigned a value

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

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.

How to use ASP.NET replace command to insert variables?

<asp:TextBox ID="TESTBOX" runat="server">SOME TEXT Query=0 MORE TEXT</asp:TextBox>
Protected Sub btnReplace_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim QueryID As String
QueryID = Request.QueryString("Query")
Dim MyText As String = Me.TESTBOX.Text
Dim MyTextNew = MyText.Replace("Query=0", "Query=" & QueryID)
TESTBOX.Text = MyTextNew
End Sub
QUESTION
How do you replace text with a variable in ASP.NET VB?
"Replacing text with a variable" works.
Try this:
Dim myVar As Integer = 12
Dim MyTextNew = MyText.Replace("Query=0", "Query=" & myVar)
and it should work.
The problem in your code is that your request for the QueryString doesn't return a value. Check it with the stack trace or msgbox() and notice that it is null.

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

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.

Resources