[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 321
  • Last Modified:

Reading app settings from an xml file

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
johnnyg123
Asked:
johnnyg123
  • 7
  • 6
  • 5
2 Solutions
 
ElrondCTCommented:
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
 
Éric MoreauSenior .Net ConsultantCommented:
0
 
johnnyg123Author Commented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Éric MoreauSenior .Net ConsultantCommented:
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
 
ElrondCTCommented:
Do you have the class in both projects?
0
 
ElrondCTCommented:
Or, alternatively, reference the class using the other project's namespace.
0
 
Éric MoreauSenior .Net ConsultantCommented:
i have the class in a component that i reference in every project
0
 
ElrondCTCommented:
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
 
johnnyg123Author Commented:
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
 
Éric MoreauSenior .Net ConsultantCommented:
I use it in a Windows application.
0
 
johnnyg123Author Commented:
Eric,

Do you have an example you could share?


Thanks!
0
 
Éric MoreauSenior .Net ConsultantCommented:
it's all in the article!

It would also be a bit difficult as I have modified the class.
0
 
johnnyg123Author Commented:
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
 
ElrondCTCommented:
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
 
Éric MoreauSenior .Net ConsultantCommented:
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
 
johnnyg123Author Commented:
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
 
Éric MoreauSenior .Net ConsultantCommented:
>>I hope you are both ok with me splitting the points between you

no problem for me
0
 
ElrondCTCommented:
That's fine. I'm glad we were able to help.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 7
  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now