473,624 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using a function instead of web.config to store connectionstrin g

Hi,

I would appreciate if someone could explain this behaviour, and maybe offer
a better solution.

I have been working with the GridView control. And SqlDataSource. It works
great if I do:
<asp:SqlDataSou rce ConnectionStrin g="yada yada yada" etc etc />.

I can hook up a GridView to the sqldatasource and view/edit/add records.

But this isn't very secure.
I saw that I could do:
ConnectionStrin g="<$ point_to_web.co nfig key >"
It also works. And I can do some weak encryption of the web.config.

But I have a function that decrypts a strongly encrypted ConnectionStrin g,
so I wanna use that.

I found out that I could do:

ConnectionStrin g="<%# GetConnStr() %>"

However, that only works if I in the page_load do:
Databind()

But now I can't do any edit's in the GridView. And if I remove the
Databind(), (or even wrap it in a "if not ispostback") I get a
"connectionstri ng not initialized" error message.

So in my page_load I now do
if me.gridview1.sq ldatasource <> GetConnStr() then
me.gridview1.sq ldatasource <> GetConnStr()
endif

but I don't think it's "clean" and it might get me into trouble later ? Like
the DataBind() that screwed up my editing capabilities.

/jim
Mar 1 '06 #1
3 2324
Jim,

It's a much longer way around but you may want to bind an object to the grid
view instead. There was an article on doing this in the January Visual
Studio Magazine and I gave it a try. It works wonderfully. I used the
ObjectDataSourc e for my grid. It required creating an object to bind to and
using Generics.List to create a list of said items. But it gave me the
ability to use all the non-programmatic grid controls (as long as my object
exposed the proper methods). Using this method you could connect to your
database any way you'd like.

If you don't get Visual Studio Magazine here are a couple of links to
different articles that show how to use the ObjectDataSourc e:

http://www.c-sharpcorner.com/Code/20...DataSource.asp

http://www.asp.net/QuickStart/aspnet...atasource.aspx

Neither of these articles use Generics like the Visual Studio Magazine
article did though. I think you can sign up to access it on their website,
www.visualstudiomagazine.com, they use a "Locator Code". The number for the
article is: VS0601JB_T

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
"Jim Andersen" <no****@nospam. dk> wrote in message
news:Ow******** ******@TK2MSFTN GP12.phx.gbl...
Hi,

I would appreciate if someone could explain this behaviour, and maybe
offer a better solution.

I have been working with the GridView control. And SqlDataSource. It works
great if I do:
<asp:SqlDataSou rce ConnectionStrin g="yada yada yada" etc etc />.

I can hook up a GridView to the sqldatasource and view/edit/add records.

But this isn't very secure.
I saw that I could do:
ConnectionStrin g="<$ point_to_web.co nfig key >"
It also works. And I can do some weak encryption of the web.config.

But I have a function that decrypts a strongly encrypted ConnectionStrin g,
so I wanna use that.

I found out that I could do:

ConnectionStrin g="<%# GetConnStr() %>"

However, that only works if I in the page_load do:
Databind()

But now I can't do any edit's in the GridView. And if I remove the
Databind(), (or even wrap it in a "if not ispostback") I get a
"connectionstri ng not initialized" error message.

So in my page_load I now do
if me.gridview1.sq ldatasource <> GetConnStr() then
me.gridview1.sq ldatasource <> GetConnStr()
endif

but I don't think it's "clean" and it might get me into trouble later ?
Like the DataBind() that screwed up my editing capabilities.

/jim

Mar 1 '06 #2
Hi Jim,

Since you're using 2.0, you don't have to reinvent the wheel! The encryption
function is built in for you to store connection strings securely.

Here's a great tip from the Tips and Tricks in this video:

http://download.microsoft.com/downlo...tips_final.wmv

Add your connection string to your web.config as normal. For example, here's
mine:

<connectionStri ngs>
<add name="Adventure Works_DataConne ctionString1" connectionStrin g="Data
Source=.\SQLEXP RESS;AttachDbFi lename=&quot;C: \Program Files\Microsoft SQL
Server\MSSQL.1\ MSSQL\Data\Adve ntureWorks_Data .mdf&quot;;Inte grated
Security=True;C onnect Timeout=30;User Instance=True"
providerName="S ystem.Data.SqlC lient" />
</connectionStrin gs>

Create a page to do the encryption/decryption:

<%@ Page Language="VB" %>
<%@ import namespace="Syst em.Web.Configur ation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<script runat="server">

Protected Sub EncryptConfig(B yVal bEncrypt As Boolean)
Dim path = "~/"
' Use the WebConfiguratio nManager to open
' the local web.config file
Dim config As Configuration = _
WebConfiguratio nManager.OpenWe bConfiguration( path)
' Get the connectionStrin gs section
' from the web.config file
Dim appSettings As ConfigurationSe ction = _
config.GetSecti on("connectionS trings")

If bEncrypt Then
' Encrypt the string using ProtectSection
appSettings.Sec tionInformation .ProtectSection _
("DataProtectio nConfigurationP rovider")
Else
'Decrypt the string using UnprotectSectio n
appSettings.Sec tionInformation .UnprotectSecti on()
End If
'Save the changes
config.Save()
End Sub
Protected Sub Button1_Click _
(ByVal sender As Object, ByVal e As System.EventArg s)
EncryptConfig(T rue)
End Sub

Protected Sub Button2_Click _
(ByVal sender As Object, ByVal e As System.EventArg s)
EncryptConfig(F alse)
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:sqldatasou rce id="SqlDataSour ce1" runat="server"
connectionstrin g="<%$ ConnectionStrin gs:AdventureWor ks_DataConnecti onString1
%>"
deletecommand=" DELETE FROM [Employee] WHERE [EmployeeID] =
@EmployeeID" insertcommand=" INSERT INTO [Employee] ([NationalIDNumbe r],
[ContactID], [LoginID], [ManagerID], [Title], [BirthDate], [MaritalStatus],
[Gender], [HireDate], [SalariedFlag], [VacationHours], [SickLeaveHours],
[CurrentFlag], [rowguid], [ModifiedDate]) VALUES (@NationalIDNum ber,
@ContactID, @LoginID, @ManagerID, @Title, @BirthDate, @MaritalStatus,
@Gender, @HireDate, @SalariedFlag, @VacationHours, @SickLeaveHours ,
@CurrentFlag, @rowguid, @ModifiedDate)"
providername="< %$
ConnectionStrin gs:AdventureWor ks_DataConnecti onString1.Provi derName %>"
selectcommand=" SELECT [EmployeeID], [NationalIDNumbe r],
[ContactID], [LoginID], [ManagerID], [Title], [BirthDate], [MaritalStatus],
[Gender], [HireDate], [SalariedFlag], [VacationHours], [SickLeaveHours],
[CurrentFlag], [rowguid], [ModifiedDate] FROM [Employee]"
updatecommand=" UPDATE [Employee] SET [NationalIDNumbe r] =
@NationalIDNumb er, [ContactID] = @ContactID, [LoginID] = @LoginID,
[ManagerID] = @ManagerID, [Title] = @Title, [BirthDate] = @BirthDate,
[MaritalStatus] = @MaritalStatus, [Gender] = @Gender, [HireDate] =
@HireDate, [SalariedFlag] = @SalariedFlag, [VacationHours] = @VacationHours,
[SickLeaveHours] = @SickLeaveHours , [CurrentFlag] = @CurrentFlag, [rowguid]
= @rowguid, [ModifiedDate] = @ModifiedDate WHERE [EmployeeID] = @EmployeeID"
<insertparamete rs>
</asp:sqldatasour ce>
<br />
&nbsp;<asp:butt on id="Button1" runat="server"
onclick="Button 1_Click" text="Encrypt" />
<asp:button id="Button2" runat="server" text="Decrypt"
onclick="Button 2_Click" /></div>
</form>
</body>
</html>

When you click the button, it'll rewrite your web.confg so it comes out like
this:

<connectionStri ngs
configProtectio nProvider="Data ProtectionConfi gurationProvide r">
<EncryptedDat a>
<CipherData>
<CipherValue>AQ AAANCMnd8BFdERj HoAwE/Cl+sBAAAAvr6cdq mKpka7y4ANmye/agQAAAACAAAAAAA DZgAAqAAAABAAAA Cbkzyh+9L59AVsW p1bn82FAAAAAASA AACgAAAAEAAAABp/xn/8HNqFjsuaLbZh9m fIAwAAR2T/I3+F9GlSFg7Xobu y5PgowpxKUztdni 9bmqi/JSgWtSxq4ziH+YQ Ro2FxYBhfdS54nG md01O7gEE+B1SPY A/bRn7pd6O+ZndTJ3 8CzOFj9vW17HWlQ O2QX13B7yiUVOiQ YJJwPdpjjCNZNT5 voItZEHrp5L9UWf +lI6Jpv/BTPDQBPH+OX9sq3 mpDdkfrySC/Jdt6pqhKnlab6Iy wRtQYvR4YTtnO0y xSnh9PM9CUbCIKE LWS9gu1mGAzQYVR m/RxRI4C1AXk8GoMw 9kr1o385JP0e6Vv qdlxdReGuWYfmBb AzxPKhPGp/YhQgvnuvz7g11Qn Mbq8YlYOjIOaXvN FYR9kZAVkbYzTy9 p0b9LlPegc5PtEv lTzyUXTN3lub52U B1bz5E8PpPr+E4T uu86N7c5dynXpNG ax+PsdzhZ/+/Dw93RLIVuPIod9V ielYRt8IiDQqI54 gmKq/ufxxri2vH0VnSMv j1eQHBtSyAM04Ws odoZS6SARQWnN6H PPNGmimPpY+nrKu MEEd0g6fv2YM//aa57Y351NzUaduh vXJIgjiRDjDLa0I wU9wCF0NKBibPJQ mJDj/kD0yY1ct8V3THqA LV9ptZp0Zh7Yosb tdN/xROca2H550cr2bp Kl7X5+oVcvp7pXZ k2tCm7V/rVIfUdb8YbDfWvN EO5RoWK7tJWiD8Z oGZ+5q4bQu8lMCu HPHMXhryyQ7kyhM rJWAjH3+WDulPaG RhS5v6A68lWeEol 0x5KfwDZ/gHWsFd5hc08pfar NInWbmnwnx8nf9Q VY8ub8xb8Ep8lQB xEUXEkmEPrSr7Pr hKGuDTImuDvwAtv rxI04oZ1hvXL6I7 FVAH0ZOgcLcnrbg flMmvJ8A1/3rllfNmE6nmoHyQ i9ZPuGq5Ro1cy66 GD53Tb++Q0IkErf Jj6qtiHhiJrYswz T1FHq+sdyV1j1JK cbiK2Bi2PtlTaKo 0ZMan3QqBhvSWnO yN7pguoKT62puRt vJgK5OVXZQ0mgi0 U+i5Eqp8+MT9hwb 4Hp9QPSEVBnzlJS tTOw8kTKXYtbA8O BAqMe3IG3Obshzs 7YQCcWJbXkY5GK+ BFDy2x80xbWSxmM 7qcL6BgWKOm6+wd 3OixeBLp16xQ4HG +Sc1AhK+t5Zq5mp 6mc508FeDpBA4HS oSqcBUPHF5PVStg QKEqMUX8Mz0g2BW yMYG15UbjvuBT7p miBYXChm+c7rSb+ FjW+rabpfuyNlnP 0raENQ6tUsJZr6M GKKzqQdiWwCVT9M cyU6YPBxNWoTwCK Zc+ueBk6YTkUAAA AH0zOlWabm9II/PQgC5sPjR5Lcko= </CipherValue>
</CipherData>
</EncryptedData>
</connectionStrin gs>
"Jim Andersen" <no****@nospam. dk> wrote in message
news:Ow******** ******@TK2MSFTN GP12.phx.gbl... Hi,

I would appreciate if someone could explain this behaviour, and maybe
offer a better solution.

I have been working with the GridView control. And SqlDataSource. It works
great if I do:
<asp:SqlDataSou rce ConnectionStrin g="yada yada yada" etc etc />.

I can hook up a GridView to the sqldatasource and view/edit/add records.

But this isn't very secure.
I saw that I could do:
ConnectionStrin g="<$ point_to_web.co nfig key >"
It also works. And I can do some weak encryption of the web.config.

But I have a function that decrypts a strongly encrypted ConnectionStrin g,
so I wanna use that.

I found out that I could do:

ConnectionStrin g="<%# GetConnStr() %>"

However, that only works if I in the page_load do:
Databind()

But now I can't do any edit's in the GridView. And if I remove the
Databind(), (or even wrap it in a "if not ispostback") I get a
"connectionstri ng not initialized" error message.

So in my page_load I now do
if me.gridview1.sq ldatasource <> GetConnStr() then
me.gridview1.sq ldatasource <> GetConnStr()
endif

but I don't think it's "clean" and it might get me into trouble later ?
Like the DataBind() that screwed up my editing capabilities.

/jim

Mar 1 '06 #3

"Ken Cox - Microsoft MVP" <BA**********@h otmail.com> skrev i en meddelelse
news:ev******** ******@TK2MSFTN GP10.phx.gbl...
The encryption function is built in for you to store connection strings
securely.

Here's a great tip from the Tips and Tricks in this video:

http://download.microsoft.com/downlo...tips_final.wmv


Hi Ken,

Thanks for answering,

Yes I am aware of the built-in ProtectedConfig urationProvider s.

From Overview of Protected Configuration:
http://msdn2.microsoft.com/en-us/lib...as(VS.80).aspx
"Both providers offer strong encryption of data"

Sounds good.

But I also read:
Building Secure ASP.NET Applications: Authentication, Authorization, and
Secure Communication

http://msdn.microsoft.com/library/en...SecNetch12.asp

And read about the DPAPI, and got to the part:
"The machine store approach is easier to develop because it does not require
user profile management. However, unless an additional entropy parameter is
used, it is less secure"

And I seemed to run into the terms "improves security" and "adds extra
security" and "easily decodable" which I found pretty "fluffy". And I
couldn't find a description of just how strong the built-in encryption (from
your example) really is (or is not).

Most of the documentation focused on "how to" or "walkthroug h"s, as the
first topic, instead of focusing on the techniques strengths and weaknesses.

I also was told by Microsoft that the Access database security was
"unbreakabl e" but now I can download a util that reveals all usernames and
passwords.

So I decided to roll my own encryption function. This way, I know what I am
getting. But I can see now, that I should be able to wrap it as a
ProtectedConfig urationProvider , and have asp.net use it, instead of the 2
built-in providers. Maybe I should look into that.

/jim
Mar 2 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4568
by: Shaun Ram | last post by:
Hi I have this constraint. A help would be greatly apprecitated. I have this Config file. <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="ITASCA"> <section name="ConnectionString" type="System.NamevaluesectionHandler,System" /> </sectionGroup>
2
1267
by: Kent Johnson | last post by:
Hi all, I have a lot of connection strings for a specific database on SQL-server in my application. Seen that there's a sqlConnectionString in Web.config. Can I use web.config to store the info about the connectionstring there? How do I call it from the application? /Kent J.
5
338
by: WFB | last post by:
Hi, I have an application with a couple of referenced assemblies. The referenced assemblies and my application all share a few configuration settings with the same name but different values. Is there a way to set up the config file to recognize this? Im thinking <section name> elements, but am not having much luck. Thanks, Joe
2
2405
by: WFB | last post by:
Hi I have an application with a couple of referenced assemblies. The referenced assemblies and my application all share a few configuration settings with the same name but different values. Is there a way to set up the config file to recognize this? Im thinking section name elements, but am not having much luck. Lets say the project has a StoreLocator assembly, a ProductGuide assembly and the main web site. All three have a value in...
17
2444
by: Davíð Þórisson | last post by:
now in my web I have some global variables to be used in many different subpages, in the old ASP I simply loaded a variables.asp file into memory using the eval() function. Now I'd like to use XML but what method would I use to load the entries from the xml file into memory and make them quickly accessible globally in the web code? Just need to know what functions specifically I should start reading about! Thx
3
602
by: Tim Gallivan | last post by:
Hi all, I think read somewhere (but I can't find it ... note to self: must get new filing system ...) that there is a workaround so that an app.config can have multiple keys with the same name or something of the like. What I require is the ability to point at a development or live database without changing any existing code in my multiple DLL / single form project. <add key="dtacollect.ConnectionString"...
0
1594
by: Shaun Ram | last post by:
Hi, I have this constraint. A help would be greatly appreciated. I have this Config file. <?xml version="1.0" encoding="utf-8" ?> <configuration> <configsections> <sectionGroup name="mainsection"> <section name="ConnectionString" type="System.NamevaluesectionHandler,System" /> </sectiongroup>
1
1430
by: ginkim | last post by:
Is there a way to grab the connectionstring value from the web.config in another project? I created a DataAccess layer to store my typed dataset and it automatically created settings.settings and app.config. The settings.settings grab the connectionstring from app.config. The problem I have is that when I publish a website that accesses the dataset, it imports the DataAccess.dll into its bin folder. From here, it's impossible for me to...
5
6515
by: Radu | last post by:
Hi. In a repeater I have as ItemTemplate the following, among others, and everything works great: <asp:SqlDataSource ID="LocationSqlDataSource" SelectCommand="SELECT blah-blah-blah" EnableCaching="True" ConnectionString="<%$ ConnectionStrings:OrderingProcess %>" CacheDuration="60" FilterExpression="ID = {0}" RunAt="server">
0
8238
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8174
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8624
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8336
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2607
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.