Solved

Reading app settings from an xml file

Posted on 2006-11-20
18
315 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 5
18 Comments
 
LVL 20

Accepted Solution

by:
ElrondCT earned 250 total points
ID: 17982258
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 70

Assisted Solution

by:Éric Moreau
Éric Moreau earned 250 total points
ID: 17983020
0
 

Author Comment

by:johnnyg123
ID: 17988549
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 70

Expert Comment

by:Éric Moreau
ID: 17988605
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
ID: 17988649
Do you have the class in both projects?
0
 
LVL 20

Expert Comment

by:ElrondCT
ID: 17988666
Or, alternatively, reference the class using the other project's namespace.
0
 
LVL 70

Expert Comment

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

Expert Comment

by:ElrondCT
ID: 17988823
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
ID: 17989199
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
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 17989409
I use it in a Windows application.
0
 

Author Comment

by:johnnyg123
ID: 17989607
Eric,

Do you have an example you could share?


Thanks!
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 17989696
it's all in the article!

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

Author Comment

by:johnnyg123
ID: 17989735
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
ID: 17989896
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 70

Expert Comment

by:Éric Moreau
ID: 17989926
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
ID: 17990363
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 70

Expert Comment

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

no problem for me
0
 
LVL 20

Expert Comment

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

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
DataGridView / get bound table name? 8 51
VB6 calling COM DLL written in Visual Studio 2003 6 57
Intermittent OleDbConnection Error 20 52
EMAIL RANGES BASED ON CURRENT TIME 12 39
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

732 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