<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Adventures In Development &#187; Database</title>
	<atom:link href="http://www.adventuresindevelopment.com/category/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.adventuresindevelopment.com</link>
	<description>Web Development Tools, Ideas, Techniques and Resources</description>
	<lastBuildDate>Fri, 27 Aug 2010 04:11:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>How to Implement an ASP.NET Color Picker</title>
		<link>http://www.adventuresindevelopment.com/2009/06/12/how-to-implement-an-aspnet-color-picker/</link>
		<comments>http://www.adventuresindevelopment.com/2009/06/12/how-to-implement-an-aspnet-color-picker/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 20:28:18 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[360 WebCMS]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Content Management Systems]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Visual Basic]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=139</guid>
		<description><![CDATA[One of the components of the 360 Web Content Management System (website in progress) that I wanted to develop was an events calendar that allowed you to post events into color-coded categories. You can see a demo of it here. At first, I had it so that users would manually enter in a 6-character HTML [...]]]></description>
			<content:encoded><![CDATA[<p>One of the components of the <a href="http://www.360webcms.com/">360 Web Content Management System</a> (website in progress) that I wanted to develop was an events calendar that allowed you to post events into color-coded categories. You can see a demo of it <a href="http://cmsdemo.factor360.com/events.aspx">here</a>. At first, I had it so that users would manually enter in a 6-character HTML color code, but it was very non-intuitive for anyone who&#8217;s never worked with HTML before. Eventually I stumbled upon the <a href="http://www.karpach.com/ColorPickerDemo.aspx">ASP.NET Color Picker control</a>. It&#8217;s a custom ASP.NET control that you can add to a page much in the way that you can add a text box, radio buttons, or a drop down list.</p>
<p><span style="text-decoration: underline;"><strong>Here&#8217;s how to implement the ASP.NET Color Picker Control</strong></span></p>
<p><strong>(1) Download the library and add it to your project<br />
</strong></p>
<p>First, download the library from the ASP.NET Color Picker Control website. Make sure to download the latest binary release from the website. Currently that version is <a href="http://www.karpach.com/files/WebControls.v.1.4.10423.1-bin.zip">ASP.NET Color Picker v.1.4.10423.1 Binary</a>. Once you get the zip file, it will contain a library that you should extract to the /bin/ folder of your website.</p>
<p><strong>(2) Register the library on your page</strong></p>
<p>ASP.NET provides a set of standard controls that you can add to a page that start with the &#8220;ASP&#8221; prefix, such as &#8220;&lt;ASP:TextBox runat=&#8221;server&#8221; id=&#8221;txtBox&#8221; /&gt;. Any custom controls will have their own prefix that you specify by registering the library on the page. It&#8217;s another line of code that you add to the top of the page next to your page definition. It should look something like this:</p>
<p>&lt;%@ Register Assembly=&#8221;Karpach.WebControls&#8221; Namespace=&#8221;Karpach.WebControls&#8221; TagPrefix=&#8221;cc1&#8243; %&gt;</p>
<p><strong>(3) Add the control to your page</strong></p>
<p>Now that you have the library referenced, you can add the control to your page and make use of it.  For the purpose of this demo, I&#8217;m going to set the AutoPostBack property to true and run a function whenever the color is changed. This will show us the color that we picked inside of a label (also shown below) after we select a new color.</p>
<p>&lt;cc1:ColorPicker ID=&#8221;colorBackgroundColor&#8221; runat=&#8221;server&#8221; AutoPostBack=&#8221;true&#8221; OnColorChanged=&#8221;chngColor&#8221; /&gt;<br />
&lt;br /&gt;&lt;br /&gt;<br />
&lt;asp:Label ID=&#8221;lblResults&#8221; runat=&#8221;server&#8221; Text=&#8221;"&gt;&lt;/asp:Label&gt;</p>
<p><strong>(4) Create Your C# Function</strong></p>
<p>After we choose a color, we have to do something with it. With the ColorPicker control above, I&#8217;m using the OnColorChanged property to call the &#8220;chngColor&#8221; function, which in C# will look something like this. This will also demonstrate how to programmatically read the color chosen with the .Color property of the ASP.NET Color Picker Control</p>
<p>protected void chngColor(object sender, EventArgs e)<br />
{<br />
lblResults.Text = &#8220;&lt;div style=&#8217;background-color:#&#8221; + colorBackgroundColor.Color.Replace(&#8220;#&#8221;, &#8220;&#8221;) + &#8220;;height:50px;width:80px;text-align:center;padding-top:35px;&#8217;&gt;Sample Text&lt;/div&gt;&#8221;;<br />
}</p>
<p><strong>(5) Success</strong></p>
<p>So far, we&#8217;ve added the library to our project, registered the library on the page, added the control to the page, and done something with the color chosen by the user. Your page should look something like this:</p>
<p><a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/06/color-picker.jpg"><img class="alignnone size-full wp-image-140" title="color-picker" src="http://www.adventuresindevelopment.com/wp-content/uploads/2009/06/color-picker.jpg" alt="color-picker" width="567" height="398" /></a></p>
<p><a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/06/colorpickerdemo.zip">You can download my sample program here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/06/12/how-to-implement-an-aspnet-color-picker/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Make A Quick &amp; Easy Testing Environment for Joomla, Magento, WordPress and Other Open Source Web-Applications</title>
		<link>http://www.adventuresindevelopment.com/2009/05/28/make-a-quick-easy-testing-environment-for-joomla-magento-wordpress-and-other-open-source-web-applications/</link>
		<comments>http://www.adventuresindevelopment.com/2009/05/28/make-a-quick-easy-testing-environment-for-joomla-magento-wordpress-and-other-open-source-web-applications/#comments</comments>
		<pubDate>Thu, 28 May 2009 15:52:03 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[Content Management Systems]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Joomla]]></category>
		<category><![CDATA[Web Servers]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[hosting]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=116</guid>
		<description><![CDATA[Earlier this week, I wrote up a tutorial about how to make a testing environment for Joomla on the windows platform. I went through the instructions of setting up WAMP, making the database, and installing and configuring Joomla. It turns out there&#8217;s a much easier way to create a testing environment for Joomla, Magento, MySQL, [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this week, I wrote up a tutorial about <a href="http://www.adventuresindevelopment.com/2009/05/25/how-to-build-a-joomla-testing-environment-on-windows/">how to make a testing environment for Joomla on the windows platform</a>. I went through the instructions of setting up WAMP, making the database, and installing and configuring Joomla. It turns out there&#8217;s a much easier way to create a testing environment for Joomla, Magento, MySQL, Lamp, Moodle, WordPress, and all sorts of other open source software from a company called <a href="http://www.jumpbox.com">JumpBox</a>.</p>
<p>Essentially, they&#8217;ll give you an image of a virtual machine that contains the web-server software, as well as the server-side software you are testing. Everything will be pre-configured and ready to go. You&#8217;ll download a copy of the virtual machine, get it running with <a href="http://www.virtualbox.org/wiki/Downloads">VirtualBox</a>, and you&#8217;re good to go. Some of the virtual machines do cost money, but fortunately for us, the image for Joomla is <a href="http://demo.joomla.org/jumpbox.html">free for download from Joomla.org</a>.</p>
<p>Normally, I&#8217;d post a walk through of going through the process of installing the software and getting it up and going, but the folks at Joomla.org have already done that for us:</p>
<p><object width="400" height="225" data="http://vimeo.com/moogaloop.swf?clip_id=3385061&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=3385061&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /></object></p>
<p><a href="http://vimeo.com/3385061">Run Joomla in 5 min with JumpBox and VirtualBox</a> from <a href="http://vimeo.com/user1058430">Sean Tierney</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/05/28/make-a-quick-easy-testing-environment-for-joomla-magento-wordpress-and-other-open-source-web-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET Caching Techniques and Tools</title>
		<link>http://www.adventuresindevelopment.com/2009/05/21/aspnet-caching-techniques-and-tools/</link>
		<comments>http://www.adventuresindevelopment.com/2009/05/21/aspnet-caching-techniques-and-tools/#comments</comments>
		<pubDate>Thu, 21 May 2009 20:36:19 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=78</guid>
		<description><![CDATA[One of the most frequent criticisms of the ASP.NET stack is that it&#8217;s less efficient than some of its open-source counterparts. However, Microsoft has actually built in a lot of neat technology into the framework related to caching that allows for much more scalability than you might think. Not only is there caching support built [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most frequent criticisms of the ASP.NET stack is that it&#8217;s less efficient than some of its open-source counterparts. However, Microsoft has actually built in a lot of neat technology into the framework related to caching that allows for much more scalability than you might think. Not only is there caching support built directly into ASP.NET, but there are actually 3 different ways to cache an ASP.NET page and related data.</p>
<p><strong><span style="text-decoration: underline;">The Output Cache</span></strong></p>
<p>Using the output cache is probably the easiest implementation of caching in ASP.NET because all you need to do is add a line to your header. This will essentially cache the entire page. This way, when you load the page a second time, it will serve up the generated HTML of the cached page rather than by going through the page lifecycle and reloading the page.</p>
<p>Here&#8217;s the line of code you need to add  to the top of your .ASPX pages to implement the Output Cache:</p>
<p><code><strong>&lt;%@ OutputCache Duration="60" VaryByParam="*" %&gt;</strong></code></p>
<p>The &#8220;Duration&#8221; property indicates the number of seconds that the cache is good for. The &#8220;VaryByParam&#8221; property allows you to create separate cached versions of the page if it&#8217;s given different querystrings. For example, if you had a content management system where your Page&#8217;s looked like http://www.example.org/Default.aspx?PageID=85, you wouldn&#8217;t want that to show up the same as http://www.example.org/Default.aspx?PageID=92. They&#8217;re separate dynamic pages on the site that&#8217;s generated from the page. You don&#8217;t want to cache one sub-page then serve that cache for the entire site.</p>
<p><strong><span style="text-decoration: underline;">The Data Cache</span></strong></p>
<p>If you need to cache any sort of information in ASP.NET, such as a DataSet, a DataTable, or even a variable, you can use the ASP.NET DataCache. This works a lot like a session or application variable, but it has some added cache-related methods as well.</p>
<p><strong>Here&#8217;s how to store something in the cache in C#:</strong></p>
<p><code>DataTable dtToBeCached = new DataTable();<br />
Cache["CachedTable"] = dtToBeCached;<br />
</code><br />
<strong>Here&#8217;s how to turn that cached object back into a DataTable:</strong></p>
<p><code>DataTable dtToBeCached = new DataTable();<br />
if(Cache["CachedTable"] != null)<br />
{<br />
dtToBeCached = (DataTable)Cache["CachedTable"];<br />
}<br />
</code><br />
If you would like to remove something from the cache at a later time, you can simply use the Cache.Remove() method.</p>
<p><strong><span style="text-decoration: underline;">Partial Page Caching:</span></strong></p>
<p>There are some cases, such as when having a website that allows for users to login, that you would want to cache some parts of page but not the entireity. Let&#8217;s say that you cached a page where one user was authenticated and that paged was cached. Then, the authenticated version of that page would be served to everyone, including individuals that aren&#8217;t logged in. In that case, you don&#8217;t want to use the Output cache onthe entire page. </p>
<p>Instead, you want to make use of the DataCache to store shared data that would be frequently read from the database. The other strategy you can use in this case is to cache ASP.NET user controls that you develop. You cache these much in the same way that you would cache a page on a website, but instead you would add that code to the user control&#8217;s header instead of the page&#8217;s header.</p>
<p><strong><span style="text-decoration: underline;">You might also want to read these articles related to ASP.NET Caching:</span></strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa478965.aspx">ASP.NET Caching: Techniques and Best Practices</a> (MSDN)</li>
<li><a href="http://www.devcity.net/Articles/209/1/article.aspx">Advanced Caching Techniques in ASP.NET 2.0</a> (DevCity)</li>
<li><a href="http://www.beansoftware.com/ASP.NET-Tutorials/Caching-Techniques.aspx">Caching Techniques in ASP.NET 2.0</a> (Bean Software).</li>
<li><a href="http://www.4guysfromrolla.com/articles/022802-1.aspx">Caching with ASP.NET </a>(4 Guys From Rolla)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/05/21/aspnet-caching-techniques-and-tools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ 101: Getting Started with LINQ</title>
		<link>http://www.adventuresindevelopment.com/2009/05/18/linq-101-getting-started-with-linq/</link>
		<comments>http://www.adventuresindevelopment.com/2009/05/18/linq-101-getting-started-with-linq/#comments</comments>
		<pubDate>Mon, 18 May 2009 19:22:00 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=40</guid>
		<description><![CDATA[LINQ has been out for around a year now, but I never have been able to get away from using traditional SQL queries and data-access classes. Today, I thought I would try to do the &#8220;Hello World&#8221; equivalent of a LINQ program and share that with you today. So What&#8217;s LINQ? LINQ stands for Language [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ has been out for around a year now, but I never have been able to get away from using traditional SQL queries and data-access classes. Today, I thought I would try to do the &#8220;Hello World&#8221; equivalent of a LINQ program and share that with you today.</p>
<p><strong>So What&#8217;s LINQ?</strong></p>
<p>LINQ stands for Language Integrated Query. It&#8217;s a technology developed for Microsoft&#8217;s .NET platform which make it easier to query databases and XML files. Here&#8217;s how <a href="http://en.wikipedia.org/wiki/LINQ">Wikipedia describes LINQ</a>:</p>
<blockquote><p>Microsoft LINQ defines a set of proprietary query operators that can be used to query, project and filter data in arrays, enumerable classes, XML (XLINQ), relational database, and third party data sources. While it allows any data source to be queried, it requires that the data be encapsulated as objects. So, if the data source does not natively store data as objects, the data must be mapped to the object domain. Queries written using the query operators are executed either by the LINQ query processing engine or, via an extension mechanism, handed over to LINQ providers which either implement a separate query processing engine or translate to a different format to be executed on a separate data store (such as on a database server as SQL queries (DLINQ)). The results of a query are returned as a collection of in-memory objects that can be enumerated using a standard iterator function such as C#&#8217;s foreach.</p></blockquote>
<p><strong>Getting Started:</strong></p>
<p>Before we can do any LINQ queries, we must first have a data source to access it. To start out, I created a new ASP.NET/C# website in Visual Studio 2008. Then, I created a two table database using the built in version of SQL Express that comes with visual studio. One table called &#8220;Users&#8221; with an ID field, a username, a password, and then an &#8220;Account Type&#8221; feature which is a foreign key of the second table &#8220;AccountTypes&#8221;. The AccountTypes table simply has an ID field that&#8217;s the primary key then a &#8220;Title&#8221;. I went ahead and added some sample data into the database as well.</p>
<p><strong>The LINQ to SQL Class:</strong></p>
<p>After creating a database, the first step is to create a &#8220;LINQ to SQL&#8221; class. This class will map your class to the tables in the database. It&#8217;s actually an optional step, but doing so will allow you better control over the class. By doing this, you can rename tables and properties from within the class. To do this, Right click on the folder of your website in the Solution Explorer, and click &#8220;Add New Item&#8221;. Then pick out &#8220;LINQ to SQL Class&#8221;. Open the class after creating it.</p>
<p>The next step is to add your database tables to the &#8220;LINQ to SQL&#8221; class. Have your &#8220;LINQ to SQL&#8221; class file open in your main window, then in your database explorer, drag the tables you want to add to the class (in our case, users and accounttypes) over to the &#8220;LINQ to SQL&#8221; class.</p>
<p>At this point, you should have something that looks like this:</p>
<p><a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/linq-to-sql.jpg"><img class="size-full wp-image-41" title="linq-to-sql" src="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/linq-to-sql.jpg" alt="linq-to-sql" width="502" height="185" /></a></p>
<p>Before closing out of your DBML file / Linq to SQL class, I recommend that you give the class a new name. The default name is &#8220;DataClassesDataContext&#8221;, Let&#8217;s change that in the properties window to &#8220;UserContext&#8221;. At this point, you could implement a lot more of the sophisticated features that LINQ offers, but for now, we&#8217;ll leave it as is.</p>
<p><strong>Creating the Query:</strong></p>
<p>Now that we have our &#8220;LINQ to SQL&#8221; class made, The next thing we&#8217;ll want to do is create our query. We can just use the &#8220;Default.aspx&#8221; and &#8220;Default.aspx.cs&#8221; that came with our project for this part. Go to the PageLoad method of our Default.ASPX.CS file and we&#8217;ll start our coding there. The first thing we need to do is create an instance of the class we created:</p>
<p><code>UserContext thisContext = new UserContext();</code></p>
<p>The next thing we need to do is write our query. This will get all users from the users table that have an account type of &#8220;Admin&#8221;:</p>
<p><code>var UserResults = (from u in thisContext.Users<br />
where u.AccountType1.Title == "User"<br />
select u);<br />
</code></p>
<p>At this point, we have everything we need to do to make use of the database. The SQL isn&#8217;t generated and ran until we actually do something with the results, so let&#8217;s do something simple and write each username that is returned to the page:</p>
<p><code>foreach (var ThisUser in UserResults)<br />
{<br />
Response.Write(ThisUser.Username + "&lt;br/&gt;");<br />
}<br />
</code></p>
<p>And that&#8217;s really all it takes to get started with LINQ.  If all is well in the world and your code is as it should be you should get something that looks a lot like this:</p>
<p><a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/results.jpg"><img class="size-full wp-image-42" title="results" src="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/results.jpg" alt="results" width="387" height="277" /></a></p>
<p><a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/linq101.zip">Click here to download the example project I made (829 KB)</a></p>
<p>You might also want to read:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb397933.aspx">Getting Started with LINQ and C#</a> (Microsoft.com)</li>
<li><a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx">Using Linq to SQL by Scott Guthery</a> (ASP.NET)</li>
<li><a href="http://dotnetslackers.com/articles/csharp/IntroducingLINQ1.aspx">Introduction to LINQ</a> (DotNetSlackers)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/05/18/linq-101-getting-started-with-linq/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>360 WebCMS Feature Look: Multisite Management</title>
		<link>http://www.adventuresindevelopment.com/2009/05/16/360-webcms-content-management-feature-look-multisite-management/</link>
		<comments>http://www.adventuresindevelopment.com/2009/05/16/360-webcms-content-management-feature-look-multisite-management/#comments</comments>
		<pubDate>Sat, 16 May 2009 21:44:45 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[360 WebCMS]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Content Management Systems]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=31</guid>
		<description><![CDATA[I&#8217;ve spent the better part of the last 3 months developing the new version of our company&#8217;s content management system that&#8217;s called &#8220;360 WebCMS&#8221;. It&#8217;s a product that Factor 360 has and is used to develop all of our client websites. One of the cool features that I built into it was multi-site management. Essentially, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent the better part of the last 3 months developing the new version of our company&#8217;s content management system that&#8217;s called &#8220;360 WebCMS&#8221;. It&#8217;s a product that <a href="http://www.factor360.com/">Factor 360</a> has and is used to develop all of our client websites. One of the cool features that I built into it was multi-site management. Essentially, one copy of the CMS can power dozens of small websites. That way, when it&#8217;s time to update the software to add in new features or take care of a problem, there&#8217;s only one copy to update instead of 20. Each site has their own separate set of data that doesn&#8217;t cross paths with any other site on the system&#8217;s.</p>
<p>I thought I would give a shot at doing a screencast and demoing off the multi-site functionality of the system. I used <a href="http://www.screencast-o-matic.com/">Screencast-O-Matic</a> to make it (and I was very impressed with their solution).</p>
<p><iframe width=504 height=424 frameborder="0" scrolling="no" src="http://www.screencast-o-matic.com/embed?sc=cQhD2UeK2&#038;w=500&#038;np=0&#038;v=2"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/05/16/360-webcms-content-management-feature-look-multisite-management/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Write Your Own Database Access Class in C#</title>
		<link>http://www.adventuresindevelopment.com/2009/05/15/write-your-own-database-access-layer-in-c/</link>
		<comments>http://www.adventuresindevelopment.com/2009/05/15/write-your-own-database-access-layer-in-c/#comments</comments>
		<pubDate>Fri, 15 May 2009 14:30:04 +0000</pubDate>
		<dc:creator>Matthew Paulson</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.adventuresindevelopment.com/?p=22</guid>
		<description><![CDATA[If you use C# or VB.NET through the ASP.NET stack (or just as a desktop application) to connect to a  SQL database, you&#8217;ll have a few options. There&#8217;s the new entity data model from Microsoft, there&#8217;s also last year&#8217;s notion of LINQ. They both do a reasonably good job, but are sometimes on the over-kill [...]]]></description>
			<content:encoded><![CDATA[<p>If you use C# or VB.NET through the ASP.NET stack (or just as a desktop application) to connect to a  SQL database, you&#8217;ll have a few options. There&#8217;s the new <a href="http://msdn.microsoft.com/en-us/library/aa697428(VS.80).aspx">entity data model</a> from Microsoft, there&#8217;s also last year&#8217;s notion of <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx">LINQ</a>. They both do a reasonably good job, but are sometimes on the over-kill side for smaller projects. Sometimes you just want to run a SQL command and get back a DataTable or have a SqlCommand executed. If you&#8217;re a new developer, it&#8217;s especially good to learn &#8220;the hard way&#8221; of writing SQL Commands because then you&#8217;ll actually know what&#8217;s going on behind all of the time-saving activities that .NET can perform now of days.</p>
<p><strong>Here&#8217;s a tradition way to read data from a database and put it in a table. (There&#8217;s also the <a href="http://www.startvbdotnet.com/ado/sqlserver.aspx">Data Reader Method</a> that some would argue is more efficient)</strong></p>
<p><code> //create command<br />
SqlCommand cmdMyQuery = new SqlCommand("Select * From Users where username=@username");<br />
cmdMyQuery.Parameters.AddWithValue("@username", "Matt");</code></p>
<p>//Get connection string<br />
string ecmsConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;<br />
SqlConnection SQLDatabaseConnection = new SqlConnection(ecmsConnectionString);</p>
<p>//Perform Command<br />
cmdSQLQuery.Connection = SQLDatabaseConnection;<br />
DataSet dsPageInfo = new DataSet();<br />
SqlDataAdapter daPageInfo = new SqlDataAdapter(cmdSQLQuery);<br />
SQLDatabaseConnection.Open();<br />
daPageInfo.Fill(dsPageInfo);<br />
SQLDatabaseConnection.Close();<br />
DataTable dtResults = dsPageInfo.Tables[0];</p>
<p><strong>That&#8217;s a lot of code to do something that you&#8217;re probably going to do on a very regular basis. If you wanted to run a SQL command such as an INSERT, UPDATE or DELETE, you traditionally would have to do something like this:</strong></p>
<p><code> //create command<br />
SqlCommand cmdMyQuery = new SqlCommand("update users set Active=1 where username=@username");<br />
cmdMyQuery.Parameters.AddWithValue("@username", "Matt");</code></p>
<p><code>//get connection string<br />
string ECMSconnString = ConfigurationManager.ConnectionStrings["csWebCMS"].ConnectionString;<br />
SqlConnection SQLDatabaseConnection = new SqlConnection(ECMSconnString);</code><br />
<code><br />
//execute command<br />
CommandToExecute.Connection = SQLDatabaseConnection;<br />
SQLDatabaseConnection.Open();<br />
CommandToExecute.ExecuteNonQuery();<br />
SQLDatabaseConnection.Close();<br />
</code><br />
This isn&#8217;t nearly as bad as doing a SQL Select statement, but there&#8217;s an easier way to redo these two things. We can create a static class with two functions, run to do SQL Select statements, and one to do INSERTS, UPDATE&#8217;S, and DELETE&#8217;s. We want to do a static class with static methods because that mean a new copy of the class won&#8217;t be made each time it&#8217;s run, meaning that it&#8217;ll take less memory and be more efficient.</p>
<p><strong>Here&#8217;s what the code will look like:</strong></p>
<p><code>using System;<br />
using System.Data;<br />
using System.Data.SqlClient;<br />
using System.Configuration;<br />
using System.Web;<br />
///  Abstracts Database connectivity and provides SQL Injection Prevention Mechanism<br />
public static class DBUtils<br />
{<br />
///  Returns the results of a SQL Query in the form of a DataTable<br />
public static DataTable SQLSelect(SqlCommand cmdSQLQuery)<br />
{<br />
//Get connection string<br />
string conConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;<br />
SqlConnection SQLDatabaseConnection = new SqlConnection(conConnectionString);<br />
//Perform Command<br />
cmdSQLQuery.Connection = SQLDatabaseConnection;<br />
DataSet dsPageInfo = new DataSet();<br />
SqlDataAdapter daPageInfo = new SqlDataAdapter(cmdSQLQuery);<br />
SQLDatabaseConnection.Open();<br />
daPageInfo.Fill(dsPageInfo);<br />
SQLDatabaseConnection.Close();<br />
return dsPageInfo.Tables[0];<br />
}<br />
///  Executes a SQL Command<br />
public static void ExecuteSQLCommand(SqlCommand CommandToExecute)<br />
{<br />
//get connection sring<br />
string conConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;<br />
SqlConnection SQLDatabaseConnection = new SqlConnection(conConnectionString);<br />
//execute command<br />
CommandToExecute.Connection = SQLDatabaseConnection;<br />
SQLDatabaseConnection.Open();<br />
CommandToExecute.ExecuteNonQuery();<br />
SQLDatabaseConnection.Close();<br />
}<br />
}<br />
</code></p>
<p><strong>Now, when you want to run a SQL Select Command and put the results in a DataTable for use, you can just do this:</strong></p>
<p><code>SqlCommand cmdMyQuery = new SqlCommand("Select * From Users where username=@username");<br />
cmdMyQuery.Parameters.AddWithValue("@username", "Matt");<br />
DataTable dtResults = dbutils.SQLSelect(cmdMyQuery);<br />
</code></p>
<p><strong>If you want to run a command, just do this:</strong></p>
<p><code>SqlCommand cmdMyQuery = new SqlCommand("insert into users (username) VALUES (@username)");<br />
cmdMyQuery.Parameters.AddWithValue("@username", "Matt");<br />
DataTable dtResults = dbutils.ExecuteSQLCommand(cmdMyQuery);<br />
</code></p>
<p>Hopefully creating a data access class will make your coding experiences in .NET just a little bit easier. To download a copy of this class in C#, <a href="http://www.adventuresindevelopment.com/wp-content/uploads/2009/05/dbutils.cs">click here (1.86KB)</a>.</p>
<p>In the near future, I&#8217;m hoping to post about the C# code-generation tool that I created which works with class. Essentially, you point it at any table in the database, and it&#8217;ll give you full CRUD (Create, Read, Update Delete) functionality for any given row in that table. It makes data-access a heck of a lot easier.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.adventuresindevelopment.com/2009/05/15/write-your-own-database-access-layer-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
