compare 2 string to get result different - asp.net

i am doing a method that able to return me what is the different between data before and data after
Dim dataBefore As String = "Name:Alice,Age:30,Sex:Male"
Dim dataAfter As String = "Name:Alice,Age:20,Sex:Female"
mtdCompare2String(dataBefore,dataAfter)
Public Shared Function mtdCompare2String(ByVal sBefore As String, ByVal sAfter As String) As String
//what i try to do before, supposing my loop should start over here but i failed,
//so i just removed the loop, i need someone to correct me =(
Dim intBefore As Integer = sBefore.IndexOf(",")
Dim intAfter As Integer = sAfter.IndexOf(",")
Dim sBefore As String = sBefore.SubString(0,intBefore)
Dim sAfter As String = sAfter.SubString(sAfter.IndexOf(":"),intAfter)
Dim sb As StringBuilder
sb.append(sBefore,sAfter)
return sb.toString
End Function
Expected Result
Age:30>20,Sex:Male>Female

Something like this should work:
Public Shared Function mtdCompare2String(ByVal sBefore As String, ByVal sAfter As String) As String
'what i try to do before, supposing my loop should start over here but i failed,
'so i just removed the loop, i need someone to correct me =(
Dim Before() As String = sBefore.Split(",")
Dim After() As String = sAfter.Split(",")
Dim ReturnString As String = ""
For I = 0 To Before.Length - 1
Dim TempBefore As String = Before(I).Split(":")(1)
Dim TempAfter As String = After(I).Split(":")(1)
If TempBefore <> TempAfter Then
ReturnString += Before(I).Split(":")(0) + ":" + TempBefore + ">" + TempAfter + ","
End If
Next
Return ReturnString.Substring(0, ReturnString.Length - 1)
End Function

Related

Binding Url to Gridview

I want to bind the url to GridView but I don't know how.
For example when I type the http://localhost:12345/example.aspx?FirstName=John in the url it will give me the result in GridView that shows only with the FirstName "John".
Here's my curent code:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim dt As New DataTable
' Stablish ODBC Connection
Dim con As New OdbcConnection("DRIVER={SQL Server};Server=WJNJPHR8TCX8P\SQLEXPRESS;Database=Fabrics;Integrated Security=True;")
' Query Command
Dim cmd As New OdbcCommand("SELECT * FROM [Client] WHERE [FirstName] = ?", con)
con.Open()
' Gets the path (Example.aspx)
Dim path As String = HttpContext.Current.Request.Url.AbsolutePath
' Gets the host (localhost)
Dim host As String = HttpContext.Current.Request.Url.Host
' Gets the whole url (localhost:24124/Example.aspx)
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
' Parse the query string variables into a NameValueCollection
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(url)
' Iterate through the collection and shows the result in MsgBox
Dim sb As New StringBuilder()
For Each s As String In qscoll.AllKeys
sb.Append(s & " = " & qscoll(s) & vbCrLf)
Next s
MsgBox(sb.ToString)
' Gets all keys and values in query string and shows it on MsgBox
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
Next key
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter
par1.OdbcType = OdbcType.NVarChar
par1.Value = FName
par1.ParameterName = "#FirtName"
cmd.Parameters.Add(par1)
'Shows the result in Data Grid
dt.Load(cmd.ExecuteReader()) '==> Error: Invalid use of default parameter
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Any help will do!
You can access your query string directly with
Dim firstName as string = Request.QueryString("firstName")
Then you must pass it as a parameter of the query before executing it
Dim par1 As New OdbcParameter
par1.DbType = DbType.String
par1.Value = firstName
par1.ParameterName = "#FirstName"
cmd.Parameters(1) = par1
Hope it helps
Answered my question!
Here's my code:
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter With {
.OdbcType = OdbcType.NVarChar,
.Value = FName,
.ParameterName = "#FirstName"
}
cmd.Parameters.Add(par1)
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView1.DataBind()
Next key
#isol Thanks for your help! :)

How to call function from class

I am trying to load a function value into a Literal2.Text.
I am getting the error
ErrorArgument not specified for parameter 'LoadMenu' of 'Public
Function LoadMenuActivity(LoadMenu As String) As String'
I call the function on page load like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Literal2.Text = AllFunc.LoadMenuActivity
End If
End Sub
Here is my Class:
Public Class AllFunc
Public Function LoadMenuActivity(ByVal LoadMenu As String) As String
Dim strCON As String = "Data Source=localhost;Initial Catalog=TAPVendor;Integrated Security=True"
Dim strSQL = "SELECT * FROM dbo.tbl_Message WHERE UserID = 'RAN' ORDER BY ID DESC"
Dim da As New SqlClient.SqlDataAdapter(strSQL, strCON)
Dim dt As New DataTable
da.Fill(dt)
Dim display As String = Nothing
Dim sb As StringBuilder = New StringBuilder()
Dim counter As Integer = Nothing
For i As Integer = 0 To dt.Rows.Count - 1
counter = counter + 1
Dim MyString As String
MyString = dt.Rows(i).Item("Timestamp")
Dim MyDateTime As DateTime
MyDateTime = New DateTime
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm:ss tt", Nothing)
Dim t As TimeSpan = DateTime.Now - MyDateTime
If t.TotalSeconds > 1 Then
display = t.Seconds.ToString() + " sec ago"
End If
If t.TotalSeconds > 60 Then
display = t.Minutes.ToString() + " mins ago"
End If
If t.TotalHours > 1 Then
display = t.Hours.ToString() + " hrs ago"
End If
If t.TotalDays > 1 Then
display = t.Days.ToString() + " days ago"
End If
sb.AppendFormat("<li class=""divider""></li>" &
" <li><a href=""#"">" &
"<div>" &
"<i class=""" & dt.Rows(i).Item("Icon") & """></i> " & dt.Rows(i).Item("Alert") & "" &
"<span class=""pull-right text-muted small"">" & display & "</span></div></a></li>")
If counter = 5 Then
Exit For
End If
Next
Return LoadMenu
End Function
End Class
What am I doing wrong?
Like the error message says, you didn't specify an argument when calling LoadMenuActivity. You have to call LoadMenuActivity("Some string").
The argument inside the () is requiring a string to be passed to it. Plus that function needs to be a Shared function to call it that way.
Literal2.Text = AllFunc.LoadMenuActivity("some string here")

Initiating an Dynamic Multidimensional Array in VB.net

I am receiving a "Object reference not set to an instance of an object." Error when trying to populate the fileDetails array. I am new to vb.net and I am lost.
Public Sub FindAllOrphanFiles(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim files As String
Dim iCount As Integer = 0
Dim fileDetails As String(,)
For Each files In fileEntries
Dim fileIcon As String
Dim thisFile As New IO.FileInfo(files)
Dim fileName As String = thisFile.Name
Dim fileSize As String = thisFile.Length
Dim fileDateModified As String = thisFile.LastWriteTime
Dim fileExtension As String = Path.GetExtension(fileName)
Dim fileShortPath As String = Replace(Replace(files, uploadFolderPath, ""), fileName, "")
Dim fileFullPath As String = files
If fileExtension = ".pdf" Then
fileIcon = "acrobat"
Else
fileIcon = "paint"
End If
' Write to Array
fileDetails(iCount, 0) = fileIcon
fileDetails(iCount, 1) = fileName
fileDetails(iCount, 2) = fileShortPath
fileDetails(iCount, 3) = fileDateModified
fileDetails(iCount, 4) = fileSize
fileDetails(iCount, 5) = fileFullPath
iCount += 1
Next files
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
FindAllOrphanFiles(subdirectory)
Next subdirectory
End Sub 'FindAllOrphanFiles
Any help would be greatly appreciated.
Your array is not initialized. If you know the size at some point before your loop, you should initialize it using REDIM:
Dim fileDetails As String(,)
redim fileDetails(fileEntries.Count -1,5)
For Each files In fileEntries
....
If you don't know it ahead of time, use Redim Preserve inside you loop:
Dim fileDetails As String(,)
Dim I as int32 = -1
For Each files In fileEntries
I += 1
redim preserve fileDetails(i,5)
....

convert existing code to asynchronous workings

I have existing code in VB in which I need to process all records that are in the list in one go, and await for their responses. When they respond, add them to the data table. The code works. I just need to convert it to run asynchronously.
Here is my code:
Imports System.Net
Imports System.IO
Public Class Form1
Dim _Datatable As New DataTable
Private Sub btnProcess_Click(sender As System.Object, e As System.EventArgs) Handles btnProcess.Click
prgProgress.Value = 0
prgProgress.Maximum = lstUrls.Items.Count
For Each _ProductEntry As String In lstUrls.Items
Try
Dim _Webclient As New WebClient
'_Webclient.Proxy = _ProxyClient
Dim _DataStream As Stream = _Webclient.OpenRead(New Uri(_ProductEntry))
Dim _DataRead As New StreamReader(_DataStream)
Dim _HtmlContent As String = _DataRead.ReadToEnd
Dim _HtmlDocument As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
_HtmlDocument.write(_HtmlContent)
Dim _ProductName As mshtml.IHTMLHeaderElement = _HtmlDocument.getElementById("product-header")
_DataStream.Close()
_DataRead.Close()
Call CheckTable("Name")
Call CheckTable("URL")
Call CheckTable("Image")
Call CheckTable("Price")
Dim _Price As String = String.Empty
Dim _SpanElements As mshtml.IHTMLElementCollection = _HtmlDocument.getElementsByTagName("span")
For Each _SpanElement As mshtml.IHTMLSpanElement In _SpanElements
If _SpanElement.classname = "regular-price" Then
_Price = Replace(Replace(_SpanElement.innertext, "£", ""), "Incl. VAT", "")
End If
Next
Dim _ImageLocation As String = String.Empty
For Each _Paragraph As mshtml.IHTMLElement In _HtmlDocument.getElementsByTagName("image")
If _Paragraph.id = "product-image-main" Then
Dim _Image As mshtml.IHTMLImgElement = CType(_Paragraph, mshtml.IHTMLImgElement)
_ImageLocation = _Image.src
Exit For
End If
Next
Dim tableElements As mshtml.IHTMLElementCollection
tableElements = _HtmlDocument.getElementsByTagName("Table")
Dim oTableTest As mshtml.IHTMLTable2 = tableElements.item(1)
'BUILD HEADERS
For Each _ColumnHeader As mshtml.IHTMLTableRow In oTableTest.rows
CheckTable(CType(_ColumnHeader.cells(0), mshtml.IHTMLElement).innerText)
Next
Dim _DataRow As DataRow = _DataTable.NewRow
_DataRow.Item("Name") = CType(_ProductName, mshtml.IHTMLElement).innerText
_DataRow.Item("URL") = _ProductEntry
_DataRow.Item("Price") = _Price
_DataRow.Item("Image") = _ImageLocation
For Each _RowData As mshtml.IHTMLTableRow In oTableTest.rows
Dim _Header As mshtml.IHTMLElement = _RowData.cells(0)
Dim _Value As mshtml.IHTMLElement = _RowData.cells(1)
_DataRow.Item(_Header.innerText) = _Value.innerText
Next
Dim _Elements As mshtml.IHTMLElementCollection = _HtmlDocument.all
For Each _Element As mshtml.IHTMLElement In _Elements
If _Element.className = "product-description product-documents" Then
For Each _ProductLink As mshtml.IHTMLElement In _Element.all
If _ProductLink.tagName = "A" Then
CheckTable(_ProductLink.innerText)
_DataRow(_ProductLink.innerText) = Replace(CType(_ProductLink, mshtml.IHTMLAnchorElement).href, "about:", "http://www.tapoutlet.co.uk")
End If
Next
End If
Next
_DataTable.Rows.Add(_DataRow)
_DataTable.AcceptChanges()
dgvScrapedData.DataSource = _Datatable
dgvScrapedData.Refresh()
Catch ex As Exception
Console.WriteLine("Error getting webpage-" & _ProductEntry)
Console.WriteLine(ex.Message.ToString)
End Try
Next
End Sub
Private Function CheckTable(ByVal ColumnName As String) As Boolean
If _DataTable.Columns.Contains(ColumnName) Then
Return True
Else
_DataTable.Columns.Add(ColumnName)
Return False
End If
End Function
End Class

Find a string and replace it more effeciently

Situation: I have a html file and I need to remove certain sections.
For Example: The file contains html: <div style="padding:10px;">First Name:</div><div style="padding:10px; background-color: gray">random information here</div><div style="padding:10px;">First Name:</div><div style="padding:10px; background-color: gray">random information here</div>
I need to remove all text that starts with "<div style="padding:10px; background-color: gray">" and ends with "</div>" so that the result would be:
<div style="padding:10px;">First Name:</div><div style="padding:10px;">First Name:</div>
I created 2 functions that do this, but I do not this it efficient at all. I have a 40mb file and it takes the program about 2 hours to complete. Is there a more efficient way to do this? Is there a way to use regex?
See my code below:
Public Shared Function String_RemoveText(ByVal startAt As String, ByVal endAt As String, ByVal SourceString As String) As String
Dim TotalCount As Integer = String_CountCharacters(SourceString, startAt)
Dim CurrentCount As Integer = 0
RemoveNextString:
Dim LeftRemoved As String = Mid(SourceString, InStr(SourceString, startAt) + 1, Len(SourceString) - Len(endAt))
Dim RemoveCore As String = Left(LeftRemoved, InStr(LeftRemoved, endAt) - 1)
Dim RemoveString As String = startAt & RemoveCore & endAt
Do
' Application.DoEvents()
SourceString = Replace(SourceString, RemoveString, "")
If InStr(SourceString, startAt) < 1 Then Exit Do
GoTo RemoveNextString
Loop
Return Replace(SourceString, RemoveString, "")
End Function
Public Shared Sub Files_ReplaceText(ByVal DirectoryPath As String, ByVal SourceFile As String, ByVal DestinationFile As String, ByVal sFind As String, ByVal sReplace As String, ByVal TrimContents As Boolean, ByVal RemoveCharacters As Boolean, ByVal rStart As String, ByVal rEnd As String)
'CREATE NEW FILENAME
Dim DateFileName As String = Date.Now.ToString.Replace(":", "_")
DateFileName = DateFileName.Replace(" ", "_")
DateFileName = DateFileName.Replace("/", "_")
Dim FileExtension As String = ".txt"
Dim NewFileName As String = DirectoryPath & DateFileName & FileExtension
'CHECK IF FILENAME ALREADY EXISTS
Dim counter As Integer = 0
If IO.File.Exists(NewFileName) = True Then
'CREATE NEW FILE NAME
Do
'Application.DoEvents()
counter = counter + 1
If IO.File.Exists(DirectoryPath & DateFileName & "_" & counter & FileExtension) = False Then
NewFileName = DirectoryPath & DateFileName & "_" & counter & FileExtension
Exit Do
End If
Loop
End If
'END NEW FILENAME
'READ SOURCE FILE
Dim sr As New StreamReader(DirectoryPath & SourceFile)
Dim content As String = sr.ReadToEnd()
sr.Close()
'WRITE NEW FILE
Dim sw As New StreamWriter(NewFileName)
'REPLACE VALUES
content = content.Replace(sFind, sReplace)
'REMOVE STRINGS
If RemoveCharacters = True Then content = String_RemoveText(rStart, rEnd, content)
'TRIM
If TrimContents = True Then content = Regex.Replace(content, "[\t]", "")
'WRITE FILE
sw.Write(content)
'CLOSE FILE
sw.Close()
End Sub
Example to execute the code (also removes Chr(13) & Chr(10):
Files_ReplaceText(tPath.Text, tSource.Text, "", Chr(13) & Chr(10), "", True, True, tStart.Text, tEnd.Text)
Do not use a RegEx to parse HTML - it is not a regular language. See here for some compelling demonstrations.
Use the HTML Agility Pack to parse the HTML and replace data.

Resources