<?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>Bill Rowell &#187; C#</title>
	<atom:link href="http://www.billrowell.com/category/development/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.billrowell.com</link>
	<description>Rumblings of Code,  and Then Some...</description>
	<lastBuildDate>Thu, 02 Feb 2012 00:08:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>SqlCacheDependency and Query Notifications</title>
		<link>http://www.billrowell.com/2011/11/19/sqlcachedependency-and-query-notifications/</link>
		<comments>http://www.billrowell.com/2011/11/19/sqlcachedependency-and-query-notifications/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 21:22:20 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=1007</guid>
		<description><![CDATA[There&#8217;s a lot of scattered information out there on how to configure ASP.NET applications to leverage Microsoft SQL Server&#8217;s Query Notification and Service Broker services for caching in ASP.NET applications. The two best step by step tutorials I&#8217;ve found online are: http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/ http://dimarzionist.wordpress.com/2009/04/01/how-to-make-sql-server-notifications-work/ Both of those articles should get you started for sure. I ran [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a lot of scattered information out there on how to configure ASP.NET applications to leverage Microsoft SQL Server&#8217;s Query Notification and Service Broker services for caching in ASP.NET applications.  The two best step by step tutorials I&#8217;ve found online are:</p>
<p><a href="http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/">http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/</a></p>
<p><a href="http://dimarzionist.wordpress.com/2009/04/01/how-to-make-sql-server-notifications-work/">http://dimarzionist.wordpress.com/2009/04/01/how-to-make-sql-server-notifications-work/</a></p>
<p>Both of those articles should get you started for sure.  I ran into issues keeping our application from crashing after a period of time though while leveraging Query Notifications for caching in a few of my sites.  The biggest issue I found was that I would see the following exception in our logs:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp charp">
When using SqlDependency without providing an options value, SqlDependency.Start() <br/>must be called prior to execution of a command added to the SqlDependency instance.</pre>
</div>
</div>
<p>Never did quite get a handle on what was going on here.  I did figure out though that I could always find this in my Application log around the time that exception was thrown:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp charp">
The query notification dialog on conversation handle '{A1FB449B-DEB3-E011-B6D2-002590198D55}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8470</Code><Description>Remote service has been dropped.</Description></Error>'.
</pre>
</div>
</div>
<p>So, does this mean that I called SqlDependency.Stop() and now queued notifications aren&#8217;t going to be delivered.  Are these critical errors that keep the application from coming back?  I&#8217;ve read that a lot of the Query Notification messages you see in the log aren&#8217;t critical errors and can be ignored.  I can&#8217;t ignore the timing of this error and the exception being thrown above though.</p>
<p>Anyway, I finally decided to pull this stuff out of our application until I get a better handle on what&#8217;s going on.  The last straw was that I was trying to sync some database changes during a maintenance period and I couldn&#8217;t get them to sync because of a bunch of these SQL Query Notification issues.  As I write this, I can&#8217;t even get my database back online as I&#8217;m waiting for ALTER DATABASE SET SINGLE_USER to complete (approaching 3 hours!!!).  As I keep waiting, my Application log keeps filling up with the following Query Notification messages:</p>
<p><strong>Query notification delivery could not send message on dialog &#8216;{FE161F6A-D6B3-E011-B6D2-002590198D55}.&#8217;. Delivery failed for notification &#8216;﻿<qn:QueryNotification xmlns:qn="http://schemas.microsoft.com/SQL/Notifications/QueryNotification" id="1530017" type="change" source="database" info="restart" database_id="5" sid="0x1F59122ACF8727448DA988D041A1D484"><qn:Message>85addbaa-ce66-431d-870f-d91580a7480a;d527d584-9fd4-4b13-85bc-87cb6c2e166f</qn:Message></qn:QueryNotification>&#8216; because of the following error in service broker: &#8216;The conversation handle &#8220;FE161F6A-D6B3-E011-B6D2-002590198D55&#8243; is not found.&#8217;.<br/><br />
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.</strong></p>
<p>I had a response to a post I made on the ASP.NET Forum and it was suggested that with all the cached items in the system, that SQL Server really could not catch up.  This is a problem because not only does it slow the entire system down, but when you have to cycle the SQL Server service itself, it takes forever for the system to come back up because all of the notifications get requeued or something.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2011/11/19/sqlcachedependency-and-query-notifications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Determine if Amazon S3 Object Exists with ASP.NET SDK</title>
		<link>http://www.billrowell.com/2010/12/21/determine-if-amazon-s3-object-exists-with-asp-net-sdk/</link>
		<comments>http://www.billrowell.com/2010/12/21/determine-if-amazon-s3-object-exists-with-asp-net-sdk/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 16:44:46 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[Amazon Web Services]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=854</guid>
		<description><![CDATA[After my earlier posts on invalidating Amazon CloudFront objects, I thought it would be important to see if an Amazon S3 object existed before trying to invalidate it. With the 1,000 request limit on invalidation requests before Amazon charges you for them, this seemed to be a prudent thing to do. So, I turned to [...]]]></description>
			<content:encoded><![CDATA[<p>After my earlier posts on invalidating Amazon CloudFront objects, I thought it would be important to see if an Amazon S3 object existed before trying to invalidate it.  With the 1,000 request limit on invalidation requests before Amazon charges you for them, this seemed to be a prudent thing to do.  So, I turned to the Amazon Web Services ASP.NET SDK to help me out with it.  This is what I came up with:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp charp">
public bool S3ObjectExists(string bucket, string key)
{
    using (AmazonS3Client client = new AmazonS3Client(this._awsAccessKey, this._awsSecretKey))
    {
        GetObjectRequest request = new GetObjectRequest();
	request.BucketName = bucket;
	request.Key = key;

	try
	{
		S3Response response = client.GetObject(request);
		if (response.ResponseStream != null)
		{
			return true;
		}
	}
	catch (AmazonS3Exception)
	{
		return false;
	}
	catch (WebException)
	{
		return false;
	}
	catch (Exception)
	{
		return false;
        }
    }
    return false;
}
</pre>
</div>
</div>
<p>I decided that if I found a valid ResponseStream on the S3Response, then I had a valid object.  All I&#8217;m checking on is the object key itself, i.e. an image path in S3.  Another note here is I&#8217;m checking for three different exceptions but returning false for all 3.  The reason I have this coded this way for now is I wanted to see what different exceptions GetObject might throw depending on what was wrong with the request.  This was done purely for testing purposes and will probably be changed in the future.  For instance, I discovered that AmazonS3Exception is thrown when the object isn&#8217;t there.  WebException is thrown when the object is there, but the request cannot be completed.  I&#8217;m still in the testing phase with this, but I hope this helps some other Amazon Web Service developers out there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/12/21/determine-if-amazon-s3-object-exists-with-asp-net-sdk/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Adding an Image to a PDF Document Using C# and PdfSharp</title>
		<link>http://www.billrowell.com/2010/12/13/adding-an-image-to-a-pdf-document-using-c-and-pdfsharp/</link>
		<comments>http://www.billrowell.com/2010/12/13/adding-an-image-to-a-pdf-document-using-c-and-pdfsharp/#comments</comments>
		<pubDate>Mon, 13 Dec 2010 20:15:57 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PDF Generation]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=757</guid>
		<description><![CDATA[A while back I wrote about generating PDF documents using PdfSharp. It worked really well for us to generate invoices and purchase orders on the fly to ship orders and receive product. One must on our invoices was showing our corporate logo on our invoices that went out to our customers. We also wanted to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://pdfsharp.com/PDFsharp/"><img src="http://www.billrowell.com/wp-content/uploads/2010/12/PDFsharplogo.gif" alt="" title="PDFsharplogo" width="64" height="64" class="alignnone size-full wp-image-759" style="float: left; margin-right: 10px;"/></a></p>
<p>A while back I wrote about generating PDF documents using <a href="http://pdfsharp.com/PDFsharp/">PdfSharp</a>.  It worked really well for us to generate invoices and purchase orders on the fly to ship orders and receive product.  One must on our invoices was showing our corporate logo on our invoices that went out to our customers.  We also wanted to do the same on the documents we generated for our purchase orders so that our vendors could easily identify our company when processing the order.  This turned out to be a snap using PdfSharp.</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
void AddLogo(XGraphics gfx, PdfPage page, string imagePath, int xPosition, int yPosition)
{
    if (!File.Exists(imagePath))
    {
	throw new FileNotFoundException(String.Format("Could not find image {0}.", imagePath));
    }

    XImage xImage = XImage.FromFile(imagePath);
    gfx.DrawImage(xImage, xPosition, yPosition, xImage.PixelWidth, xImage.PixelWidth);
}

try
{
    PdfDocument doc = new PdfDocument();
    PdfPage page = doc.AddPage();

    XGraphics gfx = XGraphics.FromPdfPage(page);

    AddLogo(gfx, invoice, "pathtoimage", 0, 0);
}
catch (Exception)
{
    // Handle exception
}
</pre>
</div>
</div>
<p>The arguments to DrawImage on the XGraphics object specify an XImage object, the starting position of the image (0, 0 in this case), and the dimensions of the image.  You can get the dimensions easily from the PixelWidth and PixelHeight properties (the Width and Height properties can be used, but are deprecated) of the XImage object.</p>
<p>Then call the AddLogo() method above to draw your image in the document.  Positioning and image dimensions are important to get correct otherwise the image won&#8217;t draw properly in your document.  Keep track of where you place your logo when drawing text or additional images on your document as well.  If you don&#8217;t keep track of positioning from element to element, you&#8217;ll actually draw over previous elements.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/12/13/adding-an-image-to-a-pdf-document-using-c-and-pdfsharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Inferring SqlDbType via Reflection</title>
		<link>http://www.billrowell.com/2010/12/08/c-inferring-sqldbtype-via-reflection/</link>
		<comments>http://www.billrowell.com/2010/12/08/c-inferring-sqldbtype-via-reflection/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 20:47:16 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=734</guid>
		<description><![CDATA[Today, I was looking for a way to take a string representation of a SqlDbType, i.e. System.Data.SqlDbType.VarChar and actually return the enumeration value (System.Data.SqlDbType is an enumeration of valid SQL data types like VarChar, Char, Int, etc.). Of course I could have done something like: public static SqlDbType GetSqlDbType(string sqlDbType) { switch (sqlDbType) { case [...]]]></description>
			<content:encoded><![CDATA[<p>Today, I was looking for a way to take a string representation of a SqlDbType, i.e. System.Data.SqlDbType.VarChar and actually return the enumeration value (System.Data.SqlDbType is an enumeration of valid SQL data types like VarChar, Char, Int, etc.).  Of course I could have done something like:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
public static SqlDbType GetSqlDbType(string sqlDbType)
{
    switch (sqlDbType)
    {
	case "varchar":
		return SqlDbType.VarChar;
	case "char":
		return SqlDbType.Char;
	case "int":
		return SqlDbType.Int;
	case "bigint":
		return SqlDbType.BigInt;
	default:
		throw new Exception(String.Format("{0} is either an unknown or unsupported SqlDbType.", sqlDbType));
    }
}
</pre>
</div>
</div>
<p>The drawback to this solution is that I would need a giant switch statement for all of the possible SqlDbType possibilities.  Plus, what if for some magical reason, a new one is added?  So I turned to Google to help me find a more elegant example, and <a href="http://bytes.com/topic/c-sharp/answers/271986-infer-sqldbtype-enumeration-member-via-reflection">I found what I was looking for</a>:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
SqlDbType sdt = (SqlDbType)Enum.Parse(typeof(SqlDbType), "VarChar", true);
</pre>
</div>
</div>
<p>This allows you to find the SqlDbType value you are looking for by using reflection on the SqlDbType enumeration.  Nice!  Of course, I wanted a more complete solution for my needs, so I came up with something like this (based on the first example):</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
public static SqlDbType GetSqlDbType(string sqlDbType)
{
    if (!String.IsNullOrEmpty(sqlDbType))
    {
	try
	{
	    string hintText = sqlDbType.Substring(sqlDbType.LastIndexOf(".") + 1);

	    SqlDbType sdt = (SqlDbType)Enum.Parse(typeof(SqlDbType), hintText, true);
	    return sdt;
	}
	catch (ArgumentException)
	{
	    throw new Exception(String.Format("{0} is an unknown SqlDbType.", sqlDbType));
	}
	catch (Exception e)
	{
	    throw e;
	}
    }

    throw new Exception("Provided value for SqlDbType was null or empty.");
}
</pre>
</div>
</div>
<p>This lets us do a couple of important things.  First, it allows for support of the complete namespace for a SqlDbType, i.e. System.Data.SqlDbType.VarChar <strong>AND</strong> just VarChar.  Second, it lets us catch important errors like an unknown SqlDbType value that is passed in to GetSqlDbType.</p>
<p>That&#8217;s it!  Enjoy!  If anyone has any questions or comments, you know what to do&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/12/08/c-inferring-sqldbtype-via-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Invalidating Content on Amazon CloudFront with ASP.NET SDK</title>
		<link>http://www.billrowell.com/2010/12/02/invalidating-content-on-amazon-cloudfront-with-asp-net-sdk/</link>
		<comments>http://www.billrowell.com/2010/12/02/invalidating-content-on-amazon-cloudfront-with-asp-net-sdk/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 19:36:34 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[Amazon Web Services]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=686</guid>
		<description><![CDATA[I&#8217;m working on integrating some of Amazon&#8217;s Web Services into out eCommerce platform. I&#8217;ve been working on performance enhancements on and off for the last year and content delivery is the last big step for us. Getting started on S3 and CloudFront was pretty easy, but I ran into some issues when updating content in [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.billrowell.com/wp-content/uploads/2010/12/logo_aws.gif" alt="" title="logo_aws" width="164" height="60" class="alignnone size-full wp-image-788" style="float: left; margin: 5px 15px 15px 0;" /></p>
<p>I&#8217;m working on integrating some of Amazon&#8217;s Web Services into out eCommerce platform.  I&#8217;ve been working on performance enhancements on and off for the last year and content delivery is the last big step for us.  Getting started on S3 and CloudFront was pretty easy, but I ran into some issues when updating content in our S3 buckets.  Luckily, Amazon added the ability to do this at the end of August.  Since we use ASP.NET, I&#8217;ve started to work with their .NET SDK.  Turns out, its pretty easy to invalidate some content.</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
public bool InvalidateContent(string distributionId, List&lt;string&gt; files)
{
    AmazonCloudFrontClient client = new AmazonCloudFrontClient(Settings.AWSAccessKey, Settings.AWSSecretKey);

    PostInvalidationRequest request = new PostInvalidationRequest();
    InvalidationBatch batch = new InvalidationBatch();

    batch.Paths = files;
    batch.CallerReference = GetHttpDate();

    request.InvalidationBatch = batch;
    request.DistributionId = distributionId;

    PostInvalidationResponse response = client.PostInvalidation(request);
    if (!String.IsNullOrEmpty(response.RequestId))
    {
	bool bInProgress = true;
	while (bInProgress)
	{
	    GetInvalidationRequest getReq = new GetInvalidationRequest();
	    getReq.DistributionId = distributionId;
	    getReq.InvalidationId = response.Id;

	    GetInvalidationResponse getRes = client.GetInvalidation(getReq);
	    bInProgress = getRes.Status.Equals("InProgress");

	    if (bInProgress)
	    {
		Thread.Sleep(Settings.AmazonWaitTime);
	    }
	}
    }
    else
    {
	return false;
    }

    return true;
}
</pre>
</div>
</div>
<p>InvalidateContent expects a CloudFront Distribution ID and a list of S3 files to invalidate.  References to the static Settings class is just a class that reads in configuration settings from a configuration file, be it App.config or any configuration file you wish to set up.  Basic values to store are your AWS Access Key, AWS Settings Key, and a wait time value before requesting information from Amazon again.  There is also a method GetHttpDate(), which just returns:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
</pre>
</div>
</div>
<p>InvalidateContent() will make a PostInvalidationRequest (which is part of the ASP.NET AWS SDK) through an AmazonCloudFrontClient object.  If this request is successfully posted, Amazon will return you a RequestId value that you can use to poll for the completion of your request. Keep in mind that you can only invalidate 1,000 S3 objects a month.  After that Amazon will start to charge you $0.005 per object invalidated.  This is per file, not per invalidation request.  Hopefully you found this helpful!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/12/02/invalidating-content-on-amazon-cloudfront-with-asp-net-sdk/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.NET SQLCacheDependency with SQL Query Notifications</title>
		<link>http://www.billrowell.com/2010/09/23/asp-net-sqlcachedependency-with-sql-query-notifications/</link>
		<comments>http://www.billrowell.com/2010/09/23/asp-net-sqlcachedependency-with-sql-query-notifications/#comments</comments>
		<pubDate>Thu, 23 Sep 2010 13:28:11 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=659</guid>
		<description><![CDATA[I&#8217;m going to make this quick and dirty. I&#8217;ve set up my ASP.NET web applications to leverage SQLCacheDependency with SQL Server 2005 Query Notifications. The setup process takes a some time and debugging can be tricky. But the payoff can be enormous. The bottom line is that the performance increase on page load times is [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to make this quick and dirty.  I&#8217;ve set up my ASP.NET web applications to leverage SQLCacheDependency with SQL Server 2005 Query Notifications.  The setup process takes a some time and debugging can be tricky.  But the payoff can be enormous.  The bottom line is that the performance increase on page load times is well worth the effort, especially for data that doesn&#8217;t change all that often.  I found it really useful for caching product data on my eCommerce sites, especially as the number of products in the system grew to over 5,000.  However, I always seem to miss a step when when configuring my SQL Server 2005 databases; so this post is for my own reference, but if it helps someone else out there, even better.</p>
<p>The original article I used as a basis for configuring my applications is at the url below:</p>
<p><a href="http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/">http://www.simple-talk.com/sql/t-sql-programming/using-and-monitoring-sql-2005-query-notification/</a></p>
<p>Follow the steps there and you&#8217;re good to go.  Especially use the SQL Profiler debug steps at the bottom of the article if you get tripped up.  One thing that I always had to do with my databases to get everything to work properly was execute the following query:</p>
<div class="wp_syntax">
<div class="code">
</div>
<pre class="csharp csharp">
use &lt;dbname&gt;
EXEC dbo.sp_changedbowner @loginame = N'&lt;dbuser&gt;', @map = false
</pre>
</div>
<p>Make sure you use this caching technique responsible though.  The Query Notifications can use up processing power so only cache data that you know will give your application a performance bump.  Also beware of memory usage as you cache more and more data.  You could end up caching so much data your application needs to restart often and that could cause slow page load times.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/09/23/asp-net-sqlcachedependency-with-sql-query-notifications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easily Cause StackOverflow Exception in ASP.NET Web Application</title>
		<link>http://www.billrowell.com/2010/03/19/easily-cause-stackoverflow-exception-in-asp-net-web-application/</link>
		<comments>http://www.billrowell.com/2010/03/19/easily-cause-stackoverflow-exception-in-asp-net-web-application/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 18:27:44 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=657</guid>
		<description><![CDATA[This is a short one, but since I can&#8217;t believe I&#8217;ve never managed to do this before, I thought I&#8217;d post a little tidbit on it. I threw a StackOverflow in one of my ASP.NET C# web applications today. Watching the request keep going for about 5 minutes, I checked the Event Log on the [...]]]></description>
			<content:encoded><![CDATA[<p>This is a short one, but since I can&#8217;t believe I&#8217;ve never managed to do this before, I thought I&#8217;d post a little tidbit on it.  I threw a StackOverflow in one of my ASP.NET C# web applications today.  Watching the request keep going for about 5 minutes, I checked the Event Log on the server.  There it was, StackOverflow exception.  Say, what?</p>
<p>How did I manage it?  Recursively add a control to its own control collection.  The .NET framework just freaks and the application pool just gets restarted after each exception kills the app.  Glad it didn&#8217;t take long to figure it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2010/03/19/easily-cause-stackoverflow-exception-in-asp-net-web-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Properties In a Active Directory Computer Object</title>
		<link>http://www.billrowell.com/2009/09/10/properties-in-a-active-directory-computer-object/</link>
		<comments>http://www.billrowell.com/2009/09/10/properties-in-a-active-directory-computer-object/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 15:49:14 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=638</guid>
		<description><![CDATA[I&#8217;m working on a project and I was curious about what properties Active Directory would return when search for computers with the DirectorySearcher class in C#. Basically, you can search an entire domain for known computers using something like: string domainName = "mydomain"; DirectoryEntry de = new DirectoryEntry(); de.Path = String.Format("LDAP://{0}", domainName); de.Username = "username"; [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on a project and I was curious about what properties Active Directory would return when search for computers with the DirectorySearcher class in C#.  Basically, you can search an entire domain for known computers using something like:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
string domainName = "mydomain";
DirectoryEntry de = new DirectoryEntry();
de.Path = String.Format("LDAP://{0}", domainName);
de.Username = "username";
de.Password = "password";

try
{
     DirectorySearcher ds = new DirectorySearcher();
     ds.Filter = "(&#038;ObjectCategory=computer)";
     SearchResultCollection results = ds.FindAll();

     foreach (SearchResult sr in results)
     {
             ResultPropertyCollection myResultPropColl;
             myResultPropColl = sr.Properties;
             foreach (string myKey in myResultPropColl.PropertyNames)
             {
                 string propString = String.Empty;
                 string tab = "    ";
                 Console.WriteLine("{0} = ", myKey);
                 foreach (Object myCollection in myResultPropColl[myKey])
                 {
                     Console.WriteLine("{0}{1}", tab, myCollection);
                 }
         }
     }
}
catch (Exception)
{
}
</pre>
</div>
</div>
<p>This code is basically borrowed from this <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.searchresult.properties.aspx">MSDN article</a>, but what I was originally after was what properties could I actually get at?  I wasn&#8217;t all that interested in the code.  Well, just running that code yielded me the following list of properties that you can access via a computer object from Active Directory:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
operatingsystem
countrycode
cn
lastlogoff
dscorepropagationdata
usncreated
objectguid
iscriticalsystemobject
serviceprincipalname
whenchanged
localpolicyflags
accountexpires
primarygroupid
badpwdcount
objectclass
instancetype
objectcategory
whencreated
lastlogon
useraccountcontrol
samaccountname
operatingsystemversion
samaccounttype
adspath
serverreferencebl
dnshostname
pwdlastset
ridsetreferences
logoncount
codepage
name
usnchanged
badpasswordtime
objectsid
distinguishedname
</pre>
</div>
</div>
<p>For my purposes, I wanted to find out operating system information, so the operatingsystem and operatingsystemversion properties woulded nicely for me.  But, there you go, all of the properties you can access from a computer object in Active Directory.  I hope this is useful to someone else out there other than myself.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2009/09/10/properties-in-a-active-directory-computer-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create PDF Documents in C# on the Fly with PdfSharp</title>
		<link>http://www.billrowell.com/2009/08/10/create-pdf-documents-in-c-on-the-fly-with-pdfsharp/</link>
		<comments>http://www.billrowell.com/2009/08/10/create-pdf-documents-in-c-on-the-fly-with-pdfsharp/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 03:33:44 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PDF Generation]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=582</guid>
		<description><![CDATA[Recently I was doing a freelance project and had to find a way to create PDF documents on the fly in a C# application. I figured the best approach would be to create PDF files that could be printed, then archived for retrieval at a later date. There are definitely libraries out there that you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://pdfsharp.com/PDFsharp/"><img src="http://www.billrowell.com/wp-content/uploads/2010/12/PDFsharplogo.gif" alt="" title="PDFsharplogo" width="64" height="64" class="alignnone size-full wp-image-759" style="float: left; margin-right: 10px;"/></a></p>
<p>Recently I was doing a freelance project and had to find a way to create PDF documents on the fly in a C# application.  I figured the best approach would be to create PDF files that could be printed, then archived for retrieval at a later date.  There are definitely libraries out there that you can pay for to help with this, but I really wanted something that was OpenSource.  Luckily, I found <a href="http://www.pdfsharp.com/PDFsharp/">PdfSharp</a>!</p>
<p>You can pretty much draw anything for your PDF document using PdfSharp, shapes, text, images, etc. and you have full control over the fonts and the font weight.  This gives you a lot of flexibility in creating your custom PDF documents.  I highly recommend checking it out if you&#8217;re looking for a cheap (free is the best!) solution for your document creation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2009/08/10/create-pdf-documents-in-c-on-the-fly-with-pdfsharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remove ViewState From ASP.NET Page to Improve Performance</title>
		<link>http://www.billrowell.com/2009/06/17/remove-viewstate-from-asp-net-page-to-improve-performance/</link>
		<comments>http://www.billrowell.com/2009/06/17/remove-viewstate-from-asp-net-page-to-improve-performance/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 00:21:41 +0000</pubDate>
		<dc:creator>Bill</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.billrowell.com/?p=526</guid>
		<description><![CDATA[In a previous post, I eluded to the fact that I remove the ViewState from our ASP.NET pages to improve performance. I can&#8217;t take credit for coming up with the idea though. Originally, I got the idea and solution I wanted to implement by reading this article at EggHead Cafe. The solution I chose was [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous post, I eluded to the fact that I remove the ViewState from our ASP.NET pages to improve performance.  I can&#8217;t take credit for coming up with the idea though.  Originally, I got the idea and solution I wanted to implement by reading <a href="http://www.eggheadcafe.com/articles/20040613.asp">this article at EggHead Cafe</a>.  The solution I chose was to store the ViewState on the web server&#8217;s file system and reference the file in the page sent back to the client.  I&#8217;ll outline how I did that below.</p>
<p>The first thing you&#8217;ll want to do is create a new Page base class that inherits from System.Web.UI.Page so you can override some of its methods, namely SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium.  This will allow you to save the page&#8217;s ViewState to the file system and then re-load it on a post back.  Let&#8217;s start with saving the ViewState to the file system.</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
protected override void protectedSavePageStateToPersistenceMedium(object viewState)
{
	// Serialize the view state into a base-64 encoded string
        LosFormatter los = new LosFormatter();
	StringWriter writer = new StringWriter();
	los.Serialize(writer, viewState);

	string guid = NewGuid();
	string vsp = ViewStateFilePath(guid);

	// Save the string to disk
	StreamWriter sw = File.CreateText(vsp);
	sw.Write(writer.ToString());
	sw.Close();

	// Save the guid in a form field
	ClientScript.RegisterHiddenField("__VIEWSTATE_GUID", guid);
}
</pre>
</div>
</div>
<p>So, let&#8217;s step through what we&#8217;re doing here.  The first few lines of code, we&#8217;re serializing the view state.  Next, where we call</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
string uid = NewGuid();
</pre>
</div>
</div>
<p>We&#8217;re creating a new guid that we will use in creating the file name on the server for the actual value of the current view state.  NewGuid() just returns a new guid value from the System.Guid class.</p>
<p>Next, we need to create a path to where we&#8217;re going to store the file as well as its file name.  Now, you can do this any way you want as long as all of your files end up being unique.  You can&#8217;t go overwriting one guy&#8217;s view state with someone else&#8217;s.  Now I based mine on basically the guid appended with the current request path minus the extension and replacing the slashes with dashes.  So, my filename looks like:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
string fileName = guid + "-" + Path.GetFileNameWithoutExtension(Request.Path).Replace(
    "/", "-") + ".vs";
</pre>
</div>
</div>
<p>Where the guid was passed in to the function that I called to create the view state file path.</p>
<p>So now that we have a path to where we can write the file, we can go ahead and do so using the StreamWriter that we created.  Now, the last thing to do is spit out where we can find the view state to the client.  This is done by registering a hidden field with the client:</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
ClientScript.RegisterHiddenField("__VIEWSTATE_GUID", guid);
</pre>
</div>
</div>
<p>That GUID allows you to recall the proper file for the client when you need to access the ViewState.</p>
<p>So now you&#8217;ve persisted the view state to the file system.  Now all that&#8217;s left is to load it up when needed, which is done with LoadPageStateFromPersistenceMedium(), which is below.</p>
<div class="wp_syntax">
<div class="code">
<pre class="csharp csharp">
protected override object LoadPageStateFromPersistenceMedium()
{
	string guid = Request.Form["__VIEWSTATE_GUID"];
	if (guid == "")
		return null;
		// determine the file to access
	if (!File.Exists(ViewStateFilePath(guid)))
	{
		return null;
	}
	else
	{
		// open the file
		StreamReader sr = File.OpenText(ViewStateFilePath(guid));
		string viewStateString = sr.ReadToEnd();
		sr.Close();
		// deserialize the string
		LosFormatter los = new LosFormatter();
		return los.Deserialize(viewStateString);
	}
}
</pre>
</div>
</div>
<p>This approach gives you the ability to minimize the amount of data that you have to send over the wire to a client browser.  There are other solutions to this like storing the ViewState in memory, but I felt that it was a waste of resources if a ViewState might only be used once and then abandoned.  The one thing you&#8217;ll want to do is manage your saved ViewState files on your disk.  These files can get out of control, especially when you get a lot of visitor&#8217;s.  So what I did was just set up a Scheduled Task in Windows to clean up stored ViewState&#8217;s every three hours.  This works out pretty good since a ViewState really won&#8217;t be needed beyond that timeframe.</p>
<p>Anyway, I hope this solution helps some other C# ASP.NET developers out there.  It sure worked out great for me!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.billrowell.com/2009/06/17/remove-viewstate-from-asp-net-page-to-improve-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

