Solved

Reading app settings from an xml file

Posted on 2006-11-20
18
309 Views
Last Modified: 2008-02-01
I need to be able to read settings from an xml file.

Unfortunately....I can't use the app exe config file because the call needs to be made from a project within my solution that has a different assembly name


I've seen alot of posts talking about serialization which unfortunately don't mean anything to me.


Please help!!!!!
0
Comment
Question by:johnnyg123
  • 7
  • 6
  • 5
18 Comments
 
LVL 20

Accepted Solution

by:
ElrondCT earned 250 total points
Comment Utility
Here's a great, simple method that RonaldBeimans posted. I'm using it for exactly this purpose in a project of mine:

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21259587.html
0
 
LVL 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 250 total points
Comment Utility
0
 

Author Comment

by:johnnyg123
Comment Utility
As I mentioned above I have a solution with multiple projects

In one project I created the class along with a fom that has 2 buttons and a text box for each of the 2 settings (ConnectionString and Last Updated)

One button will execute the read and one button will execute the save.

This works perfect.


Here is the class code:

<Serializable()> Public Class MaintainCustAppSettings
    Public ConnectionString As String
    Public LastUpdated As String

    Public Sub SaveXml(ByVal Path As String)
        Dim fStream As System.IO.FileStream
        Dim myFormat As New System.Runtime.Serialization.Formatters.Soap.SoapFormatter
        Try
            fStream = New System.IO.FileStream(Path, IO.FileMode.Create, IO.FileAccess.Write)
            myFormat.Serialize(fStream, Me)
            fStream.Close()
        Catch ex As Exception
            MsgBox("Error saving: " & ex.Message)
        Finally
            If Not (fStream Is Nothing) Then fStream.Close()
        End Try
    End Sub

    Public Shared Function LoadXML(ByVal Path As String) As MaintainCustAppSettings
        Dim fStream As System.IO.FileStream
        Dim myFormat As New System.Runtime.Serialization.Formatters.Soap.SoapFormatter
        Dim tmp As MaintainCustAppSettings
        Try
            fStream = New System.IO.FileStream(Path, IO.FileMode.Open, _
                IO.FileAccess.Read)
            tmp = CType(myFormat.Deserialize(fStream), MaintainCustAppSettings)
        Catch ex As Exception
            MsgBox("Error opening: " & ex.Message)
        Finally
            If Not (fStream Is Nothing) Then fStream.Close()
        End Try
        Return tmp

    End Function
End Class


Here is the xml file

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
- <SOAP-ENV:Body>
- <a1:MaintainCustAppSettings id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Customer/Customer%2C%20Version%3D1.0.2516.18462%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
  <ConnectionString id="ref-3">Persist Security Info=True;User ID=cust_app;Password=custapp;Initial Catalog=CustomerInfo;Data Source=webprd01;Application Name=Customer Info Tracking;Connect Timeout=60</ConnectionString>
  <LastUpdated id="ref-4">11/20/2006</LastUpdated>
  </a1:MaintainCustAppSettings>
  </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>



My problem is that in another project I am trying to read the xml file and receive the following error:

Error Opening:Specified Cast is Invalid.



Here is the code for the class in that project:


<Serializable()> Public Class GetConnectionString
    Public ConnectionString As String
    Public LastUpdated As String

    Public Shared Function LoadXML(ByVal Path As String) As GetConnectionString
        Dim fStream As System.IO.FileStream
        Dim myFormat As New System.Runtime.Serialization.Formatters.Soap.SoapFormatter
        Dim tmp As GetConnectionString
        Try
            fStream = New System.IO.FileStream(Path, IO.FileMode.Open, _
                IO.FileAccess.Read)
            tmp = CType(myFormat.Deserialize(fStream), GetConnectionString)
        Catch ex As Exception
            MsgBox("Error opening: " & ex.Message)
        Finally
            If Not (fStream Is Nothing) Then fStream.Close()
        End Try
        Return tmp

    End Function
End Class

The error occurs trying to execute

  tmp = CType(myFormat.Deserialize(fStream), GetConnectionString)


Any ideas why I'm getting this error?





0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
isn't the article to which I linked you too solve all this?

I personnaly use this library. I have a single config file that is shared by about 5 applications and I have no problems at all.
0
 
LVL 20

Expert Comment

by:ElrondCT
Comment Utility
Do you have the class in both projects?
0
 
LVL 20

Expert Comment

by:ElrondCT
Comment Utility
Or, alternatively, reference the class using the other project's namespace.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
i have the class in a component that i reference in every project
0
 
LVL 20

Expert Comment

by:ElrondCT
Comment Utility
Sorry, Eric, I meant the question for johnnyg123. His error message sounded to me like he has no reference to the class in the second project. But your methodology is probably worthwhile to know about.
0
 

Author Comment

by:johnnyg123
Comment Utility
Eric,

The article looked like it was referrring to an asp project and mine was a client app


Have you used it in a client app as well?

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
I use it in a Windows application.
0
 

Author Comment

by:johnnyg123
Comment Utility
Eric,

Do you have an example you could share?


Thanks!
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
it's all in the article!

It would also be a bit difficult as I have modified the class.
0
 

Author Comment

by:johnnyg123
Comment Utility
hmmmm

unfortunately looks like it is in c# and I'm using vb.net

was hoping to see how to call from vb.net app


0
 
LVL 20

Expert Comment

by:ElrondCT
Comment Utility
johnnyg123, the problem may be that you're using different class names in the two projects. It sounds like you're saving the XML file in the class named MaintainCustAppSettings, but then you're retrieving it in the class GetConnectionString. The SOAP formatter includes in the XML the name of the class, so even though the members of the class have the same names and datatypes, it doesn't think the structure matches. Use the same class in both projects, and I think your problem should be resolved.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
Ok. It looks like this:

Option Strict On

' *** Application's settings class

' *** This class is using Rick Strahl base class
' *** http://www.west-wind.com/presentations/configurationclass/configurationclass.asp

'E.Moreau 2006.10.24 - NotInheritable as suggested by the code analysis (CA1052)
Public NotInheritable Class App

#Region " --- Members --- "

#Region " - Public - "

    <CLSCompliant(False)> Public Shared Configuration As AppConfig = New AppConfig
 
    Public Enum enuAppEnvironnement
        dbProd = 0
        dbTest = 1
        dbAccept = 2
    End Enum

#End Region ' - Public

#End Region ' --- Members

#Region " --- Constructors --- "

    Private Sub New()
        'As suggested by the Code Analysis (CA1053)
    End Sub

#End Region ' --- Constructors

#Region " --- Properties --- "

    Public Shared ReadOnly Property PathReports() As String
        Get
            Dim strPath As String

            Select Case mintAppEnvironnement
                Case enuAppEnvironnement.dbProd
                    strPath = Configuration.PathReportPROD
                Case enuAppEnvironnement.dbTest
                    strPath = Configuration.PathReportTEST
                Case Else
                    strPath = Configuration.PathReportPROD
            End Select

            If strPath.Length > 0 And Not strPath.EndsWith("\") Then
                Return strPath & "\"
            Else
                Return strPath
            End If
        End Get
    End Property

#End Region ' --- Properties

#Region " --- Methods --- "

    Public Shared Sub SaveSettings()
        Configuration.WriteKeysToConfig(Configuration.ConfigFileName)
    End Sub

#End Region ' --- Methods

End Class




<CLSCompliant(False)> _
Public Class AppConfig
    Inherits Westwind.Tools.wwAppConfiguration

#Region " --- Members --- "

#Region " - Public - "

    'Paramètres pour la BD
    Private mstrBDConnectionStringPROD As String = "Data Source=servername;Initial Catalog=dbname;UID=youruid;PWD=yourpwd;Application Name=yourappname"

    'Paramètres pour les rapports
    Private mstrPathReportPROD As String = "\\SRVFGL01\Applications\FGLApp2006\Reports\"
    Private mstrPathReportTEST As String = "\\SRVFGL01\Applications\FGLApp2006\Reports\"

    'Nom du fichier de configuration
    Private mstrConfigFileName As String = Application.StartupPath & "\FGLConfig.xml"

#End Region ' - Public

#Region " - Private - "

    'Liste des paramètres encryptés
    Private Const mkstrEncryptFields As String = "BDConnectionStringPROD"
    Private Const mkstrEncryptKey As String = "EnterYourEncryptionKeyHere"

#End Region ' - Private

#End Region ' --- Members

#Region " --- Constructors --- "

    Sub New()
        Me.SetEncryption(mkstrEncryptFields, mkstrEncryptKey)
        Me.ReadKeysFromConfig(ConfigFileName)
    End Sub

#End Region ' --- Constructors

    Public Property BDConnectionStringPROD() As String
        Get
            Return mstrBDConnectionStringPROD
        End Get
        Set(ByVal value As String)
            mstrBDConnectionStringPROD = value
        End Set
    End Property

    Public Property PathReportPROD() As String
        Get
            Return mstrPathReportPROD
        End Get
        Set(ByVal value As String)
            mstrPathReportPROD = value
        End Set
    End Property

    Public Property PathReportTEST() As String
        Get
            Return mstrPathReportTEST
        End Get
        Set(ByVal value As String)
            mstrPathReportTEST = value
        End Set
    End Property

    Friend Property ConfigFileName() As String
        Get
            Return mstrConfigFileName
        End Get
        Set(ByVal value As String)
            mstrConfigFileName = value
        End Set
    End Property

End Class
0
 

Author Comment

by:johnnyg123
Comment Utility
ElRondCT,

I created a new project with the class and all is well.



Thanks!


Eric,

Thanks so much for your help as well!


I hope you are both ok with me splitting the points between you

0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
>>I hope you are both ok with me splitting the points between you

no problem for me
0
 
LVL 20

Expert Comment

by:ElrondCT
Comment Utility
That's fine. I'm glad we were able to help.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now