?
Solved

Write to Web.Config file in ASP.Net using VB

Posted on 2014-07-15
20
Medium Priority
?
704 Views
Last Modified: 2014-07-18
I have an existing web site that uses the AppSettings in the web.config file to hold networkIDs of users that hold certain positions. The users are then references from code through the ConfigurationManager.AppSettings collection. My manager doesnt want me to keep these values in the web.config file. She proposed that I keep them in a table and then read the values when needed. What I would like to do is read the values once from the database and write the values to the AppSettings in the web.config file. Then I wouldnt have to change any of the code because it is being referenced everywhere. Does this seem like a good approach and how do I write to the web.config file in the AppSettings..

Example of web.config file with a couple of the AppSettings that I want to write
  <location allowOverride="true" inheritInChildApplications="true">
    <appSettings>
         <add key="BusMgr" value="CISSABC"/>
         <add key="RailMgr" value="CISSDEF"/>
         <add key="FinMgr" value="CISSGHI"/>
         <add key="SpecMgr" value="CISSJKL"/>
    </appSettings>
  </location>

As I said if I can write these values then I wont have to change any of the code that references the AppSettings.

Please help me if you can. I would appreciate it

Thanks
JK
0
Comment
Question by:jknj72
  • 9
  • 6
  • 3
  • +1
20 Comments
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40197687
Hi  jknj72;

To your statement, "My manager doesnt want me to keep these values in the web.config file.", so you are going to place them in the database but yet sill write them out to the web.config file. Seeming your manager doesn't want it in the web.config file do you think she will like this any better?

I would write a small function that would return the the values and call this function wherever you wish the values. In this way the values are in a table in the database and if she changes her mind in the future or you change database manufacturers you will only need to change it in one place.
0
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40198158
The easiest way to solve your issue is to use the file attribute to create a settings.config file with all your required keys as contents:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
          <add key="BusMgr" value="CISSABC"/>
          <add key="RailMgr" value="CISSDEF"/>
          <add key="FinMgr" value="CISSGHI"/>
          <add key="SpecMgr" value="CISSJKL"/>
 </appSettings>

Open in new window



then on your web config change the key to:
<appSettings file="relative file name for settings.config">
</appSettings>

Open in new window

and your code will still work as is, because what we are doing is move all your keys to a separate file.
For very simple sample code, check:
http://www.dotnetfunda.com/articles/show/969/external-appsetting-file-for-your-appsettings-in-config-file

By everywhere I assume that you need these values for other web servers (e.g. for load balance servers), if this is the case put the file on a network share in your database server and let all web servers reference this file in their web.config files  as follows:
<appSettings file="\\server\rootShare\settings.config">
</appSettings>

Open in new window


There is no real need for a database if these values are only access as configuration values for the servers.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 40199283
>As I said if I can write these values then I wont have to change any of the code that references the AppSettings.

Why bother with this at all then if you are still going to keep the values in web.config in defiance of your manager?
0
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

 

Author Comment

by:jknj72
ID: 40199286
I think Miguels approach best suit what I am trying to do. Miguel I am going to try this approach and see what I can do. Are you available at all during the day?  If not I understand but I may have some questions which is why Im asking.
Thanks everyone
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 40199306
Everyone will be able to see them if they are in web.config. And it is a website so I would assume it can be used at any time.

I would suggest you use this as a learning and use the opportunity to rewrite your code to write proper configuration management which can be used to pickup configuration from any source (in case your manager changes mind and wants you to store all configuration in encrypted xml files, for example).
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40199325
You may be creating a maintenance nightmare. I still think you should create a small function to retrieve the information/values from the database and return that to the caller. Then you can do a search on your project to replace the old code to get the info from the web config to a one liner and your done.
0
 

Author Comment

by:jknj72
ID: 40199465
Ok then I thnik if I can read all these values into a class module and then reference these values then that would work fine. I have the tables set up. I have a class that have the properties all set up and I have a Read event that fills the properties but I dont know where to instantiate the class and fill the properties and then when I need to reference one of these properties how can I do this without having to re-fill the class again ? I guess what Im trying to say is I dont wanna have to make a database call everytime I need one of the values.
For example. I have different web forms that get the value of one of these properties(that used to be in the AppSettings)

Old Ex: Dim FirstMgr As String = ConfigurationManager.AppSettings("FirstMgr")

How can I get the class value of FirstManager without having to query the DB everytime I need one of these values?
Also, where do I instantiate the class and how can I reference the values from this class without having to call the proc again?

Thanks guys!!
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40200168
Hi JK;

I have tested the code snippet below and it does work. Not knowing your column names in the db table I have selected my own. Add two classes as like the ones below to your project. The class KeyValues is used to load the data values to a list and keep the list available throughout the application life. The ofther NetworkValues is used to store the values locally that are in the database. Using this setup any time you what to get a value for example :

Dim FirstMgr As String = KeyValue.GetManager("FirstMgr")

Will replace this line of code

Dim FirstMgr As String = ConfigurationManager.AppSettings("FirstMgr")

In the web application Startup.vb place this line of code to load the values from the DB to the list.

KeyValue.LoadMgrs()

If you have any questions please let me know.

Public Class KeyValues

    ' Always available to the web application
    Private Shared mgrs As New List(Of NetworkValues)

    ' Return the value for the Key you are looking in  
    Public Shared Function GetManager(ByVal mgr As String) As String

        Return mgrs.Where(Function(m) m.Key = mgr).Select(Function(m) m.Value.ToString).FirstOrDefault()

    End Function

    ' Used to load the list from the database
    ' you can call this from the Startup.vb
    Public Shared Sub LoadMgrs()
        ' Load the table with data. I used Entity Framework
        ' but you can switch it to ADO.Net
        ' Create a DbContext, Change MyTableEntities to the DbContext class name
        Using db = New MyTableEntities()
            ' I called my table here MgrID. Needs to be changed to whatever you used
            mgrs = (From m In db.MgrID
                    Select New NetworkValues With
                    {
                        .Key = m.Key,
                        .Value = m.Value
                    }).ToList()
        End Using

    End Sub

End Class

' Class to use when loading the information from the database
Public Class NetworkValues
    Public Key As String
    Public Value As String
End Class

Open in new window

0
 

Author Comment

by:jknj72
ID: 40200265
Thanks Fernando, I initially wanted to do something like this I just didnt know how to do it. Just an FYI, it is a website using VB and not a web app. I am also using Oracle as a DB and using Stored Procs to get the data and using OracleDataAdapter with Dataset and DataTable objects with the DataReader to read the data.
I am gonna try to figure out the differences from what you have written  but I wont be able to get to it until tomorrow but you are "spot on" to what I have been trying to do and I appreciate your work.

Thanks again
0
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40200794
@Fernando: Notice that IIS7/7.5/8 and .NET framework use the file configuration approach all over the place.
File approach is useful for configuration purposes especially when the data is not changing very often (typically read-only) and you want to share it with all your production servers. Typical example I gave to managers is how often are you going to change your exchange server name ?

The SQL approach looks like over engineering a simple issue.
0
 

Author Comment

by:jknj72
ID: 40202218
Miguel,

I will not be using this for other web programs but youare correct in that the Managers will not be changing much at all but if they do I want to be able to change something somewhere(database or config file) once. I have looked at Fernandos code and I could use that but I dont know if I can translate that code(looks like C#) to my VB app? I think I may be able to figure out what to do with your code but I have to read the article first. Im not sure exactly what you mean by

"The easiest way to solve your issue is to use the file attribute to create a settings.config file with all your required keys as contents:"

How do I do this?
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40202850
Hi JK;

The code I posted above is in fact Visual Basic .Net code and NOT C#. If you place the classes KeyValues and NetworkValues into the App_Code folder and change the implementation of the method LoadMgrs() to correctly access the Oracle database and fill the list with the results of querying the database. Then in the subroutine Application_Start in the Global.asax file place the following line of code to fill the list at application startup.

 NetworkIDs.LoadMgrs()

And then any time you wish to find a manager you can execute this line of code.

Dim FirstMgr As String = KeyValue.GetManager("FirstMgr")

That is all that needs to be done.
0
 

Author Comment

by:jknj72
ID: 40202949
This sounds great Fernando I will try and implement. Maybe I thought the code was C# cause it looked a little different from what Im used to. I will put this into place first thing in the morning and let you know how it goes.

Thanks again
JK
0
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40203407
"How do I do this? "
My first post contains all the steps to create the file and use the attribute and the link provides a detail explanation if required.
0
 

Author Comment

by:jknj72
ID: 40204942
Fernando, this is what I came up with and Im hoping you can help me drive this home...

I created the 2 classes NetworkValues and KeyValues and in the KeyValues I have the routine for populating the data into the NetworkValues class. I think this may work but first, I dont have a Startup.vb do I? I am using a Website and not a web application so in that case where would I call this to populate the class...Second, the Getmanager function and the variable(?) for mgrs is foreign to me. I guess I have never used Entity Framework because Ive never seen this code before. Is there a way you can help me with this to work with what I have done in LoadMgrs(at the bottom of this post)?

Thanks for your help

Miguel, I spoke with my Manager and she thought doing it from the DB would be the best way for us to do it. Thank you for your help and your effort....

'Sub for loading class values
    Public Shared Sub LoadMgrs()

        'Define class to be populated with data
        Dim NetworkInfo As New NetworkValues

        'Create a command
        Dim cmdGetNetworkInfo As New OracleCommand
        cmdGetNetworkInfo = CreateStoredProcCommand("GETUSERSETTINGS") 'Pass proc name to GenericDbAccess class

        'Fill it's paramters
        cmdGetNetworkInfo.Parameters.Add(New OracleParameter("v_cursor", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
        cmdGetNetworkInfo.Connection.Open()

        'Read db with command
        Dim reader As OracleDataReader = Nothing
        reader = cmdGetNetworkInfo.ExecuteReader()

        'Stuff the data returned from the command into the TransSystem class
        While (reader.Read)
            NetworkInfo.NetID = reader("Network_ID").ToString
            NetworkInfo.Value = reader("Role_Desc").ToString
        End While

        reader.Close()
        cmdGetNetworkInfo.Connection.Close()
       
    End Sub
0
 

Author Comment

by:jknj72
ID: 40205048
Fernando,

Just wanted to let you know that I figured out where to call it and now the only thing I need is the call to get the NetowrkID of the Manager that the position I pass in is for. For instance if I call
Dim FirstMgr As String = ConfigurationManager.AppSettings("FirstMgr ")
I tried this call and it returned nothing even though I have the class fully populated? I looked at this
Private Shared mgrs As New List(Of NetworkValues)
and it said it has a count = 0 ? I know Im close but if you could help me tweak this I can put this to bed

Thanks
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 40205214
Hi JK;

This is the code in the KeyValues class that need to be modified

Public Class KeyValues

    '' Always available to the web application
    '' You can change the variable mgrs to what ever you like that fits your needs.
    '' But this needs to be here
    Private Shared mgrs As New List(Of NetworkValues)

    '' Other code stay as is.

    '' Sub for loading class values
    Public Shared Sub LoadMgrs()
    
      '' Just updated the Sub where code needed to change 
    
      '' Stuff the data returned from the command into the TransSystem class
        While (reader.Read)
            '' Create a new instance of NetworkInfo
            Dim netInfo As New NetworkInfo()
            '' Fill the properties of the new NetworkInfo object
            netInfo.NetID = reader("Network_ID").ToString
            netInfo.Value = reader("Role_Desc").ToString
            '' Load the new object into the List
            mgrs.Add(netInfo)
        End While
    
    End Sub
    
End Class

Open in new window

As far as your last post this was not the code I posted to find.

Dim FirstMgr As String = ConfigurationManager.AppSettings("FirstMgr ")

You should be going the following.

Dim FirstMgr As String =   KeyValues.GetManager("FirstMgr")

Try that out.
0
 

Author Comment

by:jknj72
ID: 40205254
Your a stud Fernando. I have never seen that code you wrote for returning the Manager. Very impressive and I will defnitely use that again. Thanks for teaching me something new and thank you for the code, it works like a charm and solved my issue.

Thanks again!!
0
 

Author Closing Comment

by:jknj72
ID: 40205256
great job!!!
0
 
LVL 64

Expert Comment

by:Fernando Soto
ID: 40205269
Not a problem JK, glad I was able to help.

To your statement, "I have never seen that code you wrote for returning the Manager.", that is a Linq to Object query and Linq can really cut down on coding.
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses

862 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