How to create global obects in vb.net - vb.net

I'm using visual studio 2015.
I'm clearly missing some things...
I want to create a global filestream and stream writer.
Dim wFile As System.IO.FileStream = New FileStream _
("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append)
Dim sw As New StreamWriter(wFile)
This works fine. BUT I need to access it globally. Ideally the code would be in its own .aspx file and the wFile and sw objects could be used in a different .aspx file.
Thanks
(odd that I need to edit my original post to add new info)
I am now trying to add a class based on info from MSDN. It's not working. Code -
Imports System
Imports System.IO
Imports System.Text
Public Class test
Public Shared Sub CreateFileStream()
Dim fs As FileStream = New FileStream("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append
End Sub
End Class
Then trying to use the class in a function -
Protected Function bufferList(ByVal testData As String) As String
Try
Dim sw As New StreamWriter(fs)
sw.WriteLine(testData)
End Try
End Function
I get an error on 'Dim sw As New StreamWriter(fs)' fs is not declared. It may be inaccessible due to it's protection level
I've tried calling it with test.fs, but test does not have an fs property.

Related

VB.NET How to save Program settings inside class module

I'm currently building a program which requires numerous staff to use my program and the program is located on a shared drive on the network so all users can access the program. In my program I have a Database which I use to manage all the user accounts and other information. When you run the program for the first time ever on the network, it asks the administrator where to create the database. After the program creates the database, I save the connection string to a string variable in a class module within my program. However once I exit the program the value I set the to the string variable in the class gets erased. Is there a way to prevent the string from losing its value after closing the program ? I know I could do this via my.settings but I don't want to do it that way.
You can make your own settings file using a binary serializer.
This method can be used to store an instance of your settings class to a file, which is not very human-readable. If human readability and editability is required, you could use an xml serializer instead. The settings file will reside in the application directory. You can control this with the variable settingsFileName.
Create a new console application and paste the code below. Run it a couple of times and note that the "connection string" is persisted through application close and open.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Module1
Private settingsFileName As String = "Settings.bin"
Private mySettingsClass As SettingsClass
Private Sub loadSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Open)
mySettingsClass = CType(formatter.Deserialize(stream), SettingsClass)
End Using
Else
Using Stream As New FileStream(settingsFileName, FileMode.CreateNew)
mySettingsClass = New SettingsClass()
formatter.Serialize(Stream, mySettingsClass)
End Using
End If
End Sub
Private Sub saveSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Truncate)
formatter.Serialize(stream, mySettingsClass)
End Using
Else
Using stream As New FileStream(settingsFileName, FileMode.CreateNew)
formatter.Serialize(stream, mySettingsClass)
End Using
End If
End Sub
<Serializable>
Public Class SettingsClass
Public Property ConnectionString As String = ""
End Class
Sub Main()
Console.WriteLine("Loading settings...")
loadSettings()
Dim connectionString = mySettingsClass.ConnectionString
Console.WriteLine("Connection string: ""{0}""", connectionString)
Console.WriteLine("Enter new connection string...")
mySettingsClass.ConnectionString = Console.ReadLine()
Console.WriteLine("Saving settings...")
saveSettings()
Console.WriteLine("Done!")
Console.ReadLine()
End Sub
End Module
Add additional properties to SettingsClass which can be used elsewhere in your application.

How to use Stream to get String

I have a method in a third-party tool that has the following criteria:
ExportToXML(fileName As String) 'Saves the content to file in a form of XML document
or
ExportToXML(stream As System.IO.Stream) 'Saves the content to stream in a form of XML document
How do I use the call with the stream as the parameter to get the XML as a string?
I have researched and tried several things and just still can't get it..
You can use a MemoryStream as the stream to export the XML to, and then read the MemoryStream back with a StreamReader:
Option Infer On
Imports System.IO
Module Module1
Sub Main()
Dim xmlData As String = ""
Using ms As New MemoryStream
ExportToXML(ms)
ms.Position = 0
Using sr As New StreamReader(ms)
xmlData = sr.ReadToEnd()
End Using
End Using
Console.WriteLine(xmlData)
Console.ReadLine()
End Sub
' a dummy method for testing
Private Sub ExportToXML(ms As MemoryStream)
Dim bytes = Text.Encoding.UTF8.GetBytes("Hello World!")
ms.Write(bytes, 0, bytes.length)
End Sub
End Module
Added: Alternatively, as suggested by Coderer:
Using ms As New MemoryStream
ExportToXML(ms)
xmlData = Text.Encoding.UTF8.GetString(ms.ToArray())
End Using
A small effort at testing did not show any discernible efficiency difference.

InvalidOperationException when trying to add XElement to XDocument

I'm getting this error when I try to add a XElement to a XDocument:
An exception of type 'System.InvalidOperationException' occurred in
System.Xml.Linq.ni.dll but was not handled in user code
My code is:
Imports System.Xml
Imports System.Xml.Linq
Imports System.IO.IsolatedStorage
Imports System.IO
Public Sub SaveRecord()
Using myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim doc As XDocument
Using isoStore1 As IsolatedStorageFile = _
IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream1 As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Open, isoStore1)
doc = XDocument.Load(isoStream1)
MessageBox.Show(doc.ToString)
'This gives the right xml-code
doc.Add(New XElement("NewChild", "new content")) 'This is where the error takes place
MessageBox.Show(doc.ToString)
Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("file.xml", FileMode.Create, isoStore)
doc.Save(isoStream)
End Using
End Using
End Using
End Using
End Using
Exit Sub
End Sub
The error shows up when the debugger enters the line doc.Add(New XElement("NewChild", "new content"))
Can anyone explain to me what the cause of this error is and how I can solve it?
You need to add your XElement to your XDocuments root.
doc.Root.Add(New XElement("NewChild", "new content"))
Adding it directly to the doc will make your xml invalid as it will be having two roots because you are adding the XElement after your XDocument instead of to the root.

Saving and loading an object in Vb.net

I need to save an object that I have in my program (this object stores data) to the hard drive so i can load it next time the program starts
I have tried using serialization and xml file output but I cant seem to get this working since the data I have is not of the 'string' object type.
I considered using file open/put/get but MSDN recommends against this since it is much more inefficient than serialization.
Any simple load/save functions that will accomplish my goal?
Thanks in advance
Martin
I figured out that I needed to convert the object to binary data before serialization.
For others, here are my functions
'Imports
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
'Functions
Public Function Load()
If My.Computer.FileSystem.FileExists(mstrSaveFile) Then
Dim fs As Stream = New FileStream(mstrSaveFile, FileMode.Open)
Dim bf As BinaryFormatter = New BinaryFormatter()
mstrData = CType(bf.Deserialize(fs), CType(mstrData))
fs.Close()
End If
Return True
End Function
Public Function Save()
If My.Computer.FileSystem.FileExists(mstrSaveFile) = True Then
My.Computer.FileSystem.DeleteFile(mstrSaveFile)
End If
Dim fs As Stream = New FileStream(mstrSaveFile, FileMode.Create)
Dim bf As BinaryFormatter = New BinaryFormatter()
bf.Serialize(fs, mstrData)
fs.Close()
Return True
End Function

Save user-defined object into Windows Registry using VB.NET

I need to save created object into Windows Registry and after reopening application to read it? I know how to save and read string but this is complex object.
Any idea?
You maybe want to use a XmlSerializer (or other serializers). It's easy to use, and the documentation is full of examples.
But why storing it in the registry?
Better use Application Settings and User Settings.
EDIT:
Instead of the registry, save your object to a file in the ApplicationData directory of the user. You can get the path to this directory with
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Full example:
Imports System.IO
Imports System.Xml.Serialization
Module Module1
Public Class MySuperClass
Public Property MyString() As String
Public Property MyInt() As Int32
End Class
Public Sub Main(ByVal args() As String)
Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication")
If Not Directory.Exists(myFolder) Then
Directory.CreateDirectory(myFolder)
End If
Dim myFile = Path.Combine(myFolder, "MySettings.txt")
Dim o = New MySuperClass With {.MyString = "Hi!", .MyInt = 42}
Dim x = New XmlSerializer(GetType(MySuperClass))
Using sr = New StreamWriter(myFile)
' Save directly to file
x.Serialize(sr, o)
End Using
' for demonstrating purpose
o = Nothing
Using sr = New StreamReader(myFile)
' Load directly from file
o = CType(x.Deserialize(sr), MySuperClass)
End Using
End Sub
End Module