<?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>jesal gadhia &#187; asp.net</title>
	<atom:link href="http://jesal.us/tag/aspnet/feed/" rel="self" type="application/rss+xml" />
	<link>http://jesal.us</link>
	<description></description>
	<lastBuildDate>Thu, 14 Jul 2011 18:51:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to parse WordPress RSS feed using LINQ</title>
		<link>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/</link>
		<comments>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 05:32:28 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=238</guid>
		<description><![CDATA[Here&#8217;s a code snippet of parsing a typical WordPress RSS feed using LINQ. Note, we have to skip the first image from the media element since that&#8217;s usually a gravatar of the author. Everything else is pretty straight forward. private void BindBlogFeed() { XDocument doc = XDocument.Load("http://blogworkseverytime.wordpress.com/feed/"); XNamespace content = "http://purl.org/rss/1.0/modules/content/"; XNamespace media = "http://search.yahoo.com/mrss/"; [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a code snippet of parsing a typical WordPress RSS feed using LINQ. Note, we have to skip the first image from the media element since that&#8217;s usually a gravatar of the author.</p>
<p>Everything else is pretty straight forward.</p>
<pre>
    private void BindBlogFeed()
    {
        XDocument doc = XDocument.Load("http://blogworkseverytime.wordpress.com/feed/");
        XNamespace content = "http://purl.org/rss/1.0/modules/content/";
        XNamespace media = "http://search.yahoo.com/mrss/";

        var query = (from feed in doc.Descendants("item")
                     orderby DateTime.Parse(feed.Element("pubDate").Value) descending
                     select new
                     {
                         Title = feed.Element("title").Value,
                         Description = HttpUtility.HtmlDecode(feed.Element("description").Value),
                         Content = HttpUtility.HtmlDecode(feed.Element(content.GetName("encoded")).Value),
                         Image = (from img in feed.Elements(media.GetName("content"))
                                  where img.Attribute("url").Value.Contains("gravatar") == false
                                  select img.Attribute("url").Value).FirstOrDefault() ?? "",
                         Link = feed.Element("link").Value,
                         Date = DateTime.Parse(feed.Element("pubDate").Value).ToShortDateString()
                     });

        lvFirstBlogFeed.DataSource = query.Take(1).ToList();
        lvFirstBlogFeed.DataBind();

        lvRemainingBlogFeed.DataSource = query.Skip(1).ToList();
        lvRemainingBlogFeed.DataBind();
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Send Templated Emails Using MailDefinition Object</title>
		<link>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/</link>
		<comments>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/#comments</comments>
		<pubDate>Sat, 25 Oct 2008 23:58:32 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=100</guid>
		<description><![CDATA[Recently I discovered a better way to format my email messages in ASP.NET using the MailDefinition object. It lets you to use an email template and define tokens which you want to replace in it. This helps keep the presentation and business layers clean &#038; seperate and lets the designers go in and edit the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I discovered a better way to format my email messages in ASP.NET using the MailDefinition object. It lets you to use an email template and define tokens which you want to replace in it. This helps keep the presentation and business layers clean &#038; seperate and lets the designers go in and edit the email templates without having to navigate the StringBuilder jungle.</p>
<p>Here&#8217;s how its done.</p>
<pre name="code" class="c-sharp:nogutter">
private void SendEmail(long customerID)
{
	Customer customer = CustomerData.GetCustomer(customerID);

	MailDefinition mailDefinition = new MailDefinition();
	mailDefinition.BodyFileName = "~/Email-Templates/Order-Confirmation.html";
	mailDefinition.From = "no-reply@my-site.com";

	//Create a key-value collection of all the tokens you want to replace in your template...
	ListDictionary ldReplacements = new ListDictionary();
	ldReplacements.Add("<%FirstName%>", customer.FirstName);
	ldReplacements.Add("<%LastName%>", customer.LastName);
	ldReplacements.Add("<%Address1%>", customer.Address1);
	ldReplacements.Add("<%Address2%>", customer.Address2);
	ldReplacements.Add("<%City%>", customer.City);
	ldReplacements.Add("<%State%>", customer.State);
	ldReplacements.Add("<%Zip%>", customer.Zip);

	string mailTo = string.Format("{0} {1} <{2}>", customer.FirstName, customer.LastName, customer.EmailAddress);
	MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, ldReplacements, this);
	mailMessage.From = new MailAddress("no-reply@my-site.com", "My Site");
	mailMessage.IsBodyHtml = true;
	mailMessage.Subject = "Order Confirmation";

	SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString(), 25);
	smtpClient.Send(mailMessage);
}
</pre>
<p>Your email template could be of any extension (txt, html, etc) as long as its in a text format. I personally like to keep it in HTML format so that we can preview the email template in a browser. Basically it&#8217;ll looks something like this -</p>
<pre name="code" class="html:nogutter">
Hello <%FirstName%> <%LastName%>,

Thank you for creating an account with us. Here are your details:

<%Address1%>,
<%Address2%>
<%City%>, <%State%> <%Zip%>

Thank You,
My Site
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Code Blocks Inside Master Pages</title>
		<link>http://jesal.us/2008/09/code-blocks-inside-master-pages/</link>
		<comments>http://jesal.us/2008/09/code-blocks-inside-master-pages/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 18:22:49 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[masterpages]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=96</guid>
		<description><![CDATA[Some time ago I kept getting this error in one of the projects I was working on: The Controls collection cannot be modified because the control contains code blocks (i.e. ). I spent quite some time trying to figure it out. Finally after hours of searching I found out that Code Blocks Inside Master Pages [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago I kept getting this error in one of the projects I was working on:</p>
<p><strong>The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).</strong></p>
<p>I spent quite some time trying to figure it out. Finally after hours of searching I found out that <a href="http://aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx" target="_blank">Code Blocks Inside Master Pages Cause Trouble</a>.</p>
<p>I was using code blocks inside the head tag of all the MasterPages to resolve paths at runtime:</p>
<pre>
&lt;link rel="stylesheet" href="&lt;%= ResolveUrl("~/myStyleSheet.css") %&gt;" type="text/css" /&gt;
&lt;script type="text/javascript" src="&lt;%= ResolveUrl("~/myJavaScript.js") %&gt;"&gt;&lt;/script&gt;
</pre>
<p>Fortunately <a href="http://aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx">Milan Negovan</a> proposed a quick workaround which saved a lot of time.</p>
<p>Basically, the workaround is to change the code blocks to data binding expressions (<%# ... %>). </p>
<pre>
&lt;link rel="stylesheet" href="&lt;%# ResolveUrl("~/myStyleSheet.css") %&gt;" type="text/css" /&gt;
&lt;script type="text/javascript" src="&lt;%# ResolveUrl("~/myJavaScript.js") %&gt;"&gt;&lt;/script&gt;
</pre>
<p>and adding this to the master page code behind:</p>
<pre name="code" class="csharp:nogutter">
protected override void OnLoad (EventArgs e)
{
  base.OnLoad (e);
  Page.Header.DataBind ();
}
</pre>
<p>Since HtmlHead ultimately derives from Control and everything that derives from Control has a DataBind() method, adding that one line above would force the header to resolve data binding expressions.</p>
<p>Thats it, that does the trick!</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/09/code-blocks-inside-master-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to setup an asp.net website on localhost</title>
		<link>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/</link>
		<comments>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/#comments</comments>
		<pubDate>Fri, 12 Sep 2008 22:35:32 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[iis]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=95</guid>
		<description><![CDATA[First lets start by setting up the site in IIS&#8230; 1.Open IIS by double-clicking on Control Panel->Administrative Tools->Internet Information Services 2.Right Click on Web Sites->Default Web Site 3.Click on Properties->Home Directory and choose the location of your website Now lets give the ASPNET account the appropriate permissions to access that directory&#8230; 4. Using My Computer [...]]]></description>
			<content:encoded><![CDATA[<p><strong>First lets start by setting up the site in IIS&#8230;</strong></p>
<p>1.Open IIS  by double-clicking on <strong>Control Panel->Administrative Tools->Internet Information Services</strong></p>
<p>2.Right Click on <strong>Web Sites->Default Web Site</strong></p>
<p>3.Click on <strong>Properties->Home Directory</strong> and choose the location of your website<br />
<img src="http://jesal.us/wp-content/uploads/sc1.jpg" /></p>
<p><strong>Now lets give the ASPNET account the appropriate permissions to access that directory&#8230;</strong> </p>
<p>4. Using My Computer or the Windows Explorer, navigate to the folder containing the website you choose in the previous step </p>
<p>5. Right click on the folder and and go to <strong>Properties->Security</strong></p>
<p>5. On the Security tab, click on <strong>Add</strong> to locate the ASPNET account<br />
<img src="http://jesal.us/wp-content/uploads/sc2.jpg" /></p>
<p>6. Click on <strong>Locations</strong> and select the local machine<br />
<img src="http://jesal.us/wp-content/uploads/sc3.jpg" /></p>
<p>7. Click on <strong>Advanced->Find Now</strong> to list all the user accounts on your local machine<br />
<img src="http://jesal.us/wp-content/uploads/sc4.jpg" /></p>
<p>8. Choose <strong>ASPNET</strong> and click on OK. (If you don&#8217;t see ASPNET account in there, go to step 11)</p>
<p>9. Return to the security tab. Select the ASPNET user account and check the <strong>Full Control</strong> checkbox under the allow column. Click OK.<br />
<img src="http://jesal.us/wp-content/uploads/sc5.jpg" /></p>
<p>10. Thats it! You should now be able to go to http://localhost/ in your browser window and see your website.</p>
<p><strong>If you don&#8217;t see an ASP.NET account in Step 8 then&#8230;</strong></p>
<p>11. Run &#8220;<strong>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ aspnet_regiis.exe -i -enable</strong>&#8221; in the command line window and then repeat steps 1 through 10.</p>
<p><strong>Following steps are optional. They help you configure your web project to automatically reference the local web-server when you run or debug a site instead of launching the built-in web-server itself&#8230;</strong></p>
<p>12. Open Visual Studio and select your web-project in the solution explorer, right click and select <strong>Property pages</strong>.</p>
<p>13. Select the <strong>Start Options</strong> from the left navigation, and under <strong>Server</strong> change the radio button value from &#8216;Use default Web server&#8217; to <strong>&#8216;Use custom server&#8217;</strong>. Then set the Base URL value to be: http://localhost/<br />
<img src="http://jesal.us/wp-content/uploads/sc6.jpg" /></p>
<p>Now, when you click on any page in the app and then hit F5 or Ctrl-F5, the IDE will use the local web-server instead of popping up its own.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Load &amp; Reference An Usercontrol From Code Behind</title>
		<link>http://jesal.us/2008/09/how-to-load-reference-a-user-control-from-code-behind/</link>
		<comments>http://jesal.us/2008/09/how-to-load-reference-a-user-control-from-code-behind/#comments</comments>
		<pubDate>Mon, 01 Sep 2008 21:56:30 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[usercontrols]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=93</guid>
		<description><![CDATA[First lets create a sample user control called MyControl for demonstration purposes public partial class _Controls_MyControl : System.Web.UI.UserControl { private string _myProperty; public string MyProperty { get { return _myProperty; } set { _myProperty = value; } } protected void Page_Load(object sender, EventArgs e) { } } Now register this control in the web.config &#60;pages&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>First lets create a sample user control called MyControl for demonstration purposes</p>
<pre name="code" class="csharp:nogutter">
public partial class _Controls_MyControl : System.Web.UI.UserControl
{
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
</pre>
<p>Now register this control in the web.config</p>
<pre name="code" class="xml:nogutter">
&lt;pages&gt;
  &lt;controls&gt;
    &lt;add tagPrefix="uc" tagName="MyControl" src="~/_Controls/MyControl.ascx"/&gt;
  &lt;/controls&gt;
&lt;/pages&gt;
</pre>
<p>Now this is the most important part, you have to reference your user control in the .aspx page to be able to access its partial class members -</p>
<pre name="code" class="xml:nogutter">
<%@ Reference Control="~/_Controls/MyControl.ascx" %>
</pre>
<p>Now finally lets instantiate and load the control from the code behind&#8230;</p>
<pre name="code" class="csharp:nogutter">
_Controls_MyControl myControl = (_Controls_MyControl)LoadControl("~/_Controls/MyControl.ascx");
myControl.MyProperty = "Hello World!!";
Page.Controls.Add(myControl);
</pre>
<p>That&#8217;s it</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/09/how-to-load-reference-a-user-control-from-code-behind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET Inline Tags</title>
		<link>http://jesal.us/2008/06/aspnet-inline-tags/</link>
		<comments>http://jesal.us/2008/06/aspnet-inline-tags/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 03:54:18 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=92</guid>
		<description><![CDATA[There are all sorts of different inline tags, and I haven&#8217;t found a place that explains them all in one place, so here is the quick and dirty&#8230; &#60;% &#8230; %&#62; The most basic inline tag, basically runs normal code: &#60;% if (User.IsInRole(&#8220;admin&#8221;)) { %&#62; You can see this &#60;% } else { %&#62; You [...]]]></description>
			<content:encoded><![CDATA[<p>There are all sorts of different inline tags, and I haven&#8217;t found a place that explains them all in one place, so here is the quick and dirty&#8230;</p>
<h1 style="text-align: center;">&lt;% &#8230; %&gt;</h1>
<p>The most basic inline tag, basically runs normal code:</p>
<blockquote><p>&lt;% if (User.IsInRole(&#8220;admin&#8221;)) { %&gt;<br />
You can see this<br />
&lt;% } else { %&gt;<br />
You are no admin fool!<br />
&lt;%} %&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/ms178135%28vs.80%29.aspx" target="_blank">http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx</a></p>
<h1 style="text-align: center;">&lt;%= &#8230; %&gt;</h1>
<p>Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable:</p>
<blockquote><p>The Date is now &lt;%= DateTime.Now.ToShortDateString() %&gt;<br />
The value of string1 is &lt;%= string1 %&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/6dwsdcf5%28VS.71%29.aspx">http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx</a></p>
<p>*note: &lt;%= is the equivalent of Response.Write() -  Courtesy of Adam from the US,thanks!</p>
<h1 style="text-align: center;">&lt;%# .. %&gt;</h1>
<p>Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:</p>
<blockquote><p>&lt;asp:Repeater ID=&#8221;rptMeetings&#8221; DataSourceID=&#8221;meetings&#8221; runat=&#8221;server&#8221;&gt;<br />
&lt;ItemTemplate&gt;<br />
&lt;%# Eval(&#8220;MeetingName&#8221;) %&gt;<br />
&lt;/ItemTemplate&gt;<br />
&lt;/asp:Repeater&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/ms178366.aspx" target="_blank">http://msdn2.microsoft.com/en-us/library/ms178366.aspx</a></p>
<h1 style="text-align: center;">&lt;%$ &#8230; %&gt;</h1>
<p>Used for expressions, not code; often seen with DataSources:</p>
<blockquote><p>&lt;asp:SqlDataSource ID=&#8221;party&#8221; runat=&#8221;server&#8221; ConnectionString=&#8221;&lt;%$ ConnectionStrings:letsParty %&gt;&#8221; SelectCommand=&#8221;SELECT * FROM [table]&#8221; /&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx" target="_blank">http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx</a></p>
<h1 style="text-align: center;">&lt;%@ &#8230; %&gt;</h1>
<p>This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration:</p>
<blockquote><p>&lt;%@ Page Language=&#8221;C#&#8221; MasterPageFile=&#8221;~/MasterPage.master&#8221; AutoEventWireup=&#8221;true&#8221; CodeFile=&#8221;Default.aspx.cs&#8221; Inherits=&#8221;_Default&#8221; Title=&#8221;Untitled Page&#8221; %&gt;<br />
&lt;%@ Register TagPrefix=&#8221;wp&#8221; Namespace=&#8221;CustomWebParts&#8221; %&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/xz702w3e%28VS.80%29.aspx" target="_blank">http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx</a></p>
<h1 style="text-align: center;">&lt;%&#8211; &#8230; &#8211;%&gt;</h1>
<p>This is a server side comment, stuff  you don&#8217;t want anyone without code access to see:</p>
<blockquote><p>&lt;asp:Label ID=&#8221;lblAwesome&#8221; runat=&#8221;server&#8221; /&gt;<br />
&lt;%&#8211; sometimes end users make me angry &#8211;%&gt;<br />
&lt;asp:LinkButton ID=&#8221;lbEdit&#8221; Text=&#8221;Edit&#8221; OnClick=&#8221;Edit_Click&#8221; runat=&#8221;server&#8221; /&gt;</p></blockquote>
<p><a href="http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx" target="_blank">http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx</a></p>
<p>And that&#8217;s that.</p>
<p>Source: <a href="http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-(3c25242c-3c253d2c-3c252c-3c252c-etc).aspx" target="_blank">Naspinski</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/06/aspnet-inline-tags/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Three quick ways optimize AJAX driven websites in ASP.NET</title>
		<link>http://jesal.us/2008/04/three-quick-ways-optimize-ajax-driven-websites-in-aspnet/</link>
		<comments>http://jesal.us/2008/04/three-quick-ways-optimize-ajax-driven-websites-in-aspnet/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 22:02:17 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=84</guid>
		<description><![CDATA[Recently I was involved in a project where I had to make heavy use of AJAX. I realized there are a few simple things you could do to improve performance. 1) Combine scripts &#60;ajaxToolkit:ToolkitScriptManager ID="TSM1" runat="Server" EnablePartialRendering="true" CombineScriptsHandlerUrl="~/CombineScriptsHandler.ashx" /&#62; As the name of the property suggests, it will pretty much combine all the needed JS [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was involved in a project where I had to make heavy use of AJAX. I realized there are a few simple things you could do to improve performance.</p>
<p><strong>1) Combine scripts<br />
</strong></p>
<p><!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 ajaxToolkit\cf1 :\cf3 ToolkitScriptManager\cf0  \cf5 ID\cf1 ="ScriptManager1"\cf0  \cf5 runat\cf1 ="Server"\cf0  \cf5 EnablePartialRendering\cf1 ="true"\par ??\cf0     \cf5 CombineScriptsHandlerUrl\cf1 ="~/CombineScriptsHandler.ashx"\cf0  \cf1 /&amp;gt;}<br />
--></p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">ajaxToolkit</span><span style="color: blue;">:</span><span style="color: #a31515;">ToolkitScriptManager</span> <span style="color: red;">ID</span><span style="color: red;">="</span><span><span style="color: blue;">TSM1</span></span><span style="color: red;">" runat</span><span style="color: blue;">="Server"</span>
<span style="color: red;">EnablePartialRendering</span><span style="color: blue;">="true"</span>
<strong><span style="color: red;">CombineScriptsHandlerUrl</span><span style="color: blue;">="~/CombineScriptsHandler.ashx"</span></strong> <span style="color: blue;">/&gt;</span></pre>
</div>
<p>As the name of the property suggests, it will pretty much combine all the needed JS files into one which in turn will reduce the number of requests sent to the server. You can find a detailed discussion about this <a href="http://blogs.msdn.com/delay/archive/2007/06/20/script-combining-made-better-overview-of-improvements-to-the-ajax-control-toolkit-s-toolkitscriptmanager.aspx" target="_blank">here</a>.</p>
<p>It is pretty easy to implement; instead of using the regular ScriptManager, just switch to the ToolkitScriptManager which comes with the AjaxToolkit and then set its CombineScriptsHandlerUrl property as shown above and throw the CombineScriptsHandler.ashx (included in the &#8220;SampleWebSite&#8221; directory of AjaxControlToolkit&#8217;s <a href="http://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx" target="_blank">release package</a>) into the root.</p>
<p><strong>2) Run in release mode</strong></p>
<p>The debug versions of the AJAX library have their source formatting preserved, as well as some debug asserts. By running it in release mode you can shave off some bytes off your requests.</p>
<p><!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 ajaxToolkit\cf1 :\cf3 ToolkitScriptManager\cf0  \cf5 ID\cf1 ="ToolkitScriptManager1"\cf0  \cf5 runat\cf1 ="Server"\cf0  \cf5 EnablePartialRendering\cf1 ="true"\par ??\cf0     \cf5 ScriptMode\cf1 ="Release"\cf0  \cf5 CombineScriptsHandlerUrl\cf1 ="~/CombineScriptsHandler.ashx"\cf0  \cf1 /&amp;gt;\par ??}<br />
--></p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">ajaxToolkit</span><span style="color: blue;">:</span><span style="color: #a31515;">ToolkitScriptManager</span> <span style="color: red;">ID</span><span style="color: blue;">="TSM1"</span> <span style="color: red;">runat</span><span style="color: blue;">="Server"</span> <span style="color: red;">
EnablePartialRendering</span><span style="color: blue;">="true" </span><strong><span style="color: red;">ScriptMode</span><span style="color: blue;">="Release"</span></strong> <span style="color: blue;">/&gt;</span></pre>
</div>
<p>Although, its important to note that some versions of Safari don&#8217;t seem to be compatible with this and could cause many strange side effects as <a href="http://blog.tatham.oddie.com.au/2007/05/31/aspnet-ajax-is-a-pos-designed-by-naive-microsoft-universe-programmers/" target="_blank">this person</a> and I have experienced in the past.</p>
<p>On a side note, ASP.NET AJAX Control Toolkit officially <a href="http://msdn2.microsoft.com/en-us/library/bb470452.aspx" target="_blank">does not support </a><span class="m2"><span class="m2"><a href="http://msdn2.microsoft.com/en-us/library/bb470452.aspx" target="_blank">Macs with PowerPC processors</a>, its good to know that piece of information if a client ever demands an explanation as for why AJAX powered functionality seems to be broken or not functioning as expected in that environment.<br />
</span></span></p>
<p><strong>3) Enable script caching and compression in web.config</strong><br />
<!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 system.web.extensions\cf1 &amp;gt;\par ??\tab &amp;lt;\cf3 scripting\cf1 &amp;gt;\par ??\tab \tab &amp;lt;\cf3 scriptResourceHandler\cf1  \cf4 enableCompression\cf1 =\cf0 "\cf1 true\cf0 "\cf1  \cf4 enableCaching\cf1 =\cf0 "\cf1 true\cf0 "\cf1 /&amp;gt;\par ??\tab &amp;lt;/\cf3 scripting\cf1 &amp;gt;\par ??&amp;lt;/\cf3 system.web.extensions\cf1 &amp;gt;}<br />
--></p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">
&lt;</span><span style="color: #a31515;">system.web.extensions</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">  &lt;</span><span style="color: #a31515;">scripting</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">    &lt;</span><span style="color: #a31515;">scriptResourceHandler</span><span style="color: blue;"> </span><span style="color: red;">enableCompression</span><span style="color: blue;">=</span>"<span style="color: blue;">true</span>"<span style="color: blue;">
</span><span style="color: red;">     enableCaching</span><span style="color: blue;">=</span>"<span style="color: blue;">true</span>"<span style="color: blue;">/&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">  &lt;/</span><span style="color: #a31515;">scripting</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">system.web.extensions</span><span style="color: blue;">&gt;</span></pre>
</div>
<p>This will compress and cache all the script files which are embedded as resources in an assembly, localization objects, and scripts that are served by the script resource handler.</p>
<p>But like the previous tip, there is a exception to this one too. Some versions of IE6 have a bug where they cant&#8217;t handle GZIP&#8217;d script files correctly. The RTM version of ASP.NET AJAX works around this by explicitly not compressing files for these versions of IE. Although if you are still having a problem, it just might be a safe bet to explicitly set the enableCompression property to false in the web.config.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/04/three-quick-ways-optimize-ajax-driven-websites-in-aspnet/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Request.Browser.Crawler</title>
		<link>http://jesal.us/2008/04/requestbrowsercrawler/</link>
		<comments>http://jesal.us/2008/04/requestbrowsercrawler/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 17:02:03 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[browser]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=83</guid>
		<description><![CDATA[In my previous post about exception logging, I show how to log several different parameters related to the exception in the database. Request.Browser.Crawler is one of them and its used to track browser crawlers. It warrants its own separate entry since it requires some extra bit of setup in the web.config to get it to [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post about exception logging, I show how to log several different parameters related to the exception in the database. Request.Browser.Crawler is one of them and its used to track browser crawlers. It warrants its own separate entry since it requires some extra bit of setup in the web.config to get it to work correctly.</p>
<p>You&#8217;ll have to add the following code in the  section of your web.config file:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="rem">&lt;!-- This section is used by Request.Browser.Crawler property to detect search engine crawlers --&gt;</span>
<span class="kwrd">&lt;</span><span class="html">browserCaps</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">filter</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- SEARCH ENGINES GROUP --&gt;</span>
    <span class="rem">&lt;!-- check Google (Yahoo uses this as well) --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="^Googlebot(\-Image)?/(?'version'(?'major'\d+)(?'minor'\.\d+)).*"</span><span class="kwrd">&gt;</span>
      browser=Google
      version=${version}
      majorversion=${major}
      minorversion=${minor}
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Alta Vista (Scooter) --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="^Scooter(/|-)(?'version'(?'major'\d+)(?'minor'\.\d+)).*"</span><span class="kwrd">&gt;</span>
      browser=AltaVista
      version=${version}
      majorversion=${major}
      minorversion=${minor}
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Alta Vista (Mercator) --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="Mercator"</span><span class="kwrd">&gt;</span>
      browser=AltaVista
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Slurp (Yahoo uses this as well) --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="Slurp"</span><span class="kwrd">&gt;</span>
      browser=Slurp
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check MSN --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="MSNBOT"</span><span class="kwrd">&gt;</span>
      browser=MSN
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Northern Light --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="^Gulliver/(?'version'(?'major'\d+)(?'minor'\.\d+)).*"</span><span class="kwrd">&gt;</span>
      browser=NorthernLight
      version=${version}
      majorversion=${major}
      minorversion=${minor}
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Excite --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="ArchitextSpider"</span><span class="kwrd">&gt;</span>
      browser=Excite
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- Lycos --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="Lycos_Spider"</span><span class="kwrd">&gt;</span>
      browser=Lycos
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- Ask Jeeves --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="Ask Jeeves"</span><span class="kwrd">&gt;</span>
      browser=AskJeaves
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- check Fast --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="^FAST-WebCrawler/(?'version'(?'major'\d+)(?'minor'\.\d+)).*"</span><span class="kwrd">&gt;</span>
      browser=Fast
      version=${version}
      majorversion=${major}
      minorversion=${minor}
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
    <span class="rem">&lt;!-- IBM Research Web Crawler --&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">case</span> <span class="attr">match</span><span class="kwrd">="http\:\/\/www\.almaden.ibm.com\/cs\/crawler"</span><span class="kwrd">&gt;</span>
      browser=IBMResearchWebCrawler
      crawler=true
    <span class="kwrd">&lt;/</span><span class="html">case</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">filter</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">browserCaps</span><span class="kwrd">&gt;</span></pre>
<p>Now what does it all mean? Well, IIS uses that information in the &lt;browserCaps&gt; section of your config file to detect whether the client browser is a crawler or not. If you look at it closely, its basically a regular expression filter. I presume you could add more filters in a similar format to detect other kinds of crawlers.</p>
<p><strong>Update</strong>: For the most accurate and updated version of browserCaps and other useful browser testing/detection resources you can go to one of these sites:</p>
<p><a href="http://slingfive.com/pages/code/browserCaps/" target="_blank">http://slingfive.com/pages/code/browserCaps/</a></p>
<p><a href="http://ocean.accesswa.net/browsercaps/" target="_blank">http://ocean.accesswa.net/browsercaps/</a></p>
<p><a href="http://browsers.garykeith.com/downloads.asp" target="_blank">http://browsers.garykeith.com/downloads.asp</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/04/requestbrowsercrawler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exception Logging Using The Database</title>
		<link>http://jesal.us/2008/04/exception-logging-using-the-database/</link>
		<comments>http://jesal.us/2008/04/exception-logging-using-the-database/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 16:25:26 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[asp.net]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=82</guid>
		<description><![CDATA[This is a simple technique I use to log exceptions in all my web applications. First lets start by adding the following to the web.config: &#60;appSettings&#62; &#60;add key="LogUnhandledExceptions" value="true"/&#62; &#60;/appSettings&#62; Second, we add the following bit inside the Application_Error event of the Global.asax file. This will capture all the unhandled exceptions and log them into [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple technique I use to log exceptions in all my web applications.</p>
<p>First lets start by adding the following to the web.config:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">&lt;</span><span class="html">appSettings</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">add</span> <span class="attr">key</span><span class="kwrd">="LogUnhandledExceptions"</span> <span class="attr">value</span><span class="kwrd">="true"</span><span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">appSettings</span><span class="kwrd">&gt;</span>
</pre>
<p>Second, we add the following bit inside the Application_Error event of the Global.asax file. This will capture all the unhandled exceptions and log them into the database:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> logUnhandledExceptions = Convert.ToBoolean(ConfigurationManager.AppSettings[<span class="str">"LogUnhandledExceptions"</span>]);
.
.
.
<span class="kwrd">void</span> Application_Error(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">if</span> (logUnhandledExceptions)
    {
        <span class="kwrd">if</span> (Context != <span class="kwrd">null</span>)
        {
            <span class="kwrd">if</span> (Server.GetLastError() != <span class="kwrd">null</span>)
            {
                <span class="rem">//Get reference to the source of the exception chain</span>
                Exception ex = Context.Server.GetLastError().GetBaseException();

                YourCompany.Helpers.ExceptionHandler.Log(ex);
            }
        }
    }
}
</pre>
<p>And now finally the main part. This is the class which will log all the relavent information related to the exception in the DB.</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Data;
<span class="kwrd">using</span> System.Configuration;
<span class="kwrd">using</span> System.Web;
<span class="kwrd">using</span> System.Web.Security;
<span class="kwrd">using</span> System.Web.UI;
<span class="kwrd">using</span> System.Web.UI.WebControls;
<span class="kwrd">using</span> System.Web.UI.WebControls.WebParts;
<span class="kwrd">using</span> System.Web.UI.HtmlControls;
<span class="kwrd">using</span> System.Diagnostics;
<span class="kwrd">using</span> System.Data.SqlClient;
<span class="kwrd">using</span> System.Web.Configuration;

<span class="kwrd">namespace</span> YourCompany.Helpers
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ExceptionHandler
    {
        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Log(Exception ex)
        {
            <span class="kwrd">if</span> (ex.GetBaseException() != <span class="kwrd">null</span>)
            {
                <span class="kwrd">try</span>
                {
                    HttpContext context = HttpContext.Current;
                    HttpBrowserCapabilities browser = context.Request.Browser;

                    <span class="kwrd">string</span> referer = String.Empty;

                    <span class="kwrd">if</span> (context.Request.UrlReferrer != <span class="kwrd">null</span>)
                    {
                        referer = context.Request.UrlReferrer.ToString();
                    }

                    <span class="kwrd">using</span> (SqlConnection sqlConnection = <span class="kwrd">new</span> SqlConnection(WebConfigurationManager.ConnectionStrings[<span class="str">"ConnectionString"</span>].ConnectionString))
                    {
                        <span class="kwrd">using</span> (SqlCommand sqlCommand = <span class="kwrd">new</span> SqlCommand())
                        {
                            sqlCommand.Connection = sqlConnection;
                            sqlCommand.CommandType = CommandType.StoredProcedure;
                            sqlCommand.CommandText = <span class="str">"EventLog_Insert"</span>;

                            sqlCommand.Parameters.Add(<span class="str">"@Source"</span>, SqlDbType.NVarChar).Value = ex.Source;
                            sqlCommand.Parameters.Add(<span class="str">"@Message"</span>, SqlDbType.NVarChar).Value = ex.Message;
                            sqlCommand.Parameters.Add(<span class="str">"@Form"</span>, SqlDbType.NVarChar).Value = context.Request.Form.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@Path"</span>, SqlDbType.NVarChar).Value = context.Request.Path.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@QueryString"</span>, SqlDbType.NVarChar).Value = context.Request.QueryString.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@TargetSite"</span>, SqlDbType.NVarChar).Value = ex.TargetSite.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@StackTrace"</span>, SqlDbType.NVarChar).Value = ex.StackTrace.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@Referer"</span>, SqlDbType.NVarChar).Value = referer;
                            sqlCommand.Parameters.Add(<span class="str">"@MachineName"</span>, SqlDbType.NVarChar).Value = context.Server.MachineName.ToString();
                            sqlCommand.Parameters.Add(<span class="str">"@IPAddress"</span>, SqlDbType.NVarChar).Value = context.Request.UserHostAddress;
                            sqlCommand.Parameters.Add(<span class="str">"@BrowserType"</span>, SqlDbType.NVarChar).Value = browser.Type;
                            sqlCommand.Parameters.Add(<span class="str">"@BrowserName"</span>, SqlDbType.NVarChar).Value = browser.Browser;
                            sqlCommand.Parameters.Add(<span class="str">"@BrowserVersion"</span>, SqlDbType.NVarChar).Value = browser.Version;
                            sqlCommand.Parameters.Add(<span class="str">"@BrowserPlatform"</span>, SqlDbType.NVarChar).Value = browser.Platform;
                            sqlCommand.Parameters.Add(<span class="str">"@SupportsCookies"</span>, SqlDbType.Bit).Value = browser.Cookies;
                            sqlCommand.Parameters.Add(<span class="str">"@IsCrawler"</span>, SqlDbType.Bit).Value = browser.Crawler;

                            sqlConnection.Open();

                            sqlCommand.ExecuteNonQuery();
                        }
                    }
                }
                <span class="kwrd">catch</span>
                {
                    <span class="rem">// database error, not much you can do here except logging the error in the windows event log</span>
                    EventLog.WriteEntry(ex.Source, <span class="str">"Database Error From Exception Handler!"</span>, EventLogEntryType.Error);
                }
            }
        }
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/04/exception-logging-using-the-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Mysterious &#8220;Invalid Parameter Used&#8221; Error</title>
		<link>http://jesal.us/2008/03/the-mysterious-invalid-parameter-used-error/</link>
		<comments>http://jesal.us/2008/03/the-mysterious-invalid-parameter-used-error/#comments</comments>
		<pubDate>Sat, 29 Mar 2008 07:37:47 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[errors]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/2008/03/29/the-mysterious-invalid-parameter-used-error/</guid>
		<description><![CDATA[Recently I was trying to write a little C# function for cropping images. I expected it to be a quick 5 minute task but I ended up spending a huge amount of time getting it to work correctly. I kept getting a very stubborn and mysterious error &#8211; &#8220;Invalid Parameter Used&#8221; &#8211; whenever I tried [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was trying to write a little C# function for cropping images. I expected it to be a quick 5 minute task but I ended up spending a huge amount of time getting it to work correctly. I kept getting a very stubborn and mysterious error &#8211; &#8220;Invalid Parameter Used&#8221; &#8211; whenever I tried to save my newly cropped image by doing bitmap.Save(). I tried various suggestions I found on forums and blogs to no avail.</p>
<p>Finally I figured out what the problem was. I was encapulatning the Bitmap and Graphics objects inside a &#8220;using&#8221; statement. So the Bitmap object was being prematurely disposed before I returned it back to the caller.</p>
<p>So in the end my solution looked like this. I just god rid of the &#8220;usings&#8221;.</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode"><span class="kwrd">public</span> Bitmap CropImage(Image image, Rectangle cropRect)
{
    Bitmap bitmap = <span class="kwrd">new</span> Bitmap(cropRect.Width, cropRect.Height, PixelFormat.Format24bppRgb);
    bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.DrawImage(image, 0, 0, cropRect, GraphicsUnit.Pixel);
    <span class="kwrd">return</span> bitmap;
}</pre>
<p>Usage -<br />
<span class="csharpcode"><br />
Bitmap croppedBmp = CropImage(<span class="str">&#8220;~/uploads/test.jpg&#8221;</span>, <span class="kwrd">new</span> Rectangle(x, y, width, height));<br />
croppedBmp.Save();</span></p>
<p>Moral of the story: If you are getting this error while calling Bitmap.Save() then make sure you are not disposing your Bitmap object prematurely. Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/03/the-mysterious-invalid-parameter-used-error/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

