<?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>Ruben Canton</title>
	<atom:link href="http://www.rubencanton.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://www.rubencanton.com/blog</link>
	<description>Just another blog about web programming, design, usability, standards and maybe some SEO</description>
	<lastBuildDate>Sun, 20 May 2012 13:58:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Object Oriented Programming with JavaScript</title>
		<link>http://www.rubencanton.com/blog/2012/05/programming-object-oriented-javascript.html</link>
		<comments>http://www.rubencanton.com/blog/2012/05/programming-object-oriented-javascript.html#comments</comments>
		<pubDate>Thu, 10 May 2012 09:29:23 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=690</guid>
		<description><![CDATA[JavaScript is a powerful and old language that was not thought to work with objects, though, we can make it a bit object oriented implementing our own objects and classes like this:
Create a class
To make a class we can directly build it a constructor and inside it place all the class properties and methods like [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript is a powerful and old language that was not thought to work with objects, though, we can make it a bit object oriented implementing our own objects and classes like this:</p>
<h2>Create a class</h2>
<p>To make a class we can directly build it a constructor and inside it place all the class properties and methods like this:</p>
<pre class="brush: jscript; wrap-lines: false;">
function CreateMyObject() {
    //Here all the stuff
}
</pre>
<h2>Adding public and private variables</h2>
<p>You can make a public variable using the keyword this.</p>
<pre class="brush: jscript; wrap-lines: false;">
function CreateMyObject() {
    this.publicVar = 'Im public';
    var privateVar = 'Im private';
}
</pre>
<p><span id="more-690"></span></p>
<h2>Adding public and private methods</h2>
<p>Following the same as before, but we have to ways of setting the pointer to the method.</p>
<pre class="brush: jscript; wrap-lines: false;">
function CreateMyObject() {
    this.someMethod = someMethod;
    function someMethod() {
        alert('Hello Im a method');
    }
    this.someOtherMethod= function () {
        alert('Hello Im another method');
    }

    function privateMethod(){
        alert('Im a private method.');
    }
}
</pre>
<p>With the first option you could make a list of public methods in the top and then write the methods down, with the second you don&#8217;t need to maintain a list.</p>
<h2>Putting all of it together</h2>
<p>Just to have it as an example:</p>
<pre class="brush: jscript; wrap-lines: false;">
function CreateMyObject() {
    // Properties
    this.publicVar = 'Im public';
    var privateVar = 'Im private';

    //Methods
    this.someMethod = someMethod;
    function someMethod() {
        alert('Hello Im a method');
    }
    this.someOtherMethod= function () {
        alert('Hello Im another method');
    }
    function privateMethod(){
        alert('Im a private method.');
    }
}
</pre>
<h2>Using it</h2>
<pre class="brush: jscript; wrap-lines: false;">
var MyObject = new CreateMyObject();
alert(MyObject.publicVar);
alert(MyObject.privateVar); // This will not work. Its private!!
MyObject.someMethod();
MyObject.someOtherMethod();
</pre>
<p>Thanks to <a href="http://www.webmonkey.com/2010/02/make_oop_classes_in_javascript/">webmonkey</a>, <a href="http://javascript.about.com/library/bltut35.htm">about</a> and <a href="http://www.codeproject.com/Articles/15388/Creating-Custom-Class-in-JavaScript-and-adding-met">codeproject</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/05/programming-object-oriented-javascript.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the UpdateProgress in .Net AJAX</title>
		<link>http://www.rubencanton.com/blog/2012/04/using-the-updateprogress-in-net-ajax.html</link>
		<comments>http://www.rubencanton.com/blog/2012/04/using-the-updateprogress-in-net-ajax.html#comments</comments>
		<pubDate>Fri, 27 Apr 2012 07:35:28 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=648</guid>
		<description><![CDATA[When updating a part of page using ajax with UpdatePanels, you may want to show the user that the request is being done so he can wait until it is done and not send more asynchronous requests to the server.
Placing the UpdateProgress inside the UpdatePanel
If you want to make it clear and easy that the [...]]]></description>
			<content:encoded><![CDATA[<p>When updating a part of page using ajax with UpdatePanels, you may want to show the user that the request is being done so he can wait until it is done and not send more asynchronous requests to the server.</p>
<h2>Placing the UpdateProgress inside the UpdatePanel</h2>
<p>If you want to make it clear and easy that the UpdateProgress belongs to an UpdatePanel you can place it inside the UpdatePanel ContentTemplate tag and that will do it. The UpdateProgress content will be shown when a request is made and hidden when finished.</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;asp:UpdatePanel ID=&quot;UpdatePanel2&quot; runat=&quot;server&quot; UpdateMode=&quot;Always&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;btnAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;btnAtUpdatePanel2_Click&quot; /&gt;
            &lt;asp:Label ID=&quot;lbAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
            &lt;asp:UpdateProgress ID=&quot;UpdateProgress1&quot; runat=&quot;server&quot;&gt;
                &lt;ProgressTemplate&gt;Loading...&lt;/ProgressTemplate&gt;
            &lt;/asp:UpdateProgress&gt;
        &lt;/ContentTemplate&gt;
    &lt;/asp:UpdatePanel&gt;
</pre>
<p><span id="more-648"></span></p>
<h2>Placing the UpdateProgress outside the UpdatePanel</h2>
<p>If you need to place the UpdateProgress outside the UpdatePanel (for example to show the message in another part of the page) you can use its <em>AssociatedUpdatePanelId</em> property to link it with an UpdatePanel and make it work:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;asp:UpdatePanel ID=&quot;UpdatePanel2&quot; runat=&quot;server&quot; UpdateMode=&quot;Always&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;btnAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;btnAtUpdatePanel2_Click&quot; /&gt;
            &lt;asp:Label ID=&quot;lbAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
        &lt;/ContentTemplate&gt;
    &lt;/asp:UpdatePanel&gt;

    &lt;asp:UpdateProgress ID=&quot;UpdateProgress1&quot; runat=&quot;server&quot; AssociatedUpdatePanelID=&quot;UpdatePanel2&quot;&gt;
        &lt;ProgressTemplate&gt;Loading...&lt;/ProgressTemplate&gt;
    &lt;/asp:UpdateProgress&gt;
</pre>
<h3>Using an UpdateProgress for all the UpdatePanels</h3>
<p>If you don&#8217;t set the <em>AssociatedUpdatePanelId</em> property the UpdateProgress will trigger for all the UpdatePanels in the page, a good way to have a single UpdateProgress for all of them.</p>
<h2>Using a block panel to prevent user from making more requests</h2>
<p>I&#8217;m sure you have seen many times when doing an async request that a panel blocking you the UI box is shown, maybe saying something like &#8220;Loading&#8230;&#8221; but mainly preventing you from interacting with the UI and sending more requests.</p>
<p>Well, there are different ways of showing that depending on your needs but I&#8217;m going to show here an example of that so you can use it or get as an idea:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;asp:UpdateProgress ID=&quot;UpdateProgress&quot; runat=&quot;server&quot; DisplayAfter=&quot;0&quot;&gt;
    &lt;ProgressTemplate&gt;&lt;div class=&quot;AjaxProgressPNL&quot;&gt;&lt;span&gt;Loading...&lt;/span&gt;&lt;/div&gt;&lt;/ProgressTemplate&gt;
&lt;/asp:UpdateProgress&gt;
</pre>
<p>I&#8217;ve added a div inside the UpdateProgress with the <em>class=&#8221;AjaxProgressPNL&#8221;</em>, so I can have more than one. Since I will need to calculate the size of the div depending on its UpdatePanel parent and also position it above it we need to add an individual UpdateProgress for each UpdatePanel here (we could try not to but I don&#8217;t think it worths it). I will also add this css to it:</p>
<pre class="brush: css; wrap-lines: false;">
.AjaxProgressPNL{background:#000;text-align:center;width:100%;position:absolute;top:0;left:0;
                 display:table-cell;vertical-align:middle;opacity:0.4;padding:5px;
                 filter:alpha(opacity=40); /* For IE8 and earlier */
                 }
</pre>
<p>I&#8217;ve decided to make it half transparent and to use a black background this time. That done, we need to calculate its size dynamically using javascript (we need javascript to send the async req. after all), so let&#8217;s use something like this:</p>
<pre class="brush: jscript; wrap-lines: false;">
&lt;script type=&quot;text/javascript&quot;&gt;
    $(document).ready(function () {
        $(&quot;body&quot;).live(&quot;mouseover&quot;, function () {
            var parentHeight = $(&quot;.AjaxProgressPNL&quot;).parents(&quot;div[id*='UpdatePanel']&quot;).height();
            $(&quot;.AjaxProgressPNL&quot;).height(parentHeight);
            $(&quot;.AjaxProgressPNL span&quot;).css(&quot;line-height&quot;, parentHeight + 'px');
        });
    });
&lt;/script&gt;
</pre>
<p>I&#8217;ve used a little trick since when we work with jQuery styling and asynchronous requests the DOM objects repainted and lose their jQuery effects (these aren&#8217;t the same objects after all, they are new). When the async. request is done jQuery doesn&#8217;t reassign the binds or styles as that binding or styling happened when the page was ready, and now that <em>document.ready()</em> event will not be fired since this is an <strong>asynchronous request</strong>.</p>
<p>You can use the <em>.on()</em> (.live() in older versions) to bind events and make them continue working after an async. request, but for styling there doesn&#8217;t seem to be anything. Of course, if you work with <em>jQuery&#8217;s ajax object</em> and use it to make asynchronous requests you can use <em>.ajaxComplete()</em> or <em>.ajaxSuccess()</em>, but when combining <strong>.Net AJAX</strong> with <strong>jQuery</strong> that doesn&#8217;t make it.</p>
<h2>Displaying the UpdateProgress with a delay or immediately</h2>
<p>By using the <em>DisplayAfter</em> property, you can set how much time the UpdateProgress will take before showing itself. This way, you can avoid it to be shown in quick requests making them show as totally automatic, but since its default value is 500 (half second), you may also want to show it quicker to prevent more user postbacks.</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;asp:UpdateProgress ID=&quot;UpdateProgress1&quot; runat=&quot;server&quot; DisplayAfter=&quot;0&quot;&gt;
    &lt;ProgressTemplate&gt;Loading...&lt;/ProgressTemplate&gt;
&lt;/asp:UpdateProgress&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/04/using-the-updateprogress-in-net-ajax.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guide for using .Net UpdatePanels</title>
		<link>http://www.rubencanton.com/blog/2012/04/guide-for-using-net-updatepanels.html</link>
		<comments>http://www.rubencanton.com/blog/2012/04/guide-for-using-net-updatepanels.html#comments</comments>
		<pubDate>Tue, 24 Apr 2012 07:30:51 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=617</guid>
		<description><![CDATA[The first thing to do for using an UpdatePanel is to add a ScriptManager to the page. You can only add one and you need at least one, so you can add it to the MasterPage or just to the page using AJAX (notice the ScriptManager will add some extra scripts to your page making [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The first thing to do for using an UpdatePanel is to add a ScriptManager to the page</strong>. You can only add one and you need at least one, so you can add it to the MasterPage or just to the page using AJAX (notice the ScriptManager will add some extra scripts to your page making it slower). You can also use a ScriptManagerProxy, but that&#8217;s another story, let&#8217;s focus on UpdatePanels.</p>
<h2>Adding a basic UpdatePanel</h2>
<p>To add a basic UpdatePanel that will refresh without refreshing all the page and speed up your website just add this to your code after having added a ScriptManager:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;BTNChangeText&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;BTNChangeText_Click&quot; /&gt;
            &lt;asp:Label ID=&quot;lbText&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
        &lt;/ContentTemplate&gt;
    &lt;/asp:UpdatePanel&gt;
</pre>
<p>And this other to your back code:</p>
<pre class="brush: csharp; wrap-lines: false;">
protected void BTNChangeText_Click(object sender, EventArgs e) {
    lbText.Text = &quot;Text changed.&quot;;
}
</pre>
<p>With just that the UpdatePanel will work using its default options and the text will be changed asyncronously. Now, you can use this to make a part of the page to work as if it were an iframe but without using frames.<br />
<span id="more-617"></span></p>
<h2>Refreshing the UpdatePanel using external controls</h2>
<p>In the last example we saw that we can use a control inside the UpdatePanel, like a button, to fire and by default it will be an asynchronous postback, but, what if we want an outside the UpdatePanel control to refresh it? For doing that we have the triggers.</p>
<p>Use this code in the front end:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot;&gt;
    &lt;ContentTemplate&gt;
        &lt;asp:Button ID=&quot;BTNChangeText&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;BTNChangeText_Click&quot; /&gt;
        &lt;asp:Label ID=&quot;lbText&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
    &lt;/ContentTemplate&gt;
    &lt;Triggers&gt;
        &lt;asp:AsyncPostBackTrigger ControlID=&quot;btnOutside&quot; EventName=&quot;Click&quot; /&gt;
    &lt;/Triggers&gt;
&lt;/asp:UpdatePanel&gt;

&lt;asp:Button ID=&quot;btnOutside&quot; runat=&quot;server&quot; Text=&quot;Change from outside&quot; onclick=&quot;btnOutside_Click&quot;  /&gt;
</pre>
<p>And this in the back end:</p>
<pre class="brush: csharp; wrap-lines: false;">
        protected void BTNChangeText_Click(object sender, EventArgs e) {
            lbText.Text = &quot;Text changed from inside the UpdatePanel.&quot;;
            UpdatePanel1.Update();
        }

        protected void btnOutside_Click(object sender, EventArgs e) {
            lbText.Text = &quot;Text changed from outside the UpdatePanel.&quot;;
        }
</pre>
<p>As you can see, there is a button outside the UpdatePanel that will change the text inside it and now, at the bottom of the UpdatePanel, I&#8217;ve added a trigger to set that the outside button will asynchoronously refresh this UpdatePanel when clicked. If you don&#8217;t add the trigger the button will refresh all the page instead than just the Update Panel.</p>
<h2>Using multiple UpdatePanels and conditional postbacks</h2>
<p>Until now, we have been using just 1 UpdatePanel, which made it easy to handle its asynchronous postbacks. Now, we are going to add a second UpdatePanel to the page and see what happens:</p>
<p>This in the FrontEnd:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;BTNChangeText&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;BTNChangeText_Click&quot; /&gt;
            &lt;asp:Label ID=&quot;lbText&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
        &lt;/ContentTemplate&gt;
        &lt;Triggers&gt;
            &lt;asp:AsyncPostBackTrigger ControlID=&quot;btnOutside&quot; EventName=&quot;Click&quot; /&gt;
        &lt;/Triggers&gt;
    &lt;/asp:UpdatePanel&gt;

    &lt;asp:Label ID=&quot;lbOutside&quot; runat=&quot;server&quot; Text=&quot;Label outside.&quot;&gt;&lt;/asp:Label&gt;
    &lt;asp:Button ID=&quot;btnOutside&quot; runat=&quot;server&quot; Text=&quot;Change from outside&quot; onclick=&quot;btnOutside_Click&quot;  /&gt;

    &lt;asp:UpdatePanel ID=&quot;UpdatePanel2&quot; runat=&quot;server&quot; UpdateMode=&quot;Always&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;btnAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;btnAtUpdatePanel2_Click&quot; /&gt;
            &lt;asp:Label ID=&quot;lbAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
        &lt;/ContentTemplate&gt;
    &lt;/asp:UpdatePanel&gt;
</pre>
<p>This in the Backend:</p>
<pre class="brush: csharp; wrap-lines: false;">
        protected void btnAtUpdatePanel2_Click(object sender, EventArgs e) {
            lbAtUpdatePanel2.Text = &quot;Text changed.&quot;;
            lbText.Text = &quot;Text changed from another UpdatePanel.&quot;;
            lbOutside.Text = &quot;Text changed.&quot;;
        }
</pre>
<p>Interestingly, when we update the UpdatePanel2 <strong>we can also change the label in the UpdatePanel1</strong>, but not the one outside any UpdatePanel. How is that possible? Well, UpdatePanels have a property to set if they will be postbacked and refreshed only under certain conditions or if they should be postbacked and refreshed allways. And <strong>by default, this property is set to always</strong>. So, when we make a full postback they will obviously be refreshed, but when we do any asynchronous postback for any updatePanel in the page <strong>all of the updatePanels in the page will also postback with it</strong>, unless we set their <em>UpdateMode </em>property to <em>Conditional</em>.</p>
<p>If we set the UpdateMode to Conditional we will make the partial request quicker since we will not be refreshing all the UpdatePanels in the page. And we are using UpdatePanels to make requests quicker so&#8230; it seems logic to use a conditional UpdateMode. They are set to &#8220;Always&#8221; by default to make the use of the UpdatePanel easier not having to add any trigger to make it work.</p>
<h3>Setting the ChildrenAsTriggers property</h3>
<p><strong>By default, this property is set to true</strong>. This means any control inside the UpdatePanel will act as a trigger control and update it when fired. You can only set it to false if the UpdateMode is set to Conditional. If you set it to false the controls inside the UpdatePanel will make an asynchronous postback, but the UpdatePanel will not be refreshed.</p>
<p>This is very interesting since you can make one of those buttons do some stuff in the server without having to refresh any data back, or you can trigger another UpdatePanel but not the one in which the control is inside.</p>
<h2>Refreshing an UpdatePanel from another UpdatePanel</h2>
<p>Taking that last idea I&#8217;ve made this:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot; UpdateMode=&quot;Conditional&quot; ChildrenAsTriggers=&quot;false&quot;&gt;
    &lt;ContentTemplate&gt;
        &lt;asp:Button ID=&quot;BTNChangeText&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;BTNChangeText_Click&quot; /&gt;
        &lt;asp:Label ID=&quot;lbText&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
    &lt;/ContentTemplate&gt;
    &lt;Triggers&gt;
        &lt;asp:AsyncPostBackTrigger ControlID=&quot;btnOutside&quot; EventName=&quot;Click&quot; /&gt;
        &lt;asp:AsyncPostBackTrigger ControlID=&quot;btnAtUpdatePanel2&quot; EventName=&quot;Click&quot; /&gt;
    &lt;/Triggers&gt;
&lt;/asp:UpdatePanel&gt;

&lt;asp:Label ID=&quot;lbOutside&quot; runat=&quot;server&quot; Text=&quot;Label outside.&quot;&gt;&lt;/asp:Label&gt;
&lt;asp:Button ID=&quot;btnOutside&quot; runat=&quot;server&quot; Text=&quot;Change from outside&quot; onclick=&quot;btnOutside_Click&quot;  /&gt;

&lt;asp:UpdatePanel ID=&quot;UpdatePanel2&quot; runat=&quot;server&quot; UpdateMode=&quot;Always&quot;&gt;
    &lt;ContentTemplate&gt;
        &lt;asp:Button ID=&quot;btnAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Change&quot; onclick=&quot;btnAtUpdatePanel2_Click&quot; /&gt;
        &lt;asp:Label ID=&quot;lbAtUpdatePanel2&quot; runat=&quot;server&quot; Text=&quot;Initial Text&quot;&gt;&lt;/asp:Label&gt;
    &lt;/ContentTemplate&gt;
&lt;/asp:UpdatePanel&gt;
</pre>
<p>And this in the back end:</p>
<pre class="brush: csharp; wrap-lines: false;">
        protected void BTNChangeText_Click(object sender, EventArgs e) {
            lbText.Text = &quot;Text changed from inside the UpdatePanel.&quot;;
            lbOutside.Text = &quot;Text changed.&quot;;
        }

        protected void btnOutside_Click(object sender, EventArgs e) {
            lbText.Text = &quot;Text changed from outside the UpdatePanel.&quot;;
            lbOutside.Text = &quot;Text changed.&quot;;
        }

        protected void btnAtUpdatePanel2_Click(object sender, EventArgs e) {
            lbAtUpdatePanel2.Text = &quot;Text changed.&quot;;
            lbText.Text = &quot;Text changed from another UpdatePanel.&quot;;
            lbOutside.Text = &quot;Text changed.&quot;;
        }
</pre>
<p>Notice that with the properties <em>UpdateMode=&#8221;Conditional&#8221;</em> and <em>ChildrenAsTriggers=&#8221;false&#8221;</em> the UpdatePanel1 can launch asynchronous post backs (you can debug and see) but <strong>cannot refresh itself</strong>. Instead, the second UpdatePanel and the button outside them can update the UpdatePanel1 <strong>because they are into its triggers</strong>.</p>
<p>The UpdatePanel1 can also update the UpdatePanel2 since this second one has the UpdateMode=&#8221;Always&#8221; and it will be refreshed on any asynchronous request. </p>
<p>So, you have two ways of refreshing an UpdatePanel from another: setting its UpdateMode to always so it will be refreshed on any postback, or add a trigger with the control to fire the postback in it.</p>
<h2>Updating from BackEnd</h2>
<p>Now Imagine we want, under certain conditions, to refresh the UpdatePanel1 and we want to decide this in the back end. We can call its Update() event to make it be refreshed even when it wasn&#8217;t supposed to. Using the last example where its own button couldn&#8217;t refresh the UpdatePanel1 we can add this line to the code and make it possible in Back End:</p>
<pre class="brush: csharp; wrap-lines: false;">
        protected void BTNChangeText_Click(object sender, EventArgs e) {
            lbText.Text = &quot;Text changed from inside the UpdatePanel.&quot;;
            lbOutside.Text = &quot;Text changed.&quot;;
            UpdatePanel1.Update();
        }
</pre>
<p>Check it and see how despite its UpdateMode is set to Conditional, and its ChildrenAsTriggers to false, it is updated thanks to the call to its Update() event.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/04/guide-for-using-net-updatepanels.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS: Using a different image in list bullets</title>
		<link>http://www.rubencanton.com/blog/2012/03/css-using-a-different-image-in-list-bullets.html</link>
		<comments>http://www.rubencanton.com/blog/2012/03/css-using-a-different-image-in-list-bullets.html#comments</comments>
		<pubDate>Tue, 13 Mar 2012 14:51:31 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web design]]></category>
		<category><![CDATA[css]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=600</guid>
		<description><![CDATA[We can use a different image as a bullet for our lists, just using something like this:

.myCustomList li { list-style-image:url('imgs/Bullet.jpg');}

So nice, unfortunately that css property has its limitations and may not fit our purposes if the image is too big or we want to show it in a special way, in that case, its better [...]]]></description>
			<content:encoded><![CDATA[<p>We can use a different image as a bullet for our lists, just using something like this:</p>
<pre class="brush: css; wrap-lines: false;">
.myCustomList li { list-style-image:url('imgs/Bullet.jpg');}
</pre>
<p>So nice, unfortunately that css property has its limitations and may not fit our purposes if the image is too big or we want to show it in a special way, in that case, its better to go for the background property and make a fake bullet:</p>
<pre class="brush: css; wrap-lines: false;">
ul.myCustomList {margin:0;padding:0;}
.myCustomList li {list-style:none;background:url('imgs/Bullet.jpg') left 5px no-repeat;padding-left:20px;}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/03/css-using-a-different-image-in-list-bullets.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Agile principles</title>
		<link>http://www.rubencanton.com/blog/2012/03/agile-principles.html</link>
		<comments>http://www.rubencanton.com/blog/2012/03/agile-principles.html#comments</comments>
		<pubDate>Thu, 08 Mar 2012 07:00:09 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[methodologies]]></category>
		<category><![CDATA[paradigms]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=570</guid>
		<description><![CDATA[Simplicity
Years ago when I was a student, I remember how we thought a complex code was done by someone who knew a lot and a way of showing yourself was to write pretty complex code lines no one even you weeks later could understand.
Simplicity means even an external programmer to the project should be able [...]]]></description>
			<content:encoded><![CDATA[<h2>Simplicity</h2>
<p>Years ago when I was a student, I remember how we thought a complex code was done by someone who knew a lot and <strong>a way of showing yourself was to write pretty complex code lines</strong> no one even you weeks later could understand.</p>
<p>Simplicity means even an external programmer to the project should be able to understand what it does in a quick sight, if that happens, you will also be able to do that and that will help you with maintenance.</p>
<h3>Should I care about external programmers?</h3>
<p>There is a saying in Programming World that, if you became indispensable in your company, maybe because your codes are impossible to handle, you will never be fired. First of all, <strong>you will never be indispensable</strong>, it may cost more to them, but you cannot fully obfuscate a code and even if you can, codes can be redone. So, don&#8217;t waste your time making yours and others life more difficult.</p>
<p>Also, you will notice that, after a while, maybe some months maybe a year, <strong>you&#8217;ll forget about your own codes</strong>, not remembering why you did this or that. So <strong>the best way of helping your future self is to write simple codes</strong> that even your future self drunk could understand.</p>
<h3>Let&#8217;s see an example</h3>
<p>This:</p>
<pre class="brush: jscript; wrap-lines: true;">
function hahahah(e) { var thirteen; if (window.event) thirteen = window.event.keyCode; else thirteen = e.which; return (thirteen != 13); }
</pre>
<p>Should be this:</p>
<pre class="brush: jscript; wrap-lines: false;">
function disableEnterKey(e) {
    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox     

    return (key != 13);
}
</pre>
<p>I know, it&#8217;s not a good example, but I don&#8217;t have anything in hand atm. I will update it when I think of something better.</p>
<h3>Use some comments</h3>
<p>Despite we try to make codes simple we&#8217;ll find that sometimes that&#8217;s just not possible. When that happens, a few comments to explain what it does will help. Also, if the code has a tricky issue, a warning comment will be pretty useful (remember most probably you will be the one who, in 7 months, will have to maintain that code, and you don&#8217;t want to provoke a bug).</p>
<pre class="brush: css; wrap-lines: false;">
/* WARNING: Some styles of this object are set dynamically at its back code*/
.CustomGraph{width:290px;border:1px #eee solid;float:left;margin:0;padding:10px;}
    .CustomGraph h4{margin:0;}
    .CustomGraph .data{height:250px;background-color:#fff;overflow:auto;}
        .CustomGraph .data table{margin:15px auto 0;}
        .CustomGraph .data img{margin:0 auto;display:block;}
        .CustomGraph .data img.expandable{cursor:pointer;}
</pre>
<h2>Don&#8217;t Repeat Yourself (DRY)</h2>
<p>When writing codes it may happen to you that you make a function for one place in your project and then you need to do the same thing in another place (like a validation when adding a user later on you realize you need for updating the user too). When this happens, the temptation to just copy paste the code is big, but doing so, your code will tend to bugs and problems.</p>
<p>If you need to change that user control in the future you may forget there are two places where you have to do the changes, or even when you don&#8217;t forget, if you are touching that code, between modifications the two (or three, or four, &#8230;) copies may end being different in one of the changes. <strong>The best way to avoid this is avoiding repeated functions in the code</strong>.</p>
<h2>You aren&#8217;t gonna need it (YAGNI)</h2>
<p>YAGNI (You aren&#8217;t gonna need it) is an XP principle that prevents you from writing those things you think you are going to need later but that lots of times <strong>you don&#8217;t need in the end</strong>.</p>
<p>When we start designing we open our mind thinking of all the possible actions a user could want to do or the project could need to do. As a result, <strong>we tend to build incredibly big structures for something much more simple</strong>, increasing the project complexity and giving us more work. The YAGNI principle prevents you from this making you build just the things you really need and not the ones you think you could need, increasing the development speed and the project flexibility (less structure, more flexible). <strong>That&#8217;s why this is called Agile <img src='http://www.rubencanton.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </strong></p>
<h2>Last Responsible Moment</h2>
<p>Continuing with YAGNI we have the Last Responsible Moment principle, which consists on <strong>waiting until the very last moment before doing something</strong>, this way you give more time for design or behavior decisions to be taken and help yourself not having to rewrite it. If you have worked as a freelancer like me, you should be used to your clients changing their mind 15 times about were the logotype is going to be placed or if they will add the &#8220;Share in FB&#8221; button or not.</p>
<p>Not only that, in terms of Back End, you may know you will need some class, but instead of making it from the beggining <strong>is better to wait until you really need to use that class</strong> to write it. Not only because domainers may change their mind, but because your design may be redesigned by yourself as you keep going on the project and realize you need this or don&#8217;t need that.</p>
<p>So, don&#8217;t build all the classes &#8220;structure&#8221; at the beggining, instead, start building a class and the ones you need as soon as you need them, this way you will design them knowing the project and its needs better and <strong>adjusting them to the project instead than having to adjust the project to fit something you designed at the start</strong>, when you didn&#8217;t know that much about the project.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/03/agile-principles.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Images handler with resizing options in C#.Net</title>
		<link>http://www.rubencanton.com/blog/2012/03/images-handler-with-resizing-options-in-c-net.html</link>
		<comments>http://www.rubencanton.com/blog/2012/03/images-handler-with-resizing-options-in-c-net.html#comments</comments>
		<pubDate>Fri, 02 Mar 2012 07:00:09 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[c#.net]]></category>
		<category><![CDATA[handlers]]></category>
		<category><![CDATA[images]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=554</guid>
		<description><![CDATA[First have a look at my post for how to make an Images Handler. And from there, let&#8217;s continue.
The idea is that if I request something like these:

http://localhost:54086/images/v/?img=500667&#038;w=540
http://localhost:54086/images/v/?img=500667&#038;h=200
http://localhost:54086/images/v/?img=500667&#038;w=540&#038;maxh=90
http://localhost:54086/images/v/?img=500667&#038;w=540&#038;h=200&#038;maxh=90&#038;maxw=100

It will resize my image to the size I set and also, it will check the size limit for heights or widths so the resulting resized image doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>First have a look at my post for <a href="http://www.rubencanton.com/blog/2011/09/adding-an-http-handler-to-manage-images-requests-in-net.html">how to make an Images Handler</a>. And from there, let&#8217;s continue.</p>
<p>The idea is that if I request something like these:</p>
<ul>
<li>http://localhost:54086/images/v/?img=500667&#038;w=540</li>
<li>http://localhost:54086/images/v/?img=500667&#038;h=200</li>
<li>http://localhost:54086/images/v/?img=500667&#038;w=540&#038;maxh=90</li>
<li>http://localhost:54086/images/v/?img=500667&#038;w=540&#038;h=200&#038;maxh=90&#038;maxw=100</li>
</ul>
<p>It will resize my image to the size I set and also, <strong>it will check the size limit</strong> for heights or widths so the resulting resized image doesn&#8217;t break our layout.</p>
<h2>Adding some params to resize the image</h2>
<p>Lets add the querystring params to the handler:</p>
<pre class="brush: csharp; wrap-lines: false;">
        public const String PARAM_WIDTH = &quot;w&quot;;
        public const String PARAM_HEIGHT = &quot;h&quot;;
        public const String PARAM_MAXWIDTH = &quot;maxw&quot;;
        public const String PARAM_MAXHEIGHT = &quot;maxh&quot;;
</pre>
<p>And a condition method:</p>
<pre class="brush: csharp; wrap-lines: false;">
        private Boolean NeedsToBeResized(Image img) {
            // If one of the params comes most probably Ill need to resize:
            if (request.QueryString[PARAM_WIDTH] != null) { return true; }
            if (request.QueryString[PARAM_HEIGHT] != null) { return true; }
            if (request.QueryString[PARAM_MAXWIDTH] != null) { return true; }
            if (request.QueryString[PARAM_MAXHEIGHT] != null) { return true; }
            return false;
        }
</pre>
<h2>Resizing the image</h2>
<h3>Returning a resized Image Method</h3>
<pre class="brush: csharp; wrap-lines: false;">
        private void ReturnResizedImage(Image img, String filename) {
            try {
                // Getting params from querystring:
                Size newSize = new Size(0, 0);
                Size maxSize = new Size(0, 0);
                if (request.QueryString[PARAM_WIDTH] != null) { newSize.Width = int.Parse(request.QueryString[PARAM_WIDTH]); }
                if (request.QueryString[PARAM_HEIGHT] != null) { newSize.Height = int.Parse(request.QueryString[PARAM_HEIGHT]); }
                if (request.QueryString[PARAM_MAXWIDTH] != null) { maxSize.Width = int.Parse(request.QueryString[PARAM_MAXWIDTH]); }
                if (request.QueryString[PARAM_MAXHEIGHT] != null) { maxSize.Height = int.Parse(request.QueryString[PARAM_MAXHEIGHT]); }

                img = resizeImage(img, CalculateNewSize(img, newSize, maxSize));
                img.Save(HttpContext.Current.Response.OutputStream, getFormat(filename));
            }
            catch (Exception e) {
                response.StatusCode = 400;
                response.Write(&quot;Bad request.&quot;);
            }
        }
</pre>
<h3>Checking the new size for the image</h3>
<pre class="brush: csharp; wrap-lines: false;">
        private static Size CalculateNewSize(Image img, Size newSize, Size max) {
            float nPercent = 1; float nPercentW = 1; float nPercentH = 1;

            // STEP 1. RESIZE TO FIX SIZES
            if (newSize.Width &gt; 0 &amp;&amp; newSize.Height &gt; 0) {
                // The smaller gets priority:
                if (img.Width != newSize.Width) nPercentW = ((float)newSize.Width / (float)img.Width);
                if (img.Height != newSize.Height) nPercentH = ((float)newSize.Height / (float)img.Height);
                if (nPercentH &lt; nPercentW) { nPercent = nPercentH; } else { nPercent = nPercentW; }
            } else if (newSize.Width &gt; 0) {
                nPercent = ((float)newSize.Width / (float)img.Width);
            } else if (newSize.Height &gt; 0) {
                nPercent = ((float)newSize.Height / (float)img.Height);
            }

            // Calculate new sizes:
            int resWidth = (int)(img.Width * nPercent);
            int resHeight = (int)(img.Height * nPercent);

            // ==================================
            // STEP 2. CHECK THE LIMITS
            if (max.Width &gt; 0 &amp;&amp; resWidth &gt; max.Width) {
                nPercent = ((float)max.Width / (float)resWidth);
                resWidth = (int)(resWidth * nPercent);
                resHeight = (int)(resHeight * nPercent);
            }
            if (max.Height &gt; 0 &amp;&amp; resHeight &gt; max.Height) {
                nPercent = ((float)max.Height / (float)resHeight);
                resWidth = (int)(resWidth * nPercent);
                resHeight = (int)(resHeight * nPercent);
            }

            return new Size(resWidth, resHeight);
        }
</pre>
<h3>Resizing the Image, simple way</h3>
<pre class="brush: csharp; wrap-lines: false;">
        private static Image resizeImage(Image imgToResize, Size size) {
            if (imgToResize.Width != size.Width || imgToResize.Height != size.Height) {
                return new Bitmap(imgToResize, size.Width, size.Height);
            } else {
                return imgToResize;
            }
        }
</pre>
<h3>Getting the format type</h3>
<p>Unfortunately, to send the image to the client in the response we need to know its format type, which we can know in various ways like checking the image filename extension or getting its mimetype. Affortunately, both of us were saved in the db:</p>
<pre class="brush: csharp; wrap-lines: false;">
        private static System.Drawing.Imaging.ImageFormat getFormat(String MimeType) {
            switch (MimeType.ToLower()) {
                case &quot;image/jpeg&quot;:
                case &quot;image/jpg&quot;: return System.Drawing.Imaging.ImageFormat.Jpeg;
                case &quot;image/gif&quot;: return System.Drawing.Imaging.ImageFormat.Gif;
                case &quot;image/png&quot;: return System.Drawing.Imaging.ImageFormat.Png;
                default: return System.Drawing.Imaging.ImageFormat.Bmp;
            }
        }
</pre>
<p>In case you prefer to use the filename:</p>
<pre class="brush: csharp; wrap-lines: false;">
    private static System.Drawing.Imaging.ImageFormat getFormat(String name) {
        switch (System.IO.Path.GetExtension(name).ToLower()) {
            case &quot;.jpeg&quot;:
            case &quot;.jpg&quot;: return System.Drawing.Imaging.ImageFormat.Jpeg;
            case &quot;.gif&quot;: return System.Drawing.Imaging.ImageFormat.Gif;
            case &quot;.png&quot;: return System.Drawing.Imaging.ImageFormat.Png;
            default: return System.Drawing.Imaging.ImageFormat.Bmp;
        }
    }
</pre>
<h2>The new Image Handler ProcessRequest</h2>
<pre class="brush: csharp; wrap-lines: false;">
        public void ProcessRequest(HttpContext context) {
            request = context.Request;
            response = context.Response;

            List&lt;SqlParameter&gt; pl = new List&lt;SqlParameter&gt;();
            pl.Add(new SqlParameter(&quot;imgId&quot;, request.QueryString[&quot;img&quot;]));
            IDataReader dr = MyNamespace.db.getReader(&quot;sp_getImage&quot;, pl);

            if (dr != null &amp;&amp; dr.Read()) {
                context.Response.ContentType = dr[&quot;mimeType&quot;].ToString();
                MemoryStream ms = new MemoryStream((byte[])dr[&quot;image&quot;]);
                Image img = System.Drawing.Image.FromStream(ms);

                if (!NeedsToBeResized(img)) { //Display directly from db:
                    context.Response.BinaryWrite((byte[])dr[&quot;image&quot;]);
                } else {
                    ReturnResizedImage(img, dr[&quot;fileName&quot;].ToString());
                }
            } else {
                response.StatusCode = 404;
                response.Write(&quot;Not found.&quot;);
            }
        }
</pre>
<h2>Finally, putting all of it together:</h2>
<pre class="brush: csharp; wrap-lines: false;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace MyNamespace {
    public class VirtualImagesHandler : IHttpHandler {

        private HttpRequest request = null;
        private HttpResponse response = null;

        public const String PARAM_WIDTH = &quot;w&quot;;
        public const String PARAM_HEIGHT = &quot;h&quot;;
        public const String PARAM_MAXWIDTH = &quot;maxw&quot;;
        public const String PARAM_MAXHEIGHT = &quot;maxh&quot;;

        public bool IsReusable { get { return true; } }
        public void ProcessRequest(HttpContext context) {
            request = context.Request;
            response = context.Response;

            //
            // TODO: Check if user has rights to access this image.
            //

            List&lt;SqlParameter&gt; pl = new List&lt;SqlParameter&gt;();
            pl.Add(new SqlParameter(&quot;imgId&quot;, request.QueryString[&quot;img&quot;]));
            IDataReader dr = MyNamespace.db.getReader(&quot;sp_getImage&quot;, pl);

            if (dr != null &amp;&amp; dr.Read()) {
                context.Response.ContentType = dr[&quot;mimeType&quot;].ToString();
                MemoryStream ms = new MemoryStream((byte[])dr[&quot;image&quot;]);
                Image img = System.Drawing.Image.FromStream(ms);

                if (!NeedsToBeResized(img)) { //Display directly from db:
                    context.Response.BinaryWrite((byte[])dr[&quot;image&quot;]);
                } else {
                    ReturnResizedImage(img, dr[&quot;fileName&quot;].ToString());
                }
            } else {
                response.StatusCode = 404;
                response.Write(&quot;Not found.&quot;);
            }
        }

        private Boolean NeedsToBeResized(Image img) {
            // If one of the params comes most probably Ill need to resize:
            if (request.QueryString[PARAM_WIDTH] != null) { return true; }
            if (request.QueryString[PARAM_HEIGHT] != null) { return true; }
            if (request.QueryString[PARAM_MAXWIDTH] != null) { return true; }
            if (request.QueryString[PARAM_MAXHEIGHT] != null) { return true; }
            return false;
        }

        private void ReturnResizedImage(Image img, String filename) {
            try {
                // Getting params from querystring:
                Size newSize = new Size(0, 0);
                Size maxSize = new Size(0, 0);
                if (request.QueryString[PARAM_WIDTH] != null) { newSize.Width = int.Parse(request.QueryString[PARAM_WIDTH]); }
                if (request.QueryString[PARAM_HEIGHT] != null) { newSize.Height = int.Parse(request.QueryString[PARAM_HEIGHT]); }
                if (request.QueryString[PARAM_MAXWIDTH] != null) { maxSize.Width = int.Parse(request.QueryString[PARAM_MAXWIDTH]); }
                if (request.QueryString[PARAM_MAXHEIGHT] != null) { maxSize.Height = int.Parse(request.QueryString[PARAM_MAXHEIGHT]); }

                img = resizeImage(img, CalculateNewSize(img, newSize, maxSize));
                img.Save(HttpContext.Current.Response.OutputStream, getFormat(response.ContentType));
            }
            catch (Exception e) {
                response.StatusCode = 400;
                response.Write(&quot;Bad request.&quot;);
            }
        }

        private static System.Drawing.Imaging.ImageFormat getFormat(String MimeType) {
            switch (MimeType.ToLower()) {
                case &quot;image/jpeg&quot;:
                case &quot;image/jpg&quot;: return System.Drawing.Imaging.ImageFormat.Jpeg;
                case &quot;image/gif&quot;: return System.Drawing.Imaging.ImageFormat.Gif;
                case &quot;image/png&quot;: return System.Drawing.Imaging.ImageFormat.Png;
                default: return System.Drawing.Imaging.ImageFormat.Bmp;
            }
        }

        private static Image resizeImage(Image imgToResize, Size size) {
            if (imgToResize.Width != size.Width || imgToResize.Height != size.Height) {
                return new Bitmap(imgToResize, size.Width, size.Height);
            } else {
                return imgToResize;
            }
        }

        private static Size CalculateNewSize(Image img, Size newSize, Size max) {
            float nPercent = 1; float nPercentW = 1; float nPercentH = 1;

            // STEP 1. RESIZE TO FIX SIZES
            if (newSize.Width &gt; 0 &amp;&amp; newSize.Height &gt; 0) {
                // The smaller gets priority:
                if (img.Width != newSize.Width) nPercentW = ((float)newSize.Width / (float)img.Width);
                if (img.Height != newSize.Height) nPercentH = ((float)newSize.Height / (float)img.Height);
                if (nPercentH &lt; nPercentW) { nPercent = nPercentH; } else { nPercent = nPercentW; }
            } else if (newSize.Width &gt; 0) {
                nPercent = ((float)newSize.Width / (float)img.Width);
            } else if (newSize.Height &gt; 0) {
                nPercent = ((float)newSize.Height / (float)img.Height);
            }

            // Calculate new sizes:
            int resWidth = (int)(img.Width * nPercent);
            int resHeight = (int)(img.Height * nPercent);

            // ==================================
            // STEP 2. CHECK THE LIMITS
            if (max.Width &gt; 0 &amp;&amp; resWidth &gt; max.Width) {
                nPercent = ((float)max.Width / (float)resWidth);
                resWidth = (int)(resWidth * nPercent);
                resHeight = (int)(resHeight * nPercent);
            }
            if (max.Height &gt; 0 &amp;&amp; resHeight &gt; max.Height) {
                nPercent = ((float)max.Height / (float)resHeight);
                resWidth = (int)(resWidth * nPercent);
                resHeight = (int)(resHeight * nPercent);
            }

            return new Size(resWidth, resHeight);
        }

        public static String getImageURL(int ImageID) {
            return SkyGuard.CSC.Config.PATH_VIRTUALIMGFOLDER + &quot;?img=&quot; + ImageID;
        }
        public static String getImageURL(int ImageID, ImageSizes sizes) {
            String url = SkyGuard.CSC.Config.PATH_VIRTUALIMGFOLDER + &quot;?img=&quot; + ImageID;
            if (sizes.Width &gt; 0) { url += &quot;&amp;&quot; + PARAM_WIDTH + &quot;=&quot; + sizes.Width.ToString(); }
            if (sizes.Height &gt; 0) { url += &quot;&amp;&quot; + PARAM_HEIGHT + &quot;=&quot; + sizes.Height.ToString(); }
            if (sizes.MaxWidth &gt; 0) { url += &quot;&amp;&quot; + PARAM_MAXWIDTH + &quot;=&quot; + sizes.MaxWidth.ToString(); }
            if (sizes.MaxHeight &gt; 0) { url += &quot;&amp;&quot; + PARAM_MAXHEIGHT + &quot;=&quot; + sizes.MaxHeight.ToString(); }

            return url;
        }

        public class ImageSizes {
            public int Width { get; set; }
            public int Height { get; set; }
            public int MaxWidth { get; set; }
            public int MaxHeight { get; set; }

            public ImageSizes() : this(-1, -1, -1, -1) { }
            public ImageSizes(int pWidth, int pHeight) {
                if (pWidth &gt; 0) Width = pWidth;
                if (pHeight &gt; 0) Height = pHeight;
                MaxHeight = -1;
                MaxWidth = -1;
            }
            public ImageSizes(int pWidth, int pHeight, int pMaxWidth, int pMaxHeight) {
                if (pWidth &gt; 0) Width = pWidth;
                if (pHeight &gt; 0) Height = pHeight;
                if (pMaxWidth &gt; 0) MaxWidth = pMaxWidth;
                if (pMaxHeight &gt; 0) MaxHeight = pMaxHeight;
            }
        }

    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/03/images-handler-with-resizing-options-in-c-net.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uploading an image to database in C#</title>
		<link>http://www.rubencanton.com/blog/2012/02/uploading-an-image-to-database-in-c.html</link>
		<comments>http://www.rubencanton.com/blog/2012/02/uploading-an-image-to-database-in-c.html#comments</comments>
		<pubDate>Tue, 28 Feb 2012 10:31:47 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[c#.net]]></category>
		<category><![CDATA[files]]></category>
		<category><![CDATA[images]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=534</guid>
		<description><![CDATA[1. Placing the FileUpload object
First, we need to set the FileUpload object, we will use the one .Net gives us:

    &#60;asp:FileUpload ID=&#34;myFile&#34; runat=&#34;server&#34; /&#62;

That was easy  
2. Getting the file from the FileUpload object
2.1 Checking the uploaded file is an image
Before going on, I want to show you this useful function [...]]]></description>
			<content:encoded><![CDATA[<h2>1. Placing the FileUpload object</h2>
<p>First, we need to set the FileUpload object, we will use the one .Net gives us:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;asp:FileUpload ID=&quot;myFile&quot; runat=&quot;server&quot; /&gt;
</pre>
<p>That was easy <img src='http://www.rubencanton.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>2. Getting the file from the FileUpload object</h2>
<h3>2.1 Checking the uploaded file is an image</h3>
<p>Before going on, I want to show you this useful function you will need later:</p>
<pre class="brush: csharp; wrap-lines: false;">
        public Boolean IsImage(HttpPostedFile pf) {
            Boolean res = false;

            switch (pf.ContentType) {
                case &quot;image/gif&quot;:
                case &quot;image/jpeg&quot;:
                case &quot;image/jpg&quot;:
                case &quot;image/bmp&quot;:
                case &quot;image/png&quot;:
                case &quot;image/pjpeg&quot;:
                case &quot;image/x-png&quot;:
                    res = true;
                    break;
                default:
                    res = false;
                    break;
            }

            if (!res) { //If the filetype doesnt work i try with the extension:
                switch (Path.GetExtension(pf.FileName)) {
                    case &quot;gif&quot;:
                    case &quot;jpeg&quot;:
                    case &quot;jpg&quot;:
                    case &quot;bmp&quot;:
                    case &quot;png&quot;:
                        res = true; break;
                    default: break;
                }
            }

            return res;
        }
</pre>
<h3>2.2 Checking Im uploading something</h3>
<p>I like to have these two useful methods:</p>
<pre class="brush: csharp; wrap-lines: false;">
        private Boolean IsUploadingAnImage() {
            return (myFile.PostedFile != null &amp;&amp; myFile.PostedFile.FileName != &quot;&quot;);
        }

        private void UploadPhoto() {
            MyNamespace.Uploads.UploadProfileImage(myFile); // A call to a class that will do the stuff (see below)
            // Do more stuff if necessary
        }
</pre>
<p>So I can do this:</p>
<pre class="brush: csharp; wrap-lines: false;">
        if (IsUploadingAnImage()) { UploadPhoto(); }
</pre>
<h3>2.3 Getting the file</h3>
<p>To get the file in the object <strong>you need a byte array to get the input</strong>, then you can use that array to save it into the db, to create a file and save it in disk or to create an image object and play with it before doing something else. Lets see:</p>
<pre class="brush: csharp; wrap-lines: false;">
// Getting the object into a byte array:
byte[] fileData = new byte[Uploader.PostedFile.ContentLength]; //We make a byte array with the file size.
Uploader.PostedFile.InputStream.Read(fileData, 0, (int)Uploader.PostedFile.ContentLength); //we read the file into our array.
</pre>
<h2>Saving it into the database</h2>
<p>Putting all of it together and using a stored that saves the image into db with its type.</p>
<pre class="brush: csharp; wrap-lines: false;">
        public void UploadProfileImage(FileUpload Uploader) {
            if (IsImage(Uploader.PostedFile)) {

                byte[] fileData = new byte[Uploader.PostedFile.ContentLength]; //We make a byte array with the file size.
                Uploader.PostedFile.InputStream.Read(fileData, 0, (int)Uploader.PostedFile.ContentLength); //we read the file into our array.

                List&lt;SqlParameter&gt; pl = new List&lt;SqlParameter&gt;();
                pl.Add(new SqlParameter(&quot;image&quot;, fileData));
                pl.Add(new SqlParameter(&quot;mimeType&quot;, Uploader.PostedFile.ContentType));

                IDataReader dr = MyNamespace.db.getReader(&quot;sp_UploadImage&quot;, pl);
                if (dr != null &amp;&amp; dr.Read()) {
                    if (dr[0].ToString().ToUpper() == &quot;OK&quot;) {
                        ImageID = (int)dr[1]; // I could get the new image id in db, for example.
                    }
                }

            } else {
                ErrorMessage = &quot;File must be an image.&quot;;
            }
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/02/uploading-an-image-to-database-in-c.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Validate forms in client side using jQuery</title>
		<link>http://www.rubencanton.com/blog/2012/02/validate-forms-in-client-side-using-jquery.html</link>
		<comments>http://www.rubencanton.com/blog/2012/02/validate-forms-in-client-side-using-jquery.html#comments</comments>
		<pubDate>Fri, 24 Feb 2012 07:00:26 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[Web security]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=507</guid>
		<description><![CDATA[There is a quick way for validating forms if you are using jQuery.
1. Download the validation plugin
You need to download the jQuery Validate plugin. Alternatively you can make a call to the online version from your code.
2. Add the plugin to your website
I presume you are yet using the latest jQuery library and you don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>There is a quick way for validating forms if you are using jQuery.</p>
<h2>1. Download the validation plugin</h2>
<p>You need to download the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery Validate plugin</a>. Alternatively you can make a call to <a href="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js">the online version</a> from your code.</p>
<h2>2. Add the plugin to your website</h2>
<p>I presume you are yet using the latest jQuery library and you don&#8217;t need any explanation on <a href="http://www.rubencanton.com/blog/2010/12/introduction-to-jquery.html">how to use it</a>, then, just add another reference to the plugin in your code so you can use it:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;script src='Scripts/jquery.-1.7.1.min.js' type='text/javascript'&gt;&lt;/script&gt;
    &lt;script src='Scripts/jquery.validate.min.js' type='text/javascript'&gt;&lt;/script&gt;
</pre>
<h2>3. Make a call to validation</h2>
<p>Now, if you just want to validate a form using default validation you only need to make a call to this function:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot;&gt;
    $(document).ready(function () {
        $('form').validate();
    });
&lt;/script&gt;
</pre>
<p>You can of course have more forms and select the one you want to validate etc. But lets simplify it for this example. Now, the form will be validated but since the rules are not set jQuery will not know what to validate. </p>
<h2>4. Adding rules to validation</h2>
<p>To add rules you only need to add style classes to the class atribute like this:</p>
<pre class="brush: xml; wrap-lines: false;">
Name &lt;input class=&quot;required&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
Website &lt;input class=&quot;required url&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
Phone &lt;input class=&quot;number&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
Email &lt;input class=&quot;required email&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
</pre>
<p>As you can see, Ive add some classes and just doing that the form will be validated and the input fields be checked with the conditions Ive added through the classes. You can add multiple conditions to make a field required and number, for example.</p>
<p>Here is a list of some of the class styles you can use:</p>
<ul style="font-weight:bold;">
<li>required</li>
<li>email</li>
<li>number (decimal)</li>
<li>digits (integer)</li>
<li>date</li>
<li>dateISO</li>
<li>url</li>
<li>creditcard</li>
</ul>
<p>You can also add some properties like minlength, maxlength or range:</p>
<pre class="brush: xml; wrap-lines: false;">
Name &lt;input class=&quot;required&quot; type=&quot;text&quot; minlength=&quot;2&quot;&gt; &lt;br /&gt;
Website &lt;input class=&quot;required url&quot; type=&quot;text&quot; maxlength=&quot;80&quot;&gt; &lt;br /&gt;
Phone &lt;input class=&quot;number&quot; type=&quot;text&quot; range=&quot;600&quot;&gt; &lt;br /&gt;
Email &lt;input class=&quot;required email&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
</pre>
<p>And that will help where adding classes wouldn&#8217;t work (you need to set a value). A list of them:</p>
<ul style="font-weight:bold;">
<li>minlength</li>
<li>maxlength</li>
<li>rangelength</li>
<li>min</li>
<li>max</li>
<li>range</li>
<li>accept (file extensions)</li>
</ul>
<h2>5. Customizing validation</h2>
<p>But despite thats so useful, quick and flexible you may need more specific conditions or just want to add your own error messages. For doing so its still very easy when you make the call to the validate function, just adding custom values:</p>
<pre class="brush: jscript; wrap-lines: false;">
    $('form').validate({
        rules: {
            txtName: required,
            website: {required: true, minlength: 5},
            phone: {required:true,
                    digits: true,
                    rangelength: [6, 9]
            },
            email {required: true}
        }, messages: {
            txtName: required : 'The name is required',
            txtSurname: { required: 'The website is required',
                          minlength: 'The website need to be at least 5 characters length'}
            phone { rangelength: 'The phone needs to be between 6 and 9 characters' }
        }
    });
</pre>
<p>You can add individual conditions without brakets like in name, or add more conditions using brackets. To make them match the fields <strong>you have to add the name property</strong> to them:</p>
<pre class="brush: xml; wrap-lines: false;">
Name    &lt;input name=&quot;name&quot; class=&quot;required&quot; type=&quot;text&quot; minlength=&quot;2&quot;&gt; &lt;br /&gt;
Website &lt;input name=&quot;website&quot; class=&quot;required url&quot; type=&quot;text&quot; maxlength=&quot;80&quot;&gt; &lt;br /&gt;
Phone   &lt;input name=&quot;phone&quot; class=&quot;number&quot; type=&quot;text&quot; range=&quot;600&quot;&gt; &lt;br /&gt;
Email    &lt;input name=&quot;email&quot; class=&quot;required email&quot; type=&quot;text&quot; &gt; &lt;br /&gt;
</pre>
<h2>6. Customizing messages style</h2>
<p>Error messages will show a label like this one:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;label class=&quot;error&quot; for=&quot;txtName&quot; generated=&quot;true&quot;&gt;&lt;/label&gt;
</pre>
<p>You can add a style in your stylespage or in the same page to change its look and make it fit your page better. Notice you can use the class .error, but also the property generated=&#8221;true&#8221; or the property &#8220;for&#8221; so that you can specify more properly in your css:</p>
<pre class="brush: css; wrap-lines: false;">
.error{} /*general error messages*/
.error[generated=true] {} /*generated error msgs when jQuery validates */
.error[for=txtName]{} /*very custom style for error msg when txtName is not correct*/
</pre>
<hr />
<p>You can check more options, methods, etc. <a href="http://docs.jquery.com/Plugins/Validation">at its documentation page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/02/validate-forms-in-client-side-using-jquery.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building your Authentication system in .Net4.0</title>
		<link>http://www.rubencanton.com/blog/2012/02/building-your-authentication-system-in-net4-0.html</link>
		<comments>http://www.rubencanton.com/blog/2012/02/building-your-authentication-system-in-net4-0.html#comments</comments>
		<pubDate>Mon, 20 Feb 2012 08:30:24 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[Web security]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=462</guid>
		<description><![CDATA[By default, .Net applications offer a prebuilt authentication system that you can use to give some privacy to your website in case its a small one. But, in case you pretend to use your existing DB with its existing users table and your existing conditions you may want to build your own authentication system.
Most of [...]]]></description>
			<content:encoded><![CDATA[<p>By default, .Net applications offer a prebuilt authentication system that you can use to give some privacy to your website in case its a small one. But, in case you pretend to use your existing DB with its existing users table and your existing conditions you may want to build your own authentication system.</p>
<p>Most of these can be built using a standard .Net format which Im going to show:</p>
<ul>
<li><a href="#webconfig">Web.config</a></li>
<li><a href="#userclass">User Class</a></li>
<li><a href="#authcookie">Authentication Cookie</a></li>
<li><a href="#loginpg">Login Page</a></li>
<li><a href="#accessobject">Accesing the User Object from any Page</a></li>
</ul>
<h2><a name="webconfig">Web.config</a></h2>
<p>Let&#8217;s start talking about the webconfig file, since as its name indicates, its the file were the site configuration resides and then the best place to configure the site authentication. You can of course build your own manual system just setting something at the master page or at any individual page, but you can save some time just learning to use the web config.</p>
<h3>Web.config Authentication tag</h3>
<p>First, let&#8217;s just say we can add four types of authentication to our website. One based in windows (so, in IIS and its OS users), another based in Microsoft Passport service and finally the one based in web forms. Normally, and as most of webpages in the net, you will use a typical web form based authentication (the one with the user/password boxes and the login button).</p>
<p>So, that&#8217;s what we add to webconfig under system.web tag:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;authentication mode=&quot;Forms&quot;&gt;&lt;forms loginUrl=&quot;~/login.aspx&quot; timeout=&quot;2880&quot;/&gt;&lt;/authentication&gt;
</pre>
<p>Notice the &#8220;loginUrl&#8221; property at the forms tag, you will set on there the location of the login page in case the user tries to access a forbidden page. Pages that require authentication will redirect the user here automatically, no need to code anything.</p>
<h3>Web.config Authorization</h3>
<p>Now, we need to set the authorization level for the whole page. This means if we want to make it an intranet or a public website (with maybe some private areas).</p>
<p>For doing so, we&#8217;ll use the authentication tag under the system.web tag and set the level of authentication needed to request the website in general. We can use multiple options but most probably you will need to know only these ones:</p>
<pre class="brush: xml; wrap-lines: false;">
    &lt;system.web&gt;
        &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.0&quot;&gt;&lt;/compilation&gt;
        &lt;authorization&gt;
                &lt;deny users=&quot;*&quot;/&gt; &lt;!-- Denies permission to anyone, website closed. --&gt;
                &lt;deny users=&quot;?&quot;/&gt; &lt;!-- Denies permission to non-authenticated users. Closed to anonymous users. You use this for an intranet. --&gt;
                &lt;deny allow=&quot;*&quot;/&gt; &lt;!-- Website open to everybody. You use this for a public website. --&gt;
        &lt;/authorization&gt;
        &lt;authentication mode=&quot;Forms&quot;&gt;&lt;forms loginUrl=&quot;~/login.aspx&quot; timeout=&quot;2880&quot;/&gt;&lt;/authentication&gt;

        &lt;pages theme=&quot;Default&quot;/&gt;
    &lt;/system.web&gt;
</pre>
<p>You have to add only one of these deny/allow tags, the one you think fits better.</p>
<h3>Web.config locations</h3>
<p>After doing that, you can add individual auth. rights for different folders or files, like login.aspx or scripts/ folder. In case your website is open to public most of its folders are too, but if you set it as an intranet have in mind that, if you don&#8217;t open to public some files and folders the ones who are not authenticated will not be able to authenticate due to forbidden access to login.aspx, and they could not see the styles or run the scripts if they have no access to the needed folders. So, you will need to add something like this under the configuration tag:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;configuration&gt;
    &lt;location path=&quot;login.aspx&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;allow users=&quot;*&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;&lt;/location&gt;
    &lt;location path=&quot;scripts&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;allow users=&quot;?&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;&lt;/location&gt;
    &lt;location path=&quot;imgs&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;allow users=&quot;?&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;&lt;/location&gt;
    &lt;location path=&quot;App_Themes&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;allow users=&quot;?&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;&lt;/location&gt;
&lt;/configuration&gt;
</pre>
<p>If your site is open to public you may use something like this instead:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;configuration&gt;
    &lt;location path=&quot;admin&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;deny users=&quot;?&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;
    &lt;location path=&quot;privateArea&quot;&gt;&lt;system.web&gt;&lt;authorization&gt;&lt;deny users=&quot;?&quot;/&gt;&lt;/authorization&gt;&lt;/system.web&gt;&lt;/location&gt;
&lt;/configuration&gt;
</pre>
<p>And that&#8217;s all you need to know about webconfig. You can search more info in Google if you need or just continue forward.</p>
<h2><a name="userclass">User class</a></h2>
<p>Now you should build a basic User class to manage your website users. I mean, if you are managing authorization and private areas in the website you sure have some way of storing those users data and, normally, that is done in a database using a Users table or similar. Here is a posible idea of how that basic User class could look like:</p>
<pre class="brush: csharp; wrap-lines: true;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace MyNameSpace {
    public class User {

        //Basic
        public int ID { get; set; }
        public String Username { get; set; }
        public String PasswordInMD5 { get; set; }
        public MyNameSpace.PermissionRol Permissions { get; set; }

        //Details
        public String Email { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Phone { get; set; }

        public User() {
            Initialize();
        }
        public User(Boolean loadFromCookie) {
            Initialize();
            if (loadFromCookie) {
                this.LoadUser(MyNameSpace.AuthCookie.GetUser()); //getting basic params from cookie
                this.LoadUser(getUser(Username, PasswordInMD5)); // getting details from db
            }
        }

        private void Initialize() {
            ID = 0;
            Username = &quot;&quot;;
            PasswordInMD5 = &quot;&quot;;
            Permissions = new MyNameSpace.PermissionRol();

            FirstName = &quot;&quot;;
            LastName = &quot;&quot;;
            Email = &quot;&quot;;
            Phone = &quot;&quot;;
        }

        public static User getUser(String username, String pass) {
            List&lt;SqlParameter&gt; pl = new List&lt;SqlParameter&gt;();
            pl.Add(new SqlParameter(&quot;userName&quot;, username));
            pl.Add(new SqlParameter(&quot;MD5password&quot;, pass));

            User u = new User();
            IDataReader dr = MyNameSpace.db.getReader(&quot;sp_getUserDetails&quot;, pl);
            if (dr != null &amp;&amp; dr.Read()) {
                u.ID = (int)dr[&quot;userId&quot;];
                u.Username = dr[&quot;userName&quot;].ToString();
                u.PasswordInMD5 = dr[&quot;userPassword&quot;].ToString();
                u.FirstName = dr[&quot;firstName&quot;].ToString();
                u.LastName = dr[&quot;lastName&quot;].ToString();
                u.Phone = dr[&quot;contactNumber&quot;].ToString();
                u.Email = dr[&quot;contactEmail&quot;].ToString();
                u.Permissions.Load(MyNameSpace.PermissionRol.getRol((int)dr[&quot;RoleId&quot;]));
            }
            return u;
        }

        /// &lt;summary&gt;
        /// Loads user details from DB having its id.
        /// &lt;/summary&gt;
        public void LoadUser(MyNameSpace.User newUser) {
            this.ID = newUser.ID;
            this.PasswordInMD5 = newUser.PasswordInMD5;
            this.Username = newUser.Username;
            this.FirstName = newUser.FirstName;
            this.LastName = newUser.LastName;
            this.Email = newUser.Email;
            this.Phone = newUser.Phone;
        }

    }

}
</pre>
<p>Let&#8217;s not discuss its properties, its just an example. You can copypaste and adapt it to your needs. It also includes a reference to a PermissionRoles class where I have the different user rights and options (so, I do not only give access to a page, but also to do different actions or visualize different items). I give you an idea of how to implement it:</p>
<pre class="brush: csharp; wrap-lines: false;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Caching;

namespace MyNameSpace {
    public class PermissionRol {

        //Basic
        public int ID { get; set; }
        public String Name { get; set; }

        //Permissions
        public Boolean UserView;
        public Boolean UserAdd;
        public Boolean UserEdit;
        public Boolean UserRemove;

        public Boolean UnitView;
        public Boolean UnitAdd;
        public Boolean UnitEdit;
        public Boolean UnitRemove;
        public Boolean UnitAssignation;

        public Boolean AdminRights;
        public Boolean EnableEditMode;

        public PermissionRol() {
            ID = 0;
            Name = &quot;&quot;;

            UserView = false;
            UserAdd = false;
            UserEdit = false;
            UserRemove = false;

            UnitView = false;
            UnitAdd = false;
            UnitEdit = false;
            UnitRemove = false;
            UnitAssignation = false;

            EnableEditMode = false;
            AdminRights = false;
        }

        public void Load(PermissionRol newRol) {
            this.ID = newRol.ID;
            this.Name = newRol.Name;

            this.UserView = newRol.UserView;
            this.UserAdd = newRol.UserAdd;
            this.UserEdit = newRol.UserEdit;
            this.UserRemove = newRol.UserRemove;

            this.UnitView = newRol.UnitView;
            this.UnitAdd = newRol.UnitAdd;
            this.UnitEdit = newRol.UnitRemove;
            this.UnitRemove = newRol.UnitRemove;
            this.UnitAssignation = newRol.UnitAssignation;

            this.EnableEditMode = newRol.EnableEditMode;
            this.AdminRights = newRol.AdminRights;
        }

        public static List&lt;PermissionRol&gt; getRoles() {
            // Try to get from cache:
            List&lt;PermissionRol&gt; lstRoles = (List&lt;PermissionRol&gt;)HttpRuntime.Cache.Get(MyNameSpace.Config.CACHE_PERMISSIONROLES);

            if (lstRoles == null) {
                lstRoles = new List&lt;PermissionRol&gt;();
                IDataReader dr = MyNameSpace.db.getReader(&quot;sp_getRoles&quot;);

                if (dr != null) {
                    while (dr.Read()) {
                        PermissionRol rol = new PermissionRol();
                        rol.ID = (int)dr[&quot;ID&quot;];
                        rol.Name = dr[&quot;Name&quot;].ToString();

                        rol.EnableEditMode = (Boolean)dr[&quot;EnableEditMode&quot;];
                        rol.UnitAdd = (Boolean)dr[&quot;UnitAdd&quot;];
                        rol.UnitAssignation = (Boolean)dr[&quot;UnitAssignation&quot;];
                        rol.UnitEdit = (Boolean)dr[&quot;UnitEdit&quot;];
                        rol.UnitRemove = (Boolean)dr[&quot;UnitRemove&quot;];
                        rol.UnitView = (Boolean)dr[&quot;UnitView&quot;];
                        rol.UserAdd = (Boolean)dr[&quot;UserAdd&quot;];
                        rol.UserEdit = (Boolean)dr[&quot;UserEdit&quot;];
                        rol.UserRemove = (Boolean)dr[&quot;UserRemove&quot;];
                        rol.UserView = (Boolean)dr[&quot;UserView&quot;];
                        rol.AdminRights = (Boolean)dr[&quot;AdminRights&quot;];

                        lstRoles.Add(rol);
                    }
                }

                //Add to cache
                HttpRuntime.Cache.Remove(MyNameSpace.Config.CACHE_PERMISSIONROLES);
                HttpRuntime.Cache.Add(MyNameSpace.Config.CACHE_PERMISSIONROLES, lstRoles, null, DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
            }

            return lstRoles;
        }

        public static PermissionRol getRol(int pID) {
            IEnumerable&lt;PermissionRol&gt; rol = from roles in getRoles() where roles.ID == pID select roles;
            return rol.ToList&lt;PermissionRol&gt;()[0];
        }

    }
}
</pre>
<h2><a name="authcookie">Authentication Cookie</a></h2>
<p>Now its time to get to next stage and build our authentication cookie. This is a special type of cookie that .Net uses to authenticate the user and make sure this user is authenticated. Which will be the difference between an anonymous user and a known one. Be care with this then since not any cookie will do. You may create your own encrypted cookie and use to it authenticate but .Net will still not recognize that user as authenticated and due to your webconfig confs the user will have no access.</p>
<p>So, let&#8217;c build our own Authentication cookie adapted to our needs in our own class:</p>
<pre class="brush: csharp; wrap-lines: false;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace MyNameSpace {
    public class AuthCookie {

        public AuthCookie() {
            //
            // TODO: Add constructor logic here
            //
        }

        public static MyNameSpace.User GetUser() {
            MyNameSpace.User u = new MyNameSpace.User();
            HttpCookie au = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (au != null) {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(au.Value);

                if (!ticket.Expired) {
                    String data = ticket.UserData;
                    u.Username = data.Split('|')[0];
                    u.PasswordInMD5 = data.Split('|')[1];
                } else {
                    LogOut();
                }
            }
            return u;
        }

        public static void LogOut() {
            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Redirect(&quot;~/login.aspx&quot;);
        }

        /// &lt;summary&gt;
        /// Creates the authentication cookie.
        /// &lt;/summary&gt;
        public static void Save(MyNameSpace.User u) {
            Save(u, false);
        }

        /// &lt;summary&gt;
        /// Creates the authentication cookie.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;u&quot;&gt;User&lt;/param&gt;
        /// &lt;param name=&quot;isPersistent&quot;&gt;Default: false.&lt;/param&gt;
        public static void Save(MyNameSpace.User u, Boolean isPersistent) {
            DateTime expirationDate = DateTime.MaxValue;
            if (isPersistent) { expirationDate = DateTime.Now.AddMonths(3); }

            String userData = u.Username + &quot;|&quot; + u.PasswordInMD5;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, &quot;CSC&quot;, DateTime.Now,
                expirationDate, isPersistent, userData, FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);

            HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
        }

    }
}
</pre>
<p>This one is pretty simple, it has a method to Save the Cookie sending a User object (which we did before) and another to get it. Also, we can use it to LogOut so all the Login/Logout things are kept here. What I save in the Cookie is the username and password in MD5, I decided to go through this type of authentication for this test project, but of course you can use different ways of doing it (in fact, I tend to use different combinations).</p>
<h2><a name="loginpg">Login Page</a></h2>
<p>Finally, we have to set the code for the Login Page. Whatever the layout you use you will most probably end up using some user/pass combination. So this is it:</p>
<pre class="brush: csharp; wrap-lines: false;">
    public partial class Login : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            lbErrorMessage.Text = &quot;&quot;;
        }

        protected void Page_PreRender(object sender, EventArgs e) {
            pnlErrorMessage.Visible = (lbErrorMessage.Text.Length &gt; 0);
        }

        protected void BTNLogin_Click(object sender, EventArgs e) {
            MyNameSpace.User u = MyNameSpace.User.getUser(TXTUser.Text, getInMD5(TXTPass.Text));

            if (u.ID &gt; 0) {
                MyNameSpace.AuthCookie.Save(u);
                Redirect();
            } else {
                lbErrorMessage.Text = &quot;Invalid Username or Password.&quot;;
            }
        }

        private void Redirect() {
            if (Request.QueryString[&quot;ReturnUrl&quot;] != null &amp;&amp; Request.QueryString[&quot;ReturnUrl&quot;].ToString().Length &gt; 2) {
                Response.Redirect(Request.QueryString[&quot;ReturnUrl&quot;]);
            } else {
                Response.Redirect(&quot;~/default.aspx&quot;);
            }
        }

        public static String getInMD5(String inputString) {
            byte[] input = Encoding.UTF8.GetBytes(inputString);
            byte[] output = MD5.Create().ComputeHash(input);
            StringBuilder sb = new StringBuilder(output.Length);
            for (int i = 0; i &lt; output.Length; i++) {
                sb.Append(output[i].ToString(&quot;X2&quot;));
            }
            return sb.ToString();
        }

    }
</pre>
<h2><a name="accessobject">Accesing the User from any Page</a></h2>
<p>We can then create this User object at our Master Page so that it loads on any request (in case we need this to be done) and access it from our pages. If you don&#8217;t know how to do this, you can check <a href="http://www.rubencanton.com/blog/2011/09/using-global-objects-in-your-page-with-a-master-page.html">how to access a MasterPage object from any page</a> with more detail.</p>
<p><strong>Master Page Example:</strong></p>
<pre class="brush: csharp; wrap-lines: false;">
        public MyNameSpace.User User;

        protected void Page_Init(object sender, EventArgs e) {
            User = new MyNameSpace.User(true);
        }

        protected void Page_Load(object sender, EventArgs e) {
            lbWelcomeMsg.Text = &quot;You are logged in as &quot; + User.Username;
        }
</pre>
<p><strong>Default page example:</strong></p>
<pre class="brush: csharp; wrap-lines: false;">
    public partial class Default1 : System.Web.UI.Page {
        MyNameSpace.User User;

        protected void Page_Load(object sender, EventArgs e) {
            User = ((MyNameSpace.MyMasterPage)Page.Master).User;
            lbUserName.Text = User.FirstName;
        }

    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/02/building-your-authentication-system-in-net4-0.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get a string in MD5 in C#.Net</title>
		<link>http://www.rubencanton.com/blog/2012/02/how-to-get-a-string-in-md5-in-c-net.html</link>
		<comments>http://www.rubencanton.com/blog/2012/02/how-to-get-a-string-in-md5-in-c-net.html#comments</comments>
		<pubDate>Fri, 17 Feb 2012 07:22:32 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[Web security]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=455</guid>
		<description><![CDATA[Here it is:

        public static String getInMD5(String inputString) {
            byte[] input = Encoding.UTF8.GetBytes(inputString);
            byte[] output = MD5.Create().ComputeHash(input);
          [...]]]></description>
			<content:encoded><![CDATA[<p>Here it is:</p>
<pre class="brush: csharp; wrap-lines: false;">
        public static String getInMD5(String inputString) {
            byte[] input = Encoding.UTF8.GetBytes(inputString);
            byte[] output = MD5.Create().ComputeHash(input);
            StringBuilder sb = new StringBuilder(output.Length);
            for (int i = 0; i &lt; output.Length; i++) {
                sb.Append(output[i].ToString(&quot;X2&quot;));
            }
            return sb.ToString();
        }
</pre>
<p>You may need this too:</p>
<pre class="brush: csharp; wrap-lines: false;">
using System.Text;
using System.Security.Cryptography;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/02/how-to-get-a-string-in-md5-in-c-net.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

