How to read simple pseudo XML file? - vb.net

I want to be able to read info from a simple, pseudo XML file I created to get the content. Here is what my XML file would look like :
<title>Form Title</title>
<Message1>A message or something</Message1>
<FormWidth>500</FormWidth>
<FormHeight>500</FormHeight>
The XML class I find online and inside Visual Studio are too advance. This is just a simple config file I'd like to use. Any tips?

Add a function like this to your code behind (I just converted this from c# so you may need to change some things):
Private Shared Function ReadValueFromXML(ValueToRead As String) As String
Try
Dim doc As New XPathDocument(System.Web.HttpContext.Current.Server.MapPath("filenameOfYourXML.xml"))
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim expr As XPathExpression
expr = nav.Compile(Convert.ToString("/") & ValueToRead)
Dim iterator As XPathNodeIterator = nav.Select(expr)
While iterator.MoveNext()
Return iterator.Current.Value
End While
Return String.Empty
Catch
Return String.Empty
End Try
End Function
Don't forget to add these import statements in your code behind as well:
Imports System.Xml
Imports System.Xml.XPath
And when you use it, let's say you want to get the value of FormWidth:
Dim FormWidth As String = ReadValueFromXML("FormWidth")

Related

Find exact string and replace with carriage return plus string with visual studio

I am looking to find all instances of the exact string "Public" and replace it with " ' \n Public" (Add an empty comment above every Public declaration. )
I would also like to ignore any lines that are already commented out i.e. 'Public, and capture the whole line
What you want to do is
Load up the Find and Replace dialog and put Public in the Find what field and put '\nPublic in the Replace with field.
Check Match case and Use Regular Expressions
And away you go. The extension Multiline Search and Replace makes this a bit easier.
If you want normalized Windows-style line endings, you may want to replace with '\r\nPublic instead.
Visual Studio 2019 will allow you to replace Public with '\nPublic when using RegEx option. However if you don't have 2019 (or it doesn't work for some other reason), you can write some code to do it:
Put this method in your code and start debugging, then call the method
Imports System.IO
Module Module1
Public Sub foo()
Dim fileName = New System.Diagnostics.StackTrace(True).GetFrame(0).GetFileName()
Dim fileContents As String
Using sr = New StreamReader(fileName)
fileContents = sr.ReadToEnd().Replace(
"Pub" & "lic",
"'" & Environment.NewLine & "Pub" & "lic") ' String split so not replaced
End Using
Using sw = New StreamWriter(fileName, False)
sw.Write(fileContents)
End Using
End Sub
Sub Main()
foo()
End Sub
End Module
I think it's not natively possible with Visual Studio, but you can download a plugin like
https://marketplace.visualstudio.com/items?itemName=PeterMacej.MultilineSearchandReplace,
that provides such support.

Loading My.Settings in other solution

I need to load My.settings from the first Solution into the Second.
In the first project I have a helper class for getting the Settings.
Public Class format
Public NotInheritable Class Helper
Private Sub New()
End Sub
Public Shared Function getAppSetting() As String
Dim returnValue As Object = My.Settings.format
If returnValue Is Nothing Then
Return String.Empty
Else
Return returnValue.ToString
End If
End Function
Public Shared Function getAppSettingTheme() As String
Dim returnValue_theme As Object = My.Settings.theme_selected
If returnValue_theme Is Nothing Then
Return String.Empty
Else
Return returnValue_theme.ToString
End If
End Function
End Class
End Class
This class I have implemented in the other Solutions (Even addiction I have a set)
In other Solutions I have the code for getting the Settings.
Imports MyProject.format.Helper
MsgBox(getAppSettingTheme())
But in the MsgBox I see Default Settings (Unchanged) While in the first solution displays the user-changed settings.
My.Settings I have saved [My.settings.save]
If you choose to do this in a complicated way,what you have to do is,make classes in the first project to read My.Settings,then reference the project in the other project and use it...
However,i'll rather describe an easier way(tho the above one is not that hard) to achieve your goal.
Firstly,i believe that you are using My.Settings to store some data,right ?If so,you can simply save the data to a text file and read it from anywhere you want.This will save plenty of your code and make it tidy :)
As you seem to be a beginner,i would try to keep it as simple as possible and explain in the simplest words...
Now,let's assume,you have 4 My.Settings entries as follows :
UserName
Password
Phone
Age
Instead of writing this data in My.Settings,write it to a text file.Let's assume a user inputs relevant data and it looks somewhat like this :
Zack Rayan
1212121
+090990809809
20
To write a text file, you can simply use File.WriteAllText but as we see that here,our data is in multiline,we can make use of the following :
FIle.WriteAllLines
File.AppendText
Well,let's use File.AppendText method(you can use the below code with WriteAllText as well :)) :
File.AppendText("C:\test.mycustomExtension" , "Zack Rayan" + Environment.NewLine + "1212121" + Environment.NewLine + "+090990809809" + Environment.NewLine + "20")
This will write a text file for you containing the given data in separate lines as well as you will have your own custom extension for the file :)
Now,how to use it ?
Simple :
Dim ReadFile as New List(Of String)(File.ReadAllLines("C:\Test.mycustomextension"))
Now,let's assume,when you were using My.Settings, you used some codes like this :
If My.Settings.UserName = "Zack" Then
......
Scroll up and look closely.UserName was your first entry in My.Settings and when we wrote the text file,ZACK RAYAN-the assumed username was also written in the first line
A few lines above, i created a list which reads the text file.It needs no saying that it will read(and store) the first line first and then move on gradually. So,where you used :
If My.Settings.UserName = "Zack" Then
u should now use :
If ReadFile(0) = "Zack" Then
I hope this helps to enrich your knowledge :)

Extracting `dll` files from the Resources after they been added using CodeDOM in VB.Net

I'v seen a lot of answers here on stackoverflow, but none of them help me with exactly what i need and almost all of them in C# when i need VB, so i hope someone will help me with my problem, which is this :
I have compiled a exe file in vb.net using CodeDOM, and i added two dll file to its resources and that worked just fine and you can even notice that the size of the exe has increase after adding the resources, but when i run the exe file like that My.Resources.Touchless, it gives me an error saying that
"Resources" is not a member of "My".
And what i need is to read these dll files from the compiled exe file and then extract them using File.WriteAllBytes()..., if i didn't try to extract the files from the resources and instead of that i copied them manually to the executable path, the application will work perfectly, so the problem is just with trying to call the dll files from the resources.
Here is some code :
Public Shared Function Compile(ByVal Output As String, ByVal Source As String, ByVal Icon As String, ByVal resources As String) As Boolean
Dim Parameters As New CompilerParameters()
Dim cResults As CompilerResults = Nothing
Dim Compiler As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
Parameters.GenerateExecutable = True
Parameters.TreatWarningsAsErrors = False
Parameters.OutputAssembly = Output
Parameters.MainClass = "MyNamespace.MainWindow"
Parameters.EmbeddedResources.Add(Path.GetTempPath & "TouchlessLib.dll")
Parameters.EmbeddedResources.Add(Path.GetTempPath & "WebCamLib.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", Path.GetTempPath & "TouchlessLib.dll"})
Parameters.CompilerOptions = "/platform:x86 /target:winexe"
If Not String.IsNullOrEmpty(Icon) Then
File.Copy(Icon, "icon.ico")
Parameters.CompilerOptions += " /win32icon:" & "icon.ico"
End If
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source)
If cResults.Errors.Count > 0 Then
For Each compile_error As CompilerError In cResults.Errors
Dim [error] As CompilerError = compile_error
Console.Beep()
MsgBox("Error: " & [error].ErrorText & vbCr & vbLf & [error].Line)
Next
Return False
End If
If Not (String.IsNullOrEmpty(Icon)) Then
File.Delete("icon.ico")
End If
Return True
End Function
When i call them from the compiled exe file like this :
File.WriteAllBytes(Application.StartupPath & "\TouchlessLib.dll", My.Resources.TouchlessLib)
File.WriteAllBytes(Application.StartupPath & "\WebCamLib.dll", My.Resources.WebCamLib)
... i get the following error message :
"Resources" is not a member of "My".
Try adding this class:
Imports System.Dynamic
Imports System.Reflection
Public Class DynamicResources
Inherits DynamicObject
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim name As String = IO.Path.GetFileNameWithoutExtension(s)
Dim Manager As New Resources.ResourceManager(name, asm)
Try
Dim resource = Manager.GetObject(binder.Name)
If Not resource Is Nothing Then
result = resource
Return True
End If
Catch ex As Exception
End Try
Next
Return False
End Function
End Class
You can use it like this:
Dim root as string=Application.StartupPath
File.WriteAllBytes(Path.Combine(root, "TouchlessLib.dll"), DynamicResources.TouchlessLib)
File.WriteAllBytes(Path.Combine(root, "WebCamLib.dll"), DynamicResources.WebCamLib)
The My namespace and any associated functionality is created via auto-generated code. Since your code is now the code generator and not the IDE, you will not have those niceties unless your code provides it.
To extract an embedded resource, you need to include code similar to the following in the source code you are compiling with CodeDOM.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim fi As New FileInfo(s)
Using strm As Stream = asm.GetManifestResourceStream(s)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
Next
Make sure that you also include:
Imports System.Reflection
Imports System.IO
This code retrieves the executing Assembly obtains an array of embedded resource names. It then calls GetManifestResourceStream method to get the named resource as a stream. This stream is copied to a file stream.
Modify the example to suite your needs.
Note that I have not included any error checking/handling in this example. Anything dealing with IO should have some error handling.
Edit:
Based on the comment below, it appears that only a copy/paste type answer will do for the OP.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName As String
Dim fi As FileInfo
resourceName = "TouchlessLib.dll"
fi = New FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, resourceName))
Using strm As Stream = asm.GetManifestResourceStream(resourceName)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using

Loading a file into memory stream buffer and creating new file with same content and with different filename

I don't know whether it is simple or not because i am new to programming.
my requirement is : In my vb.net winform application, the filenames of the files present in "D:\Project" willbe displayed in DataGridView1 control. Now I want to load these files one after another into memory stream buffer and add the headers("ID","Name","Class") to the content in the file. Then I want to save these files in "C:\" with "_de" as suufix to the filename i.e.,sample_de.csv.
Can anyone please help me? If you need more clarity i can post it in more clear way
Many Thanks for your help in advance.
Try adapting this example to your situation:
Imports System.Text
Imports System.IO
Module Module1
Sub Main()
' Read input
Dim inputBuffer As Byte() = File.ReadAllBytes(".\input.txt")
' Manipulate the input
Dim outputBuffer As Byte() = DoSomethingWithMyBuffer(inputBuffer)
' Add headers
' There are several ecodings to choose from, make sure you are using
' the appropriate encoder for your file.
Dim outputTextFromBuffer As String = Encoding.UTF8.GetString(outputBuffer)
Dim finalOutputBuilder As StringBuilder = New StringBuilder()
finalOutputBuilder.AppendLine("""ID"",""Name"",""Class""")
finalOutputBuilder.Append(outputTextFromBuffer)
' Write output
File.WriteAllText(".\output.txt", finalOutputBuilder.ToString(), Encoding.UTF8)
End Sub
Private Function DoSomethingWithMyBuffer(inputBuffer As Byte()) As Byte()
'' Do nothing because this is just an example
Return inputBuffer
End Function
End Module

VB.NET Read Certain text in a text file

I want my program to read certain text in a text file. For example if I have a text file that contains the following info..
acc=blah
pass=hello
I want my vb.net application to get that the account variable is equal to blah, and the password variable is equal to hello.
Can anyone tell me how to do this?
Thanks
Here is a quick little bit of code that, after you click a button, will:
take an input file (in this case I created one called "test.ini")
read in the values as separate lines
do a search, using regular expressions, to see if it contains any "ACC=" or "PASS=" parameters
then write them to the console
here is the code:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFile As String = "Test.INI"
Dim sr As New StreamReader(strFile)
Dim InputString As String
While sr.Peek <> -1
InputString = sr.ReadLine()
checkIfContains(InputString)
InputString = String.Empty
End While
sr.Close()
End Sub
Private Sub checkIfContains(ByVal inputString As String)
Dim outputFile As String = "testOutput.txt"
Dim m As Match
Dim m2 As Match
Dim itemPattern As String = "acc=(\S+)"
Dim itemPattern2 As String = "pass=(\S+)"
m = Regex.Match(inputString, itemPattern, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m2 = Regex.Match(inputString, itemPattern2, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Do While m.Success
Console.WriteLine("Found account {0}", _
m.Groups(1), m.Groups(1).Index)
m = m.NextMatch()
Loop
Do While m2.Success
Console.WriteLine("Found password {0}", _
m2.Groups(1), m2.Groups(1).Index)
m2 = m2.NextMatch()
Loop
End Sub
End Class
Have a look at this article
Reading and writing text files with VB.NET
Wile reading the file line by line, you can use String.Split Method with the splitter being "=", to split the string into param name, and param value.
Looks like you've got an INI file of some kind... The best way to read these is using the *PrivateProfile* functions of the windows API, which means you can actually have a proper full INI file quite easily for anything you need. There is a wrapper class here you may like to use.
Microsoft recommends that you use the registry to store this sort of information though, and discourages use of INI files.
If you wish to just use a file manually with the syntax you have, it is a simple case of splitting the string on '=' and put the results into a Dictionary. Remember to handle cases where the data was not found in the file and you need a default/error. In modern times though, XML is becoming a lot more popular for data text files, and there are lots of libraries to deal with loading from these.
My suggestion: you use XML. The .NET framework has a lot of good XML tools, if you're willing to make the transition to put all the text files into XML, it'll make life a lot easier.
Not what you're looking for, probably, but it's a cleaner solution than anything you could do with plain text (outside of developing your own parser or using a lower level API).
You can't really selectively read a certain bit of information in the file exclusively. You'll have to scan each line of the file and do a search for the string "pass=" at the beginning of the line. I don't know VB but look up these topics:
File readers (espically ones that can read one line at a time)
String tokenizers/splitting (as Astander mentioned)
File reading examples
Have you thought about getting the framework to handle it instead?
If you add an entry into the settings tab of the project properties with name acc, type string, scope user (or application, depending on requirements) and value pass, you can use the System.Configuration.ApplicationSettingsBase functionality to deal with it.
Private _settings As My.MySettings
Private _acc as String
Private _pass as String
Public ReadOnly Property Settings() As System.Configuration.ApplicationSettingsBase
Get
If _settings Is Nothing Then
_settings = New My.MySettings
End If
Return _settings
End Get
End Property
Private Sub SetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
theSettings.acc=_acc
theSettings.pass=_pass
Settings.Save()
End Sub
Private Sub GetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
_acc=theSettings.acc
_pass=theSettings.pass
End Sub
Call GetSettings in whatever load event you need, and SetSettings in closing events
This will create an entry in the application.exe.config file, either in your local settings \apps\2.0\etc etc directory, or your roaming one, or if it's a clickonce deployment, in the clickonce data directory. This will look like the following:-
<userSettings>
<MyTestApp.My.MySettings>
<setting name="acc" serializeAs="String">
<value>blah</value>
</setting>
<setting name="pass" serializeAs="String">
<value>hello</value>
</setting>
</MyTestApp.My.MySettings>
</userSettings>
Writing your own parser is not that hard. I managed to make one for a game (Using C#, but VB appears to have Regex class too. Using that, the acc variable in your file would be everything up to the = sign, and then blah would be everything past the = to the newline character (\n) Then go to the next line and repeat.
I have written this for you, check it and enjoy with the results, have a great day!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim acc As New List(Of String)
Dim pass As New List(Of String)
Dim lines() As String = System.IO.File.ReadAllLines(".\credentials.txt")
For Each lineItem As String In lines
Dim vals() As String = lineItem.Split(Convert.ToChar("="))
If vals.Length > 0 Then
Dim lineId As String = vals(0)
If lineId = "acc" Then
acc.Add(vals(1))
ElseIf lineId = "pass" Then
pass.Add(vals(1))
End If
End If
Next
TextBox_acc.Text = String.Join(Environment.NewLine, acc)
TextBox_pass.Text = String.Join(Environment.NewLine, pass)
End Sub
End Class