INCLUDE_DATA

This weekend I was working on a new website template and wanted to make to have the general settings for the site stored in the web.config file. This gave me some challenges, but as usual I found a solution for it. ASP.NET provides a configuration system we can use to keep our applications flexible at runtime.

The <appSettings> element of a web.config file is a place to store connection strings, server names, file paths, and other website settings needed by an application to perform work. I want to use the same template for different websites, so I wanted a place where I can store all the website specific information and have them changeable from a web interface.

Some of the settings that I wanted in the appSettings are:

  • Google Analytic code
  • Adsense Code
  • Google Webmaster verify code
  • Domain name
  • Recaptcha Private and Public code to use for comment

I had added them first to my web.config file, however I couldn’t get it to work to save the changes to the file. So I created a second config file called settings.config and pointed in the web.config in tha appSetting element to that config file:

[code language=”vb”]

<appSettings configSource="settings.config" />

[/code]

In the settings.config file I added all the appSettings like this:

[code language=”vb”]

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="domain" value="diabetestype12.info" />
<add key="keyword" value="Diabetes Type 1 and 2" />
<add key="header" value="[meta name=’verify-v1′ content=’uZh/yCSVBvYTVP0dg0nYhaSAZBAPqNHQokswmg19CHs=’ /]|[meta name=’revisit’ content=’7 days’ /]" />
<add key="googleanalytics" value="UA-3718430-11" />
<add key="recaptchaPrivate" value="xxxQYAAAAAAFvUdhItSzUBfNzxxxxxx" />
<add key="recaptchaPublic" value="xxxYAAAAAACgd_3XrDokJsUFNAxxxxxxxy" /
</appSettings>

[/code]

To be able to save the information for the google webmaster verification code to the header <meta name=”verify-v1″ content=”uZh/yCSVBvYTVP0dg0nYhaSAZBAPqNHQokswmg19CHs=” />, I had to strip: <> and the vbCrLf (line return) to different characters that would be fine in the settings.config file. I change the < to [ and the > to ] and the vbCrLf to |. Here is the code I use to do that:

[code language=”vb”]

Function clean(ByVal str As String) As String
str = str.Replace("<", "[")
str = str.Replace(">", "]")
str = str.Replace(vbCrLf, "|")
str = str.Replace("""", "’")
Return str
End Function

[/code]

And the follow code to put the characters back in again:

[code language=”vb”]

Function ReFormat(ByVal str As String) As String
str = str.Replace("[", "<")
str = str.Replace("]", ">")
str = str.Replace("|", vbCrLf)
str = str.Replace("’", """")
Return str
End Function

[/code]

Make sure you add all the appSettings first in the settings.config file, as I have not made an error checking to see if the appSettings element are there. You could of course expand on that.

[code language=”vb”]

Imports System.Web.Configuration

Partial Class admin_wpexample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Me.TBDomain.Text = config.AppSettings.Settings.Item("domain").Value
Me.TBkeyword.Text = config.AppSettings.Settings.Item("keyword").Value
Me.TBHeader.Text = ReFormat(config.AppSettings.Settings.Item("header").Value)
End If
End Sub

End Class

[/code]

When you click the button save settings the following code will save the information to the settings.config file:

[code language=”vb”]

Protected Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
config.AppSettings.Settings.Remove("domain")
config.AppSettings.Settings.Add(New KeyValueConfigurationElement("domain", Me.TBDomain.Text))
config.AppSettings.Settings.Remove("keyword")
config.AppSettings.Settings.Remove("header")
config.AppSettings.Settings.Add(New KeyValueConfigurationElement("header", clean(Me.TBHeader.Text)))
config.Save()
End Sub

[/code]

The webpage looks like this:

[code language=”vb”]

<%@ Page Language="VB" MasterPageFile="~/MasterPageAdmin.master" validateRequest="false" AutoEventWireup="false" CodeFile="settings.aspx.vb" Inherits="admin_settings" title="Manage Settings" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table style="width:100%;">
<tr>
<td>
Domain Url:</td>
<td>
<asp:TextBox ID="TBDomain" runat="server" Width="287px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Title (keywords)</td>
<td>
<asp:TextBox ID="TBkeyword" runat="server" Width="287px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Header Meta</td>
<td>
<asp:TextBox ID="TBHeader" runat="server" Width="579px" Height="60px"
TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
&nbsp;</td>
<td>
<asp:Button ID="BtnSave" runat="server" Text="Save Settings" />
</td>
</tr>
</table>
<br />
</asp:Content>
[/code]

In order to be able to use in your text boxes “<” and not to get:

A potentially dangerous Request.Form value was detected from the client (ctl00$ContentPlaceHolder1$TBHeader=”<meta name=”verify-v…”).

You add validateRequest=”false” to the <%@ Page Language=”VB” …  %> line this will allow you to use those characters.

Now to use the stored appSettings: here an example how to add the stored meta tags to the header programmatically:

In the aspx Master page, where I want to set the Google Analytics code and the Google Webmaster Verification code programmatically I can now read from the web.config file the appSettings:

[code language=”vb”]

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Title</title>

<asp:ContentPlaceHolder ID="head" runat="server">
<asp:Literal ID="ltlheader" runat="server"></asp:Literal>
</asp:ContentPlaceHolder>
</head>

<body>
<form id="form1" runat="server">

<asp:Literal ID="LtlAnalytics" runat="server"></asp:Literal>
</form>

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src=’" + gaJsHost + "google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker(MyAnalytics);
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>

[/code]

In the code behind it looks like this:

[code language=”vb”]

Me.LtlAnalytics.Text = "<script type=""text/javascript"">var MyAnalytics=""" & System.Configuration.ConfigurationManager.AppSettings("GoogleAnalytics").ToString & """;</script>"

Me.ltlheader.Text = ReFormat(System.Configuration.ConfigurationManager.AppSettings("header").ToString)

[/code]

The same way you can have your Adsense code stored in the web.config file and you will be able to change the code for the adsense without having to go to the page to change it. You can have a literal on your page that you fill with the Adsense code or you do a replace text, if you read the text from database and want to insert the Adsense code. Just use a custom tage like #Adsense1#

[code language=”vb”]

Dim Adwords1 As String = ReFormat(System.Configuration.ConfigurationManager.AppSettings("Adwords1").ToString)
Me.LTLRelated.Text = Me.LTLRelated.Text.Replace("#Adwords1#", Adwords1)
[/code]

Have fun programming :)

SEO Powered by Platinum SEO from Techblissonline