Replace exact word - vb.net

I want to convert this string:
"http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"
to this:
"http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}"
But I am getting output like this:
"http://www.example.com/sms.aspx?user={0}&pass={0}123&mbno={2}&msg={3}".
I have used the following line of code for replacing:
Dim SMSUrlStr As String="http://www.example.com/sms.aspxuser=joey&pass=joey123&mbno=9792234567&msg=Test"
e.g. Regex.Replace(SMSUrlStr, joey, {0})
but it is also replacing "joey" from "joey123".
How can I make the replacement more specific?

Instead of looking at the input as a string, you could regard it as a URI. There are methods in the framework to work with URIs, and from that we can rebuild it into the form you need:
Imports System.Collections.Specialized
Imports System.Text
Imports System.Web
Module Module1
Sub Main()
Dim s = "http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"
Dim u = New Uri(s)
Dim q = HttpUtility.ParseQueryString(u.Query)
Dim newQ = q.AllKeys.Select(Function(p, i) p & "={" & i & "}")
Dim newS = u.GetLeftPart(UriPartial.Path) & "?" & String.Join("&", newQ)
Console.WriteLine(newS)
Console.ReadLine()
End Sub
End Module
Outputs:
http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}

Related

How to divide a string by another string using Split in VB.Net? [duplicate]

This question already has an answer here:
VB.NET String.Split method?
(1 answer)
Closed 3 years ago.
I am trying to divide a string similar to this:
"<span>1</span> - Selection"
And get the value that is enclosed between the <span>.
In JavaScript I do this:
var example= "<span>1</span> - selection";
var separation= example.replace("</span>","<span>").split("<span>");
console.log("Split: ",separation);
//The result is ["","1"," - Selección"]
console.log("Value that I want: ",separation[1]); //I get the value that I need
And that's it that I need to do but in Visual .NET, but it doesn't work for me.
I try:
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
or sending all the </span> replaced in the string to just do:
Dim WordString As String = "<span>1<span> - Selection"
Dim idSelection As String() = WordString.Split("<span>")
But in the position (1) I always get "span>1", and I can't do the split like in JS
How can I do it correctly?
To simulate the code VB.Net use https://dotnetfiddle.net/
The code:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
Console.WriteLine(idSelection(1))
End Sub
End Module
You have to use Split(String[], StringSplitOptions) to split using a string. So you can use the following solution:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split({"<span>"}, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine(idSelection(0))
End Sub
End Module
demo on dotnetfiddle.net
You can also use a solution using a regular expression with a positiv lookahead and lookbehind:
Imports System
Imports System.Text.RegularExpressions
Public Module Module1
Public Sub Main()
Dim rgx As New Regex("(?<=<span>)(.+)(?=</span>)")
Dim WordString As String = "<span>1</span> - Selection"
If rgx.IsMatch(WordString) Then
Console.WriteLine(rgx.Matches(WordString)(0))
End If
End Sub
End Module
demo on dotnetfiddle.net

VB.NET/ import namespaces from codeDOM compiler

I encounter an error while compiling a project containing the import of a namespace.
I have a file called "Dissimulation.vb" in which the namespace "Dissimulation2" is declared. Here is his code:
Option Strict Off
Option Explicit Off
Imports System.IO
Imports System.Security.Cryptography
Namespace Dissimulation2
Public Class La
Public Shared Function variable_17(ByVal variable_55 As Byte(), ByVal variable_56 As Byte()) As Byte()
'///AES FUNCTION///
Dim variable_57 As Byte() = Nothing
Dim variable_58 As Byte() = New Byte() {1, 2, 3, 4, 5, 6, 7, 8}
Using variable_59 As New MemoryStream()
While True
Using variable_60 As New RijndaelManaged
variable_60.KeySize = 256
variable_60.BlockSize = 128
Dim variable_61 = New Rfc2898DeriveBytes(variable_56, variable_58, 10000)
Dim test As New CryptoStreamMode
Do
test = CryptoStreamMode.Write
variable_60.Key = variable_61.GetBytes(variable_60.KeySize / 8)
variable_60.IV = variable_61.GetBytes(variable_60.BlockSize / 8)
variable_60.Mode = CipherMode.CBC
Using variable_62 = New CryptoStream(variable_59, variable_60.CreateDecryptor(), test)
variable_62.Write(variable_55, 0, variable_55.Length)
variable_62.Close()
variable_57 = variable_59.ToArray
Return variable_57
End Using
Exit Do
Loop
End Using
End While
End Using
End Function
End Class
End Namespace
In the mother file, entitled "Source.vb" I would like to call this function. To do this, I simply take it like this:
Dissimulation2.La.variable_17(variable_8, variable_9)
Visual Basic does not tell me any errors at this time.
Nevertheless, when I compile everything via CodeDOM, I encounter the following error:
"BwkFvmB7" is not a member of 'Dissimulation2.La'.
Here are the parameters of CodeDOM:
Imports System.Text
Imports System.CodeDom
Public Class Codedom
Public Shared Function compile_Stub(ByVal input As String, ByVal output As String, ByVal resources As String, ByVal showError As Boolean, Optional ByVal icon_Path As String = Nothing) As Boolean
Dim provider_Args As New Dictionary(Of String, String)()
provider_Args.Add("CompilerVersion", "v2.0")
Dim provider As New Microsoft.VisualBasic.VBCodeProvider(provider_Args)
Dim c_Param As New Compiler.CompilerParameters
Dim c_Args As String = " /target:winexe /platform:x86 /optimize "
If Not icon_Path = Nothing Then
c_Args = c_Args & "/win32icon:" & icon_Path
End If
c_Param.GenerateExecutable = True
c_Param.ReferencedAssemblies.Add("System.Drawing.Dll")
c_Param.ReferencedAssemblies.Add("System.Windows.Forms.Dll")
c_Param.GenerateInMemory = True
c_Param.OutputAssembly = output
c_Param.EmbeddedResources.Add(resources)
c_Param.CompilerOptions = c_Args
c_Param.IncludeDebugInformation = False
Dim c_Result As Compiler.CompilerResults = provider.CompileAssemblyFromSource(c_Param, input)
If c_Result.Errors.Count = 0 Then
Return True
Else
If showError Then
For Each _Error As Compiler.CompilerError In c_Result.Errors
MessageBox.Show("ERREUR de compilation" & vbNewLine &
"FileName: " & _Error.FileName & vbNewLine &
"Line: " & _Error.Line & vbNewLine & "ErrorText: " &
_Error.ErrorText & vbNewLine &
"Column: " &
_Error.Column & vbNewLine &
"Error Type: " &
_Error.IsWarning & vbNewLine & "ErrorNumber: " &
_Error.ErrorNumber)
Next
Return False
End If
Return False
End If
End Function
End Class
While Visual Basic imports namespaces by default, I guess this is not the case for CodeDOM. So, I guess that error appears. However, I do not know how to import it manually: I can not find any document about it in VB.NET.
Can you point me to the right path?
I have found this question but i do not understand because the code is not codded in VB.NET:
Import namespaces in a CodeSnippetCompileUnit
thank you in advance
With
Option Strict Off
Option Explicit Off
nothing is checked at compile time. Put both on and then I assume you get the error in Visual Studio, too.
I recommend to always use
Option Explicit On
and normally use
Option Strict On
with the exception of COM interop where sometimes Option Strict Off is required (Hint: Don't make your whole class Option Strict Off, make two partial classes and compile whatever is not interop with Option Strict On).

VB.net add a header/footer to every page of a PDF using iText7

I am trying to create a PDF with a header and footer. Both header and foot are images. Since my pdf creates a random amount of pages I need to automaticly add it to every page. I know I need to use some sort of eventhandler. Unfortunately I can't find any examples in the vb.net language, I only can find java/C# examples and I am really bad at reading/converting these language to vb.net. I am not a expert yet at programming.
Can anyone point me in the right direction.
Edit4: Removed random stuff no longer need to answer my question.
This piece of code below is all I got on creating the PDF itself.
Imports System.IO
Imports MySql.Data.MySqlClient
Imports iText.Kernel
Imports iText.Kernel.Pdf
Imports iText.Kernel.Font
Imports iText.Kernel.Font.PdfFont
Imports iText.Kernel.Font.PdfFontFactory
Imports iText.IO.Image
Imports iText.IO.Image.ImageData
Imports iText.IO.Image.ImageDataFactory
Imports iText.Layout.Element.Image
Imports iText.Layout
Imports iText.Layout.Element
Imports iText.Layout.Element.Table
Imports iText.Kernel.Events.Event
Imports iText.Kernel.Events.PdfDocumentEvent
Imports iText.Kernel.Geom.PageSize
Imports iText.Kernel.Geom.Rectangle
Imports iText.Kernel.Pdf.PdfDocument
Imports iText.Kernel.Pdf.PdfNumber
Imports iText.Kernel.Pdf.PdfWriter
Imports iText.Kernel.Pdf.Canvas.PdfCanvas
Imports iText.Kernel.Pdf.Canvas.PdfCanvasConstants
Imports iText.Kernel.Pdf.Xobject.PdfFormXObject
Imports iText.Layout.Canvas
Imports iText.Layout.Document
Imports iText.Layout.Style
Imports iText.Layout.Layout.LayoutArea
Imports iText.Layout.Layout.LayoutContext
Imports iText.Layout.Layout.LayoutResult
Imports iText.Layout.Renderer.CellRenderer
Imports iText.Layout.Renderer.DrawContext
Imports iText.Layout.Renderer.TableRenderer
Imports iText.Signatures.PdfSignatureAppearance
Public Sub NewiText7PdfCreation()
'Dim dest As String = "\\test\verkoop\offerte v2\Offerte " & offertenummer2 & "-" & offertenummer & " " & TextBox2.Text & ".pdf"
Dim dest As String = "iText7Test.pdf"
Dim writer As PdfWriter = New PdfWriter(dest)
Dim pdf As PdfDocument = New PdfDocument(writer)
Dim doc As Document = New Document(pdf)
Dim font As PdfFont = PdfFontFactory.CreateFont("C:\Windows\Fonts\calibri.ttf")
'header
Dim headerlocation As String = "Resources\Offerte-NL.png"
Dim headerimage2 As Image = New Image(ImageDataFactory.Create(headerlocation))
doc.Add(headerimage2)
'klant gegevens
doc.Add(New Paragraph("Debiteur gegevens").SetFont(font))
Dim debnr As String = TextBox1.Text
Dim bn As String = TextBox2.Text
Dim adr As String = TextBox3.Text
Dim pcwp As String = TextBox4.Text
Dim cp As String = TextBox5.Text
Dim km As String = TextBox6.Text
Dim klanttable As New Table(2)
klanttable.SetMaxWidth(350)
klanttable.SetHorizontalAlignment(0)
klanttable.SetFont(font)
klanttable.SetFontSize(8)
klanttable.SetWidth(350)
klanttable.SetMinWidth(120)
klanttable.AddCell("Debiteur nr.: ")
klanttable.AddCell(debnr)
klanttable.AddCell("(Bedrijfs)naam:")
klanttable.AddCell(bn)
klanttable.AddCell("Adres:")
klanttable.AddCell(adr)
klanttable.AddCell("Postcode & woonplaats:")
klanttable.AddCell(pcwp)
klanttable.AddCell("Contactpersoon:")
klanttable.AddCell(cp)
klanttable.AddCell("Kenmerk:")
klanttable.AddCell(km)
Dim cell As New Cell
klanttable.SetMarginTop(10)
klanttable.SetMarginBottom(10)
doc.Add(klanttable)
doc.Close()
End Sub
Edit:
Found a nice tutorial on the iText website.
https://developers.itextpdf.com/content/itext-7-jump-start-tutorial-net/chapter-3-using-renderers-and-event-handlers
I just don't quite get how to insert that piece of code into my own piece of code. I think I need to create a new class that handles the event.
But how do I need to call this event.
I just add the follow line to my code:
Implements IEventHandler
And this new sub.
Public Sub HandleEvent([event] As [Event]) Implements IEventHandler.HandleEvent
Throw New NotImplementedException()
End Sub
How do I adjust the sub to handle the page-start event and page-end event ( if it's even still called that way)
Edit: I just imported all the stuff just to be sure I got everything. When everything is working fine I am just gonna remove everything not being used.
With some efforts, I could implement PAGE_END event in vb.net. Here is the code for you.
(A) In main module create pdf routine add:
*Dim HandlerRLA = New VariableHeaderEventHandlerRLA
PDFfile.AddEventHandler(PdfDocumentEvent.END_PAGE, HandlerRLA)*
(B) Add anlother class after End Class. You may add text/paragraph as per requirement. I have used image as Header and Footer on specific pages.
Public Class VariableHeaderEventHandlerRLA
Implements IEventHandler
Dim header As String
Dim doc As PdfDocument
Public Sub TextFooterEventHandler(ByRef doc As PdfDocument)
Me.doc = doc
End Sub
Public Sub HandleEvent([event2] As [Event]) Implements IEventHandler.HandleEvent
Dim docEvent1 As PdfDocumentEvent = event2
Dim canvas1 As PdfCanvas = New PdfCanvas(docEvent1.GetPage())
Dim pageSize1 As iText.Kernel.Geom.Rectangle = docEvent1.GetPage().GetPageSize()
'Dim canvas As Canvas = New Canvas(docEvent.GetPage(), New iText.Kernel.Geom.Rectangle(0, 0, pageSize.GetWidth(), pageSize.GetHeight))
Dim PDoc1 As PdfDocument = docEvent1.GetDocument()
Dim Page1 = docEvent1.GetPage()
Dim PageNo1 As Integer = PDoc1.GetPageNumber(Page1)
If PageNo1 > 1 Then
Dim imageFile, BottomImage As String
imageFile = "path to image folder\secondtop.bmp"
Dim data3 = ImageDataFactory.Create(imageFile)
BottomImage = "path to image folder\secondbottom2.bmp"
Dim data4 = ImageDataFactory.Create(BottomImage)
Dim Ratio = data3.GetHeight / data3.GetWidth
Dim rect As iText.Kernel.Geom.Rectangle = New iText.Kernel.Geom.Rectangle(0, 784, 595, 595 * Ratio)
With canvas1
.AddImage(data3, 0, 784, 595, 0)
'.AddImageFittedIntoRectangle(data3, rect, 0)
Ratio = data4.GetHeight / data4.GetWidth
rect = New iText.Kernel.Geom.Rectangle(0, 0, 595, 595 * Ratio)
'.AddImageFittedIntoRectangle(data4, rect, 0)
.AddImage(data4, 0, 0, 595, 0)
End With
End If
'Throw New NotImplementedException()
End Sub
End Class

"var" variable is used before it is assigned a value

It seems like I need to assign some values into variable var() and I don't know how. Can someone help me fix this please.
Imports System
Imports System.IO
Module Module1
Sub Main()
Dim i As Integer
Dim var() As String
Dim lines() As String = IO.File.ReadAllLines("C:\Users\carment\Desktop\Test.txt")
i = 1
For Each line As String In lines
var(i) = line
Console.WriteLine(var(i))
i = i + 1
Next
End Sub
End Module
You have to initialize the array as well:
var = New String(lines.Length-1) {}

How to get the variable names types, and values in the current class or Method in VB.net?

Hi
I am working on a project where my class has to execute VB code provided by the user, to make it simple i am trying to recreate my own eval function, i am using the following code i found on the web to do this task
Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.CodeDom.Compiler
Imports System.Reflection
Imports System.IO
Namespace PAB.Util
Public Class EvalProvider
Public Function VS_Eval(ByVal vbCode As String) As Object
Dim c As VBCodeProvider = New VBCodeProvider
Dim icc As ICodeCompiler = c.CreateCompiler()
Dim cp As CompilerParameters = New CompilerParameters
cp.ReferencedAssemblies.Add("system.dll")
cp.ReferencedAssemblies.Add("system.xml.dll")
cp.ReferencedAssemblies.Add("system.data.dll")
' Sample code for adding your own referenced assemblies
'cp.ReferencedAssemblies.Add("c:\yourProjectDir\bin\YourBaseClass.dll")
'cp.ReferencedAssemblies.Add("YourBaseclass.dll")
cp.CompilerOptions = "/t:library"
cp.GenerateInMemory = True
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("Imports System" & vbCrLf)
sb.Append("Imports System.Xml" & vbCrLf)
sb.Append("Imports System.Data" & vbCrLf)
sb.Append("Imports System.Data.SqlClient" & vbCrLf)
sb.Append("Namespace PAB " & vbCrLf)
sb.Append("Class PABLib " & vbCrLf)
sb.Append("public function EvalCode() as Object " & vbCrLf)
'sb.Append("YourNamespace.YourBaseClass thisObject = New YourNamespace.YourBaseClass()")
sb.Append(vbCode & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Debug.WriteLine(sb.ToString()) ' look at this to debug your eval string
Dim cr As CompilerResults = icc.CompileAssemblyFromSource(cp, sb.ToString())
Dim a As System.Reflection.Assembly = cr.CompiledAssembly
Dim o As Object
Dim mi As MethodInfo
o = a.CreateInstance("PAB.PABLib")
Dim t As Type = o.GetType()
mi = t.GetMethod("EvalCode")
Dim s As Object
s = mi.Invoke(o, Nothing)
Return s
End Function
End Class
End Namespace
The problem with code is that it can't access any variables or there values, so i have decided to get the variable names, there values types and there types dynamically and recreate them in the class that is being created dynamically.
Please suggest a way to get the variable names there types and values in the current class or method, so that i can recreate them, and execute the user passed code, the user knows what variables are in the current class or method and there datatypes but he don't know there values as they may have changed, so he can't initialize them.
Is there a way to do this, this code will be called in an asp.net page on page_load event, the code passed by the user is stored in the variable vbCode that is passed as a parameter.
If there is any other method to do this, please suggest
Thank you
I have finally found the solution of how to get the variables and values of the current instance of a class.
using System.Reflection; it is very easy to achieve, all you have to write is the following line:
Dim fields As FieldInfo() = Me.GetType().GetFields()
For Each fld As FieldInfo In fields
Dim name As String = fld.Name
Dim value = fld.GetValue(Me)
Dim typ As Type = fld.FieldType
Next
Note : It only works for public variables
This may help you?