Embedding and referencing XML file in VB.NET project - vb.net

In a VS2013 VB.NET WinForms project I need to include an XML file in the deployed application that will be read from and written to at run time.
I have the file as an embedded resource, and have "Copy Always" selected for output. The file name is "Settings.xml" and the resource name is Settings.
Looking at this example I did the following to reference it in my code:
Private xmlFile as XmlDocument ' In the general declaration area, before the Load event
xmlFile.LoadXml(My.Resources.Settings) ' In the Load event, in a Try/Catch
But I get an "Object reference not set to an instance of an object" on the second line.
In the code I plan on accessing the xml with something like this:
Dim xmlDoc as New XmlDocument
xmlDoc = xmlFile
I'm not sure yet how to save any changes I make, as initial attempts of something like xmlDoc.Save(xmlFile) didn't work.
What am I missing?

First of all, you need to use the constructor for xmlFile:
Private xmlFile As New XmlDocument
Then, all you need to do is use the resource name, i.e. "Settings.xml" if the resource is embedded:
xmlFile.LoadXml("Settings.xml")
You shouldn't even need to set the resource as "CopyAlways".

Related

How to load MSXML2.DOMDocument object

I have Word VBA code that is supposed to create an Msxml2.DOMDocument object and load an Xml file into it:
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.Load (XmlFileName)
This code runs on my computer.
On a coworker's computer the Load method returns False and doesn't load the data.
I tried switching from MSXML 3.0 to MSXML 6.0 by changing the first line of code to
Set XDoc = CreateObject("MSXML2.DOMDocument60")
as well as changing the project's reference to v6.0. This resulted in failure to create the object, giving the error message
"Runtime error 429: ActiveX component can't create object"
I tried reregistering the .dll files for both MSXML versions, with no effect.
What might be causing the code to run on my machine but not on others?
How might I resolve the respective errors for either v3.0 or v6.0?
I figured out what was causing this problem. The XML file I was trying to load was inside a zip file and before loading it I had to find its name using pattern matching. My coworkers computer had the "File name extensions" checkbox unchecked so the file name that VBA read didn't match the required pattern that included the .xml extension. After I checked the checkbox it worked perfectly.

How do you read the File Properties of a file found via GetFiles function?

I'm trying to get a collection of executables, their directories, and their version numbers displayed in a GridView like so:
Dim dir As New DirectoryInfo("C:\Program Files (x86)\PathExample")
For Each foundFile As FileInfo In dir.GetFiles("*.exe", SearchOption.AllDirectories)
Dim foundFileInfo = FileVersionInfo.GetVersionInfo(foundFile.ToString)
'Dim foundFileInfo = FileVersionInfo.GetVersionInfo(foundFile.Directory.ToString)
DataGridView1.Rows.Add(foundFileInfo, foundFile.Directory, foundFile)
Next foundFile
The GridView will successfully show the executable name, and the directory in their respective columns, however, I get thrown an error:
System.IO.FileNotFoundException: 'Console.exe'
Console.exe is in fact an existing file, and it's able to obtain the directory and executable name, and store it in the GridView, it's ONLY when I try to get the file version info that it starts throwing this error.
Am I using the wrong function?
I basically need to be able to read any line from this menu:
FileProperties
I need to be able to read each property individually, like getting just the File Version, or Copyright info, or Last-Modified date, etc. and storing that into a variable to be placed in one of the columns in the GridView.
There are a few problems with the code:
FileVersionInfo.GetVersionInfo() expects the full path of the file. Don't use foundFile.ToString. Instead, use foundFile.FullName.
foundFile is a FileInfo object. You shouldn't add it directly to a DataGridView cell. Select the appropriate property instead. You probably want foundFile.Name (or perhaps .FullName).
Similarly, foundFileInfo is an object of type FileVersionInfo. You should use a specific property to display in the cell.
Assuming you want the file description, directory path, and file name (respectively) in the cells, your code should look something like this:
For Each foundFile As FileInfo In dir.GetFiles("*.exe", SearchOption.AllDirectories)
Dim foundFileInfo = FileVersionInfo.GetVersionInfo(foundFile.FullName)
DataGridView1.Rows.Add(foundFileInfo.FileDescription, foundFile.DirectoryName, foundFile.Name)
Next
You can use foundFileInfo to get other info like the file version, copyright, etc. See the available properties under the FileVersionInfo class.

Can't save to embedded xml document

In a VB.NET project I have an xml document as an embedded resource. I am accessing it with
Private xmlFile as New XmlDocument()
in the General Declaration area. And then I am loading it in the form load method:
xmlFile.LoadXml(My.Resources.Settings)
In a method I'm finding specific nodes and updating them from user input:
'Dim xmlDoc as XmlDocument
'xmlDoc = xmlFile
Dim settingNodes As XmlNodeList = xmlFile.SelectNodes("//Program/ProgramTitle")
For Each setting As XmlNode In settingNodes
If setting.InnerText = title Then
setting.ParentNode.Item("ProgramSaveFolder").InnerText = programFolder
setting.ParentNode.Item("PrimaryBackupFolder").InnerText = primBackup
setting.ParentNode.Item("SecondaryBackupFolder").InnerText = secBackup
End If
Next
' Neither of these work
xmlFile.Save("Settings.txt")
'xmlDoc.Save("GameSettings.txt")
The xmlDoc code is from when I was led to believe at one point that it's not saving because xmlFile was in use (I've been trying a lot different things!).
But, as noted in the code, neither of those work. This is very similar to what I see all over for examples of how to do this, but when I run the program it doesn't change the file at all.
You cannot modify an embedded resource. You can include the XML file as content and it will appear in your build folder as a normal file that can be loaded and updated using the File.IO namespace or XMLDocument.Load().
One catch to look out for is that a file in the Program Files folder being modified will require administrator rights which a user may not have. If this is the case, it's best to copy the file to the AppData folder.

Uploading xml to windows phone 8 VB

`Dim medium As String = TextBox1.Text
Dim data_xml = XElement.Load("Assets\Manager.xml")
'next quaries the xml for desired attributes
Dim query = From DataTable1 In data_xml.Descendants("DataTable1")
Where (DataTable1.Attribute("Medium").Value = medium)
Select Uname = DataTable1.Attribute("Username").Value
For Each result In query
'displays results to textbox
TextBox2.Text = result
Next
I try to use this code to read from an xml file in the assets but the file does not seem to exist
At the declaration of the xelement.load("Assets\Manager.xml") I get this error
An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: Could not find file 'C:\Data\SharedData\PhoneTools\AppxLayouts\d5d3a1e7-56d7-477c-bcd2-f949f3374de1VS.Debug_AnyCPU.NAME\Assets\Manager.xml'.
If there is a handler for this exception, the program may be safely continued.
Any ideas?
Steps to make it work:
Change Manager.xml Build action to Content
Change Copy to output directory to Copy if newer
Load file using XElement.Load("Assets/Manager.xml");
Edit:
Ok, since you are not willing to share more of the code even though you ask for help, there's nothing else I can do but put up an example :)
"Software" below, implemented in Visual Basic, reads and displays XML file named Manager.xml, that is set as Content in WP8 project. Working example can be found at https://github.com/mikkoviitala/read-content-xml

How do I get resource file values in Visual Basic?

I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.
Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.
I think the issue is with the string "MyProjectName.My.Resources.Resources".
Would I be better off moving the strings into their own resource file?
I thought it was something similar to:
my.Resource.whateverhere
Is that not the kind of resources you are looking for?
Try
Global.<MyNamespace>.My.Resources.<ResourceStringName>
to access Resource Strings
Try ResourceManager("MyProjectName.Resources", ...), otherwise if it's the application resources you can simply use My.Resources.HD (see here:My.Resources Object)
or
Open Reflector, load your assembly there, go to resources, a list of resources appears, search for the one containg 'HD', copy the name (it's like MyProjectName.Resources.resources), remove the last .resources and try with that.
Refer to the MSDN article Retrieving Resources with the ResourceManager Class for naming convetions:
Dim myManager As New _
System.Resources.ResourceManager("ResourceNamespace.myResources", _
myAssembly)
If you load an external .resx file and want it to show up under intellisense My.Resources then you need to do 2 things.
First the file should be in the root of your project. Simply right click the project and do "Add Existing Item", and give it your .resx file. You should notice that there is no chevron to expand the resx file like your built-in resource file.
The last step is to highlight your resx file and go to the properties window. Under Custom Tool put "ResXFileCodeGenerator" and under the Custom Tool NameSpace put "My.Resources". You should now be able to programmatically access this resource under My.Resources.[name of the resx file].resource_item.
I was unable to access the resource file until I moved the .resx file into its own project and referenced that project from my main one. I also had to create a dummy class in that project so that it would compile into a DLL file.
The code for accessing the resource file is actually located in the generated Resource.resx.vb file.
I was able to access the resource file using the following code.
'Name of Class Library where I moved the resx file
Dim classLibraryName As String = "ResourceProj"
'Name of Resource File without the .resx suffix
Dim resourceFileName As String = "Mappings"
'Finding the assembly of the resx file, ResourceProjClass is a dummy class I created so that the dll would build.
Dim myAssembly As Assembly = GetType(ResourceProj.ResourceProjClass).Assembly
Dim rm As Resources.ResourceManager = Nothing
rm = New Resources.ResourceManager(classLibraryName & "." & resourceFileName, GetType(myAssembly)
Return rm.GetString(lookUpKey)
Simply:
Dim loginMessage As String = Global.Resources.NameOfYourResxFile.NameOFVariable