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 :)

Here is some code that I have been using to save my images into a MS Access Database with ASPX vb.net.

The html code looks like this. It is to upload a picture and add title and description to it.
[code language=”vb”]
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h1>
Image Upload Information</h1>
<p style="text-align: left">

<table>
<tr>
<td style="width: 100px">
&amp;nbsp; Image :&amp;nbsp;</td>
<td style="width: 100px">
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp; Title &amp;nbsp;&amp;nbsp; :&amp;nbsp;</td>
<td style="width: 100px">
<asp:TextBox ID="Tbtitle" runat="server" Width="376px">Title Here</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp; Description :&amp;nbsp;</td>
<td style="width: 100px">
<asp:TextBox ID="description" runat="server" Height="88px" TextMode="MultiLine" Width="384px">Description Here</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp;Location :&amp;nbsp;</td>
<td style="width: 100px">
<asp:TextBox ID="location" runat="server" Width="376px">Location Here</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp; Tags :&amp;nbsp;</td>
<td style="width: 100px">
<asp:TextBox ID="tags" runat="server" Width="376px">Tags Here</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp;Width :&amp;nbsp;<br />
</td>
<td style="width: 100px">
<asp:TextBox ID="width" runat="server" Width="40px">1024</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
&amp;nbsp;&amp;nbsp; Height :&amp;nbsp;</td>
<td style="width: 100px">
<asp:TextBox ID="height" runat="server" Width="40px">768</asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="Button1" runat="server" Text="Upload Image" /></td>
</tr>
</table>
<br />
&amp;nbsp;
<br />
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</p>
</asp:Content>
[/code]
In the code behind page the following code is there. When you click the button it will upload the image to the MS Access Database and it will show the image on the page in the literal1

[code lang=”vb”]
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wService As com.www.imgStore = New com.www.imgStore
Dim myFile As HttpPostedFile = FileUpload1.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
Dim myData(nFileLen) As Byte
myFile.InputStream.Read(myData, 0, nFileLen)
Dim ms As IO.MemoryStream = New IO.MemoryStream(myData)
Dim img As Drawing.Image = convertImg(ms)
img = resizeImage(img, width.Text.Trim &amp; "x" &amp; height.Text.Trim)
Dim bytes() As Byte = imgToBytes(img)
Dim ret As String = wService.storeImage(Tbtitle.Text, description.Text, location.Text, tags.Text, width.Text, height.Text, Date.Now, bytes)
Literal1.Text = "http://www.yoursite.com/imgGrabing.aspx?id=" &amp; ret &amp; "<br/>" &amp; bytes.Length &amp; " Bytes Uploaded<br/><img src=""imgGrabing.aspx?id=" &amp; ret &amp; """>"
wService.Dispose()
ms.Dispose()
img.Dispose()
End Sub
[/code]

This is the code to convert the image.
[code language=”vb”]
Public Function convertImg(ByVal imgL As IO.MemoryStream) As System.Drawing.Image
Dim memstream As IO.MemoryStream = New IO.MemoryStream
Dim icf() As Drawing.Imaging.ImageCodecInfo = Drawing.Imaging.ImageCodecInfo.GetImageEncoders
Dim encps As Drawing.Imaging.EncoderParameters = New Drawing.Imaging.EncoderParameters(1)
encps.Param(0) = New Drawing.Imaging.EncoderParameter(Drawing.Imaging.Encoder.Quality, 100)
Dim btmp As Drawing.Bitmap = Drawing.Bitmap.FromStream(imgL)
btmp.Save(memstream, icf(1), encps)
btmp.Dispose()
btmp = Nothing
Dim img As Drawing.Image = Drawing.Bitmap.FromStream(memstream)
Return img
End Function
[/code]

Move the image over into a Byte() is done here:
[code language=”vb”]
Public Function imgToBytes(ByVal bmp As Drawing.Image) As Byte()
Dim ms As New IO.MemoryStream
bmp.Save(ms, Drawing.Imaging.ImageFormat.Jpeg)
Dim abyt(ms.Length – 1) As Byte
ms.Seek(0, IO.SeekOrigin.Begin)
ms.Read(abyt, 0, ms.Length)
Return abyt
End Function
[/code]

When I save the image, I resize it to a decent size to store in the database, so that I dont have to worry about resizing the images first before uploading.
[code language=”vb”]
Public Function resizeImage(ByVal img As Drawing.Image, ByVal size As String) As Drawing.Image
Dim oImg As Drawing.Image = img
Dim width As Integer = size.Split("x")(0)
Dim height As Integer = size.Split("x")(1)
Dim oThumbNail As Drawing.Image = New Drawing.Bitmap(width, height, oImg.PixelFormat)
Dim oGraphic As Drawing.Graphics = Drawing.Graphics.FromImage(oThumbNail)
oGraphic.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
oGraphic.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
oGraphic.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
Dim oRectangle As Drawing.Rectangle = New Drawing.Rectangle(0, 0, oThumbNail.Width, oThumbNail.Height)
oGraphic.DrawImage(oImg, oRectangle)
oImg.Dispose()
Return oThumbNail
End Function
[/code]

I have created a webservice to save the images, because I use it also to upload still images from my PTZ camera and it just connects to the webservice and stores the images.
[code language=”vb”]
<WebMethod()> _
Public Function storeImage(ByVal cameraid As Integer, ByVal preset As Integer, ByVal bits() As Byte) As Boolean
saveImg(cameraid, preset, Date.Now, bits)
Return True
End Function

Public Function saveImg(ByVal Cameraid As Integer, ByVal preset As Integer, ByVal picTimeStamp As Date, ByVal picImg As Byte()) As Boolean
Try
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
Dim oleDBConn As New Data.OleDb.OleDbConnection(strConn)
oleDBConn.Open()
Dim oleDBAdapter As Data.OleDb.OleDbDataAdapter = New Data.OleDb.OleDbDataAdapter("Select * From Pictures", strConn)
Dim oleDBcb As Data.OleDb.OleDbCommandBuilder = New Data.OleDb.OleDbCommandBuilder(oleDBAdapter)
Dim ds As Data.DataSet = New Data.DataSet
oleDBAdapter.MissingSchemaAction = Data.MissingSchemaAction.AddWithKey
oleDBAdapter.Fill(ds, "Pictures")
Dim dsRow As Data.DataRow = ds.Tables(0).NewRow
dsRow.BeginEdit()
dsRow("Cameraid") = Cameraid
dsRow("Preset") = preset
dsRow("picTimeStamp") = picTimeStamp
dsRow("picBinary") = picImg
dsRow.EndEdit()
ds.Tables(0).Rows.Add(dsRow)
oleDBAdapter.Update(ds.Tables(0))
ds.AcceptChanges()
oleDBConn.Dispose()
oleDBcb.Dispose()
oleDBAdapter.Dispose()
Return True
Catch ex As Exception
Return False
End Try
End Function
[/code]

The Access Database structure I used is:
ImgID:AutoNumber
PicTimeStamp: Date/Time
picBinary:Ole Object
CameraID:Number
Preset:Number

Hope this will get you going in the right direction and start to save your Images to Database using vb.net and MS Access

One of the things I often do with my website is populate a Dropdownlist1 with information from a MYSQL database. Here is an example code which I use to do that:
[code language=”vb”]Dim myConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString
Dim conn As MySqlConnection = New MySqlConnection(myConnectionString)
Dim cmd As MySqlCommand = New MySqlCommand(myConnectionString)
Dim sqlString As String = Nothing
Dim myConnection As New MySqlConnection(myConnectionString)
Dim myAdapter As MySqlDataAdapter = New MySqlDataAdapter(sqlString, myConnection)
Dim DS As DataSet = New DataSet

myAdapter.SelectCommand.CommandText = "select ID,MyDescription from Mydropdowntable"
myAdapter.Fill(DS)
Dim RText As String = "[Please Select]"
Me.Dropdownlist1.Items.Clear()
If DS.Tables(0).Rows.Count > 0 Then
For i As Integer = 0 To DS.Tables(0).Rows.Count – 1
Me.Dropdownlist1.Items.Insert(0, New ListItem(DS.Tables(0).Rows(i).Item(0).ToString, DS.Tables(0).Rows(i).Item(0).ToString))
Next
Else
RText = "Nothing Available"
End If
Me.Dropdownlist1.Items.Insert(0, New ListItem(RText, "0"))

myAdapter.Dispose()
myConnection.Dispose()
DS.Dispose()[/code].
I am connecting to a MYSQL database and are using Devart .Net Database connection with VS2008

You have to import the following at the beginning:
[code language=”vb”]Imports System.Data
Imports CoreLab.MySql[/code].

SEO Powered by Platinum SEO from Techblissonline