<?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>Thu, 02 Feb 2012 10:48:59 +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>Updating Campaign Member using Salesforce API and C#</title>
		<link>http://www.rubencanton.com/blog/2012/02/updating-campaign-member-using-salesforce-api-and-c.html</link>
		<comments>http://www.rubencanton.com/blog/2012/02/updating-campaign-member-using-salesforce-api-and-c.html#comments</comments>
		<pubDate>Thu, 02 Feb 2012 10:45:46 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[c#.net]]></category>
		<category><![CDATA[salesforce]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=416</guid>
		<description><![CDATA[Well, if you check at Salesforce API documentation and follow their tutorial to connect to SF database and request data, everything should be fine. The API its pretty flexible and solid. But, once you get to the update point you may find some problem&#8230;
I connected to Salesforce and requested my CampaignMember, loading it into an [...]]]></description>
			<content:encoded><![CDATA[<p>Well, if you check at Salesforce API documentation and follow their tutorial to connect to SF database and request data, everything should be fine. The API its pretty flexible and solid. But, once you get to the update point you may find some problem&#8230;</p>
<p>I connected to Salesforce and requested my CampaignMember, loading it into an object called &#8220;CampaignMember&#8221; (yes, im so original). Then, if I tried to update it using something like:</p>
<pre class="brush: csharp; wrap-lines: false;">
Salesforce.SaveResult[] saveResults = sf.update(new Salesforce.sObject[] { CampaignMember });
</pre>
<p>It would not work, since it seems that object has every field filled and would try to update all of them, including the read-only ones. So I would receive a saveResults object with the error message &#8220;<em>Unable to create/update fields: CampaignId, HasResponded, LeadId. Please check the security settings of this field and verify that it is read/write for your profile</em>&#8220;. And that&#8217;s why instead of using the loaded object <strong>you need to create a new one</strong>, set the value you want to update and update just that field.</p>
<p>Then, not reading properly last message, you may think as I did to create a new object (let&#8217;s say uCampaignMember) and set uCampaignMember.HasResponded = true; but unfortunately in my case, that field was read-only again. Ok, now I&#8217;m stock. <strong>How can I update that now if its read-only???</strong> Luckily after testing here and there I found out <strong>you have to update its Status instead</strong>, doing something like this:</p>
<pre class="brush: csharp; wrap-lines: false;">
            if (CampaignMember == null) {
                return false;
            } else {
                Connect();

                try {
                    Salesforce.CampaignMember uCampaignMember = new Salesforce.CampaignMember();
                    uCampaignMember.Id = CampaignMember.Id;
                    uCampaignMember.Status = &quot;Responded&quot;;
                    Salesforce.SaveResult[] saveResults = sf.update(new Salesforce.sObject[] { uCampaignMember });
                    if (saveResults[0].success) {
                        return true;
                    } else {
                        return false;
                    }
                }
                catch (Exception ex) {
                    throw (ex);
                }
            }
</pre>
<p>And that will work. If you want to set the campaign member to &#8220;not responded&#8221; again, just set Status = &#8220;Sent&#8221;.</p>
<h2>Conclusions</h2>
<p>When sending an object to be updated it will try to update all the fields the object has filled using its id for the where clause. So, if you read an object from db, modify some of its properties and use that same object to update it on the db it will try to update every field, <strong>including the read-only ones</strong>, and that will not work.</p>
<p>To update an object you will need then, to create a new one, fill in only the fields you want to update and send it to be updated. Taking care not to fill any read-only field.</p>
<p>Finally, if you are trying to update a Campaign Member to set that it has responded to an email campaign, instead of updating HasResponded = true, as you may think would be the logic, since HasResponded is read-only you will have to update its status instead, like in the code above.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/02/updating-campaign-member-using-salesforce-api-and-c.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Embedding images in an Email sent by ASP.Net Server</title>
		<link>http://www.rubencanton.com/blog/2012/01/embedding-images-in-an-email-sent-by-asp-net-server.html</link>
		<comments>http://www.rubencanton.com/blog/2012/01/embedding-images-in-an-email-sent-by-asp-net-server.html#comments</comments>
		<pubDate>Wed, 11 Jan 2012 09:49:34 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>
		<category><![CDATA[emails]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=397</guid>
		<description><![CDATA[If you want to embed your images in an email sent using ASP.Net server instead than using URLs you can use an AlternateView and use the mime standard to embed them:

    using System.Net.Mail;

    protected void SendBTN_Click(object sender, EventArgs e) {

        // Send [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to embed your images in an email sent using ASP.Net server instead than using URLs you can use an AlternateView and use the mime standard to embed them:</p>
<pre class="brush: csharp; wrap-lines: false;">
    using System.Net.Mail;

    protected void SendBTN_Click(object sender, EventArgs e) {

        // Send email using ASP.Net:
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

        message.From = new System.Net.Mail.MailAddress(Email_From);
        message.To.Add(Email_To);
        message.Bcc.Add(Email_BCC);
        message.Subject = Email_Subject;
        message.IsBodyHtml = true;
        message.AlternateViews.Add(getS4HRegisteredUsersWithoutAnOrderBody_ForEmail(Customer.Name));

        SmtpClient smtp = new SmtpClient(&quot;subdom.myserver.com&quot;);
        smtp.Send(message);

        // Show some &quot;Email Sent&quot; msg and all that stuff or return ok.
    }

private AlternateView getS4HRegisteredUsersWithoutAnOrderBody_ForEmail(String CustName) {
        StringBuilder body = new StringBuilder();
        body = SkyGuard.MIS.Email.getTemplate(&quot;S4HRegisteredUserWithoutOrder.htm&quot;);
        body.Replace(&quot;[SUBJECT]&quot;, Email_Subject);
        body.Replace(&quot;[CUSTNAME]&quot;, CustName);
        //These keys are set into the image src attribute
        body.Replace(&quot;[LOGO_IMGSRC]&quot;, &quot;cid:logo&quot;); //Notice that we are adding a cid:id as the image source
        body.Replace(&quot;[SUPPORT_PHOTO_IMGSRC]&quot;, &quot;cid:avatar&quot;);
        body.Replace(&quot;[SIGNATURE_IMGSRC]&quot;, &quot;cid:signature&quot;);

        AlternateView view = AlternateView.CreateAlternateViewFromString(body.ToString(), null, System.Net.Mime.MediaTypeNames.Text.Html);

        //Company Logo
        LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath(&quot;~/imgs/Emails/Company_logo.png&quot;), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        logo.ContentId = &quot;logo&quot;;
        LinkedResource avatar = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath(&quot;~/imgs/Emails/Support_Avatar.png&quot;), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        avatar.ContentId = &quot;avatar&quot;;
        LinkedResource signature = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath(&quot;~/imgs/Emails/Support_Signature.png&quot;), System.Net.Mime.MediaTypeNames.Image.Jpeg);
        signature.ContentId = &quot;signature&quot;;

        view.LinkedResources.Add(logo);
        view.LinkedResources.Add(avatar);
        view.LinkedResources.Add(signature);

        return view;
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2012/01/embedding-images-in-an-email-sent-by-asp-net-server.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mailto: and its parameters</title>
		<link>http://www.rubencanton.com/blog/2011/12/mailto-tricks-and-parameters.html</link>
		<comments>http://www.rubencanton.com/blog/2011/12/mailto-tricks-and-parameters.html#comments</comments>
		<pubDate>Wed, 21 Dec 2011 11:29:57 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web standards]]></category>
		<category><![CDATA[emails]]></category>
		<category><![CDATA[html41]]></category>
		<category><![CDATA[xhtml]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=384</guid>
		<description><![CDATA[Mailto is a link &#8220;address&#8221; we can set to an anchor tag to let the user send an email to someone with just a click. Something like this:

&#60;a href=&#34;mailto:someone@someserver.com&#34;&#62;Send email&#60;/a&#62;

That would show something like this:
Send email
If you click on there, and you have configured in your PC a default email software to handle it, Outlook [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Mailto</strong> is a link &#8220;address&#8221; we can set to an anchor tag to let the user send an email to someone with just a click. Something like this:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;a href=&quot;mailto:someone@someserver.com&quot;&gt;Send email&lt;/a&gt;
</pre>
<p>That would show something like this:<br />
<a href="mailto:someone@someserver.com">Send email</a></p>
<p>If you click on there, <strong>and you have configured in your PC a default email software</strong> to handle it, Outlook or the software you are using will open with a blank email with just an address at the &#8220;To&#8221; field, the one written in the link. You can also configure your browser to open your Gmail/hotmail/whatever account when doing this.</p>
<p>Now, what if you wanted to send that email with a default subject, cc, bcc or including body? Well you can, just adding parameters as if it were an url like this:</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;a href=&quot;mailto:someone@someserver.com?subject=Default subject&amp;cc=someone@tocopy.com&amp;bcc=hidden@copied.com&amp;body=Lets start saying this&quot;&gt;Send email&lt;/a&gt;
</pre>
<p>Which would look like this:<br />
<a href="mailto:someone@someserver.com?subject=Default subject&#038;cc=someone@tocopy.com&#038;bcc=hidden@copied.com&#038;body=Lets start saying this">Send email</a></p>
<h2>List of parameters</h2>
<ul>
<li><strong>subject</strong>: The email subject.</li>
<li><strong>cc</strong>: List of emails to send a copy.</li>
<li><strong>bcc</strong>: List of emails to send a hidden copy (rest of recipients will not see it).</li>
<li><strong>body:</strong> Some text to add as the email body by default. Limited to 255 characters.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/12/mailto-tricks-and-parameters.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How can I force a page jump in HTML printing?</title>
		<link>http://www.rubencanton.com/blog/2011/12/how-can-i-force-a-page-jump-in-html-printing.html</link>
		<comments>http://www.rubencanton.com/blog/2011/12/how-can-i-force-a-page-jump-in-html-printing.html#comments</comments>
		<pubDate>Thu, 08 Dec 2011 09:40:08 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[Web standards]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=372</guid>
		<description><![CDATA[If you would like to decide when the page will break and the next one will be started when your web page is printed you can use three CSS2.0 styles to set this &#8220;jump&#8221;.

page-break-before: Sets the element page break behavoir before the element starts.
page-break-inside: Lets you set that the page break behavior has to be [...]]]></description>
			<content:encoded><![CDATA[<p>If you would like to <strong>decide when the page will break and the next one will be started when your web page is printed</strong> you can use three CSS2.0 styles to set this &#8220;jump&#8221;.</p>
<ul>
<li><strong>page-break-before</strong>: Sets the element page break behavoir before the element starts.</li>
<li><strong>page-break-inside</strong>: Lets you set that the page break behavior has to be avoided inside this element.</li>
<li><strong>page-break-after</strong>: Sets the element page break behavoir after the element ends.</li>
</ul>
<p>So, you can for example add this style to a table and the table will start in a new page when the page is printed:</p>
<pre class="brush: css; wrap-lines: false;">
    table.details {page-break-before: always;}
</pre>
<p>Or you can have an style like this and use it as a page-breaker.</p>
<pre class="brush: css; wrap-lines: false;">
    .page-break {page-break-before: always;}
</pre>
<pre class="brush: xml; wrap-lines: false;">
    &lt;div class=&quot;page-break&quot;&gt;&lt;/div&gt;
</pre>
<p>Finally, you may want some element to be printed in the same page, making it break to a new page in case it doesn&#8217;t fit in the current one:</p>
<pre class="brush: css; wrap-lines: false;">
    table td.nobreaks {page-break-inside: avoid;}
</pre>
<p>Or you may want to avoid that an element that doesnt fits completely in a page provokes a jump, so you use all the possible space:</p>
<pre class="brush: css; wrap-lines: false;">
    h1 {page-break-before: avoid;}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/12/how-can-i-force-a-page-jump-in-html-printing.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding an HTTP Handler to manage Images requests in .Net</title>
		<link>http://www.rubencanton.com/blog/2011/09/adding-an-http-handler-to-manage-images-requests-in-net.html</link>
		<comments>http://www.rubencanton.com/blog/2011/09/adding-an-http-handler-to-manage-images-requests-in-net.html#comments</comments>
		<pubDate>Thu, 15 Sep 2011 21:32:21 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>
		<category><![CDATA[handlers]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[images]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=365</guid>
		<description><![CDATA[This time I found myself in a very interesting challenge. We store user profile and login images in a server folder and users update their images as they need. Sometimes, when you make a release, it is just better to remove everything and paste the new version (just in case some old file remains on [...]]]></description>
			<content:encoded><![CDATA[<p>This time I found myself in a very interesting challenge. We store user profile and login images in a server folder and users update their images as they need. Sometimes, when you make a release, it is just better to remove everything and paste the new version (just in case some old file remains on there) which, in case you forget, may end with the user images removed. <strong>What a problem!</strong></p>
<p>As always, there are different solutions for this, like using SQL Server to store the images, but I decided to use <strong>an external folder</strong> which the application would have access and edit rights <strong>and a virtual path</strong>. Saving the images was not a deal, just using a <em>FileStream</em> object and <em>Write</em> method. <strong>The problem came when having to send the images to the user on a request.</strong></p>
<p>If they are stored in a virtual path, <strong>there isn&#8217;t a real path for them in the site</strong>, there is no <em>www.mysite.com/imgs/img.jpg</em>, I have a \\imgs\img.jpg instead. So, how could I set an url for that image so the browser can get it?</p>
<p>Well, the solution was <strong>to use some virtual path and return the image when the user tried to access it</strong>, this can be done with a Module checking each request to the application, with a webservice, with a fake aspx page that returns an image instead than a page or with a handler. <strong>I decided to use the handler since it seems the best option for this purpose</strong>.</p>
<p>First, I made the handler just creating a new class, made it use the <em>IHttpHandler</em> interface to make it &#8220;interfaceable&#8221; and then added the rest of the behavior:</p>
<pre class="brush: csharp; wrap-lines: false;">
public class UserImagesHandler : IHttpHandler
{
	public UserImagesHandler() { }
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context) {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        String file = System.IO.Path.GetFileName(request.Path);

        context.Response.ContentType = &quot;image/&quot; + System.IO.Path.GetExtension(file).Replace(&quot;.&quot;, &quot;&quot;);
        if (request.RawUrl.ToLower().Contains(&quot;profile&quot;)) {
            response.TransmitFile(MyNameSpace.Config.PATH_IMG_USER_PROFILE + file);
        } else if (request.RawUrl.ToLower().Contains(&quot;login&quot;)) {
            response.TransmitFile(MyNameSpace.Config.PATH_IMG_USER_LOGIN + file);
        } else {
            response.StatusCode = 404;
            response.Write(&quot;Not found.&quot;);
        }

    }
}
</pre>
<p>The method <em>IsReusable</em> comes with the <em>IHttpHandler</em> interface and is used to determine if the handler should be kept in memory and be reused by any request or should make a new instance for every request. In our case our handler should be reusable so it handles every request saving proc time and memory.</p>
<p>Now, <strong>I need to say IIS to send these requests to this handler</strong>. I can do that using the IIS configuration, but that&#8217;s limited to the file extension (you can only make a handler for each file extension, you can still create a new file extension for your handler but.. that wasn&#8217;t my idea) or you can set it at the webconfig which gives you more flexibility.</p>
<p>There are two ways for adding this to the webconfig <strong>depending on if you are using IIS6 or IIS7</strong>, since you may have IIS6 at local and 7 at production or viceversa you may want to use both ways so it will work at any IIS.</p>
<p>First way, <strong>in IIS6</strong>, it is set under the <em>&lt;system.web></em> tag:</p>
<pre class="brush: xml; wrap-lines: false;">
	&lt;system.web&gt;
		&lt;httpHandlers&gt;
            &lt;add verb=&quot;*&quot; path=&quot;imgs/users/*/*&quot; type=&quot;UserImagesHandler&quot; /&gt;
		&lt;/httpHandlers&gt;
	&lt;/system.web&gt;
</pre>
<p>Second, for <strong>IIS7</strong>, under the <em>&lt;system.WebServer></em> tag:</p>
<pre class="brush: xml; wrap-lines: false;">
	&lt;system.webServer&gt;
		&lt;handlers&gt;
            &lt;add verb=&quot;*&quot; path=&quot;imgs/users/*/*&quot; type=&quot;UserImagesHandler&quot; name=&quot;UserImagesHandler&quot; /&gt;
		&lt;/handlers&gt;
	&lt;/system.webServer&gt;
</pre>
<p>Once thats done your handler should work and <strong>the requests for the images in the virtual path will be catched and responsed with what we have at the real folder</strong>. We can also add other features like access control since this is a full request and we have access to the session, cookies or auth. cookies. We could also add querystrings to resize the responsed images, make any log or any other thing you want to control.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/09/adding-an-http-handler-to-manage-images-requests-in-net.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using global objects in your page with a Master Page</title>
		<link>http://www.rubencanton.com/blog/2011/09/using-global-objects-in-your-page-with-a-master-page.html</link>
		<comments>http://www.rubencanton.com/blog/2011/09/using-global-objects-in-your-page-with-a-master-page.html#comments</comments>
		<pubDate>Wed, 07 Sep 2011 18:37:39 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=361</guid>
		<description><![CDATA[MasterPages are very useful to set the site structure like a header and footer, but, they can also help managing authorization or global issues of the site just declaring the needed variables on it and using them, if necessary, from the content pages or user controls. Let&#8217;s see this with an example, imagine we need [...]]]></description>
			<content:encoded><![CDATA[<p><strong>MasterPages</strong> are very useful to set the site structure like a header and footer, but, <strong>they can also help managing authorization or global issues of the site</strong> just declaring the needed variables on it and using them, if necessary, from the content pages or user controls. Let&#8217;s see this with an example, imagine we need to add a site navigator object for showing dynamic menus, a navigator and other issues.</p>
<p>First of all, we need to declare that variable as a public property:</p>
<pre class="brush: csharp; wrap-lines: false;">
public MyLibrary.Navigator Navi {get; set;}
</pre>
<p>We need to initialize the object (because we are using an object in this example) before accesing it or we&#8217;ll find a null reference. If we do that in the Page_Load, we will find that the <em>Page.Page_Load</em> loads before the <em>MasterPage.Page_Load</em> giving us a null reference in case we access it from the <em>Page_Load</em> at the child Page. So, <strong>we need to initialize it in the <em>MasterPage.Page_Init</em></strong> to avoid problems:</p>
<pre class="brush: csharp; wrap-lines: false;">
        protected void Page_Init(object sender, EventArgs e) {
            Navi = new MyLibrary.Navigator();
        }
</pre>
<h2>Accessing the object from a Page</h2>
<p>Now, we can access the object from the page without a problem. Let&#8217;s see how:</p>
<pre class="brush: csharp; wrap-lines: false;">
    protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack) {
            ((MyProject.SiteMaster)this.Master).Navi.LoadOrSomethingElse();
        }
    }
</pre>
<p>When we access the <em>Page.Master</em> property it gives us a generic MasterPage, so, if we want to access our object <strong>we will have to cast that generic MasterPage to our specific MasterPage</strong>. In this example, our MasterPage was inside a namespace called &#8220;MyProject&#8221; and our MasterPage class was called &#8220;SiteMaster&#8221;.</p>
<p>Once we have got access to the MasterPage and its properties <strong>we can now access our global object</strong> and use it calling its methods or properties.</p>
<p><strong>Remember</strong>: You need to cast the MasterPage to be able to access your specific MasterPage properties.</p>
<p><strong>Warning</strong>: For doing this you need to reference the Master Page from the Page, this is done by default if you have set the Page &#8220;MasterPage&#8221; property to the needed MasterPage, <strong>if not, you will have to add a manual reference</strong> (note: I&#8217;ve not tried it).</p>
<h2>Accessing the MasterPage from a Web User Control</h2>
<p>Now that we have accessed a MasterPage from a Page, and that lets us access a &#8220;global&#8221; object or similar, we may need to access it from a Web User Control too. Imagine&#8230; what if we make a Menu Control and place it on the page making it totally independent? It would be able to get the User object from the Master Page and show only the options avaliable for this user, without having to make another object and requesting again to the DB.</p>
<p>This time, since the <em>Web User Control</em> isn&#8217;t going to have a reference to the <em>MasterPage </em>in one of its properties we have to add a reference manually:</p>
<pre class="brush: csharp; wrap-lines: false;">
&lt;%@ Register TagPrefix=&quot;mp&quot; TagName=&quot;SiteMaster&quot; Src=&quot;~/Site.master&quot; %&gt;
</pre>
<p>Now, we can access it as we did on the Page:</p>
<pre class="brush: csharp; wrap-lines: false;">
    protected void Page_PreRender(object sender, EventArgs e) {
        user = ((MyProject.SiteMaster)this.Page.Master).User;
        // Do the rest of the stuff
    }
</pre>
<p><strong>Remember</strong>: You need to add a reference to the MasterPage in the <em>Web User Control</em> to be able to access its namespace.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/09/using-global-objects-in-your-page-with-a-master-page.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTTP Server Status</title>
		<link>http://www.rubencanton.com/blog/2011/08/http-server-status.html</link>
		<comments>http://www.rubencanton.com/blog/2011/08/http-server-status.html#comments</comments>
		<pubDate>Tue, 23 Aug 2011 18:18:30 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web standards]]></category>
		<category><![CDATA[http]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=354</guid>
		<description><![CDATA[When a server answers a client request it gives an status code in the answer header that informs you if everything has gone ok or there has been any issue. Those statuses are divided in 5 groups:

1xx: Informational.
2xx: Success.
3xx: Redirect commands. Very important in SEO.
4xx: Client error.
5xx: Server error.

Between them, the most common and the [...]]]></description>
			<content:encoded><![CDATA[<p>When a server answers a client request it gives an status code in the answer header that informs you if everything has gone ok or there has been any issue. Those statuses are divided in 5 groups:</p>
<ul>
<li><strong>1xx</strong>: Informational.</li>
<li><strong>2xx</strong>: Success.</li>
<li><strong>3xx</strong>: Redirect commands. Very important in SEO.</li>
<li><strong>4xx</strong>: Client error.</li>
<li><strong>5xx</strong>: Server error.</li>
</ul>
<p>Between them, the most common and the ones you may find while developing websites are these:</p>
<ul>
<li><strong>100: Continue</strong>. The first part of the request is accepted and you should continue sending the rest if there was anything else to send. You may find it if working with AJAX or webservices.</li>
<li><strong>200: OK. The request has been answered without any problem</strong>.</li>
<li><strong>201: Created</strong>. When a new resource has succesfully been created due to the request.</li>
<li><strong>301: Moved permanently</strong>. Used when a page has moved to a new location, very important in SEO if you don&#8217;t want to lose PR.</li>
<li><strong>302: Found (Moved temporarily)</strong>. This is the standard temporary redirection code.</li>
<li><strong>303: See other (Moved temporarily)</strong>. If the request was a POST it has to be changed to GET in the new resource.</li>
<li><strong>307: Temporary redirect</strong>. Read down.</li>
<li><strong>400: Bad request</strong>. It happens when the user sets a querystring with manual data, for example.</li>
<li><strong>401: Unauthorized</strong></li>
<li><strong>403: Forbidden</strong></li>
<li><strong>404: Not found.</strong> One of the most popular.</li>
<li><strong>500: Internal Server Error</strong>. It happens a lot when working in localhost and should never happen in production.</li>
</ul>
<h2>Difference between 302, 303 and 307 redirects</h2>
<p>Well, when a resource has changed its location temporarily and you send data using the POST method the client should ask you if you want to send that data to the new resource or not. Since that was a bit annoying for users browser-makers decided to skip the standard, not unaccomplisshing it, but doing something not specificated which was to convert the POST request in a GET request and make a GET to the new URI.</p>
<p>Technically they do not have to ask the user because <strong>its a GET request instead than a POST</strong>, but technically too <strong>they are not following the standard</strong> but skiping it with a trick (like if this were the Formula 1!). So the standard was updated and two new statuses were created: 303 and 307.</p>
<p>303 specifies that, yes, you should resend the POST data in a GET to the new URI, while 307 says that, by all means, <strong>you have to ask the user</strong>. 302 is then ambiguous (well, it really isn&#8217;t, but since its behavour was reinterpreted by browser-makers officially it should act as a 307 but in real life it is acting as a 303).</p>
<p>So there you have, standards and how developers do not follow them <img src='http://www.rubencanton.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>There are more <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">Server statuses</a> at the w3.org.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/08/http-server-status.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linking a .Net Label Control with an input</title>
		<link>http://www.rubencanton.com/blog/2011/08/linking-a-label-with-an-input.html</link>
		<comments>http://www.rubencanton.com/blog/2011/08/linking-a-label-with-an-input.html#comments</comments>
		<pubDate>Fri, 19 Aug 2011 19:31:20 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=347</guid>
		<description><![CDATA[In standard HTML label tags are used to assign some text to an input inside a form, giving the user the option to click the text in the label and causing the assigned input to be clicked too. This is very useful for CheckBoxes and Radio Buttons.

&#60;!-- Standard HTML4.1 --&#62;
&#60;input type=&#34;checkbox&#34; id=&#34;CHKCandies&#34; value=&#34;1&#34; /&#62;
&#60;label for=&#34;CHKCandies&#34;&#62;I [...]]]></description>
			<content:encoded><![CDATA[<p>In standard HTML <strong>label tags are used to assign some text to an input inside a form</strong>, giving the user the option to click the text in the label and causing the assigned input to be clicked too. This is very useful for CheckBoxes and Radio Buttons.</p>
<pre class="brush: xml; wrap-lines: false;">
&lt;!-- Standard HTML4.1 --&gt;
&lt;input type=&quot;checkbox&quot; id=&quot;CHKCandies&quot; value=&quot;1&quot; /&gt;
&lt;label for=&quot;CHKCandies&quot;&gt;I want some candies&lt;/label&gt;
</pre>
<p>In .Net you can always assign some text to a CheckBox or Radio Button using its <em>Text</em> property, but, in case you want to add some functionality to that text like a link in the typical &#8220;<em>[ ] I&#8217;m agree with the &lt;a>Terms of use&lt;/a></em>&#8221; or similar <strong>you may find that the <em>Text</em> property in a Radio Button isn&#8217;t enough</strong>.</p>
<p>Fortunately the <strong>Label control</strong> not only has a <em>Text</em> attibute but also acts as a container letting you write anything between its tags. So, <strong>you can add more lines of text, links and other labels inside it</strong>. Once done, <strong>to assign it to an input control you can use the property <em>AssociatedControlID</em></strong>, the label will now be linked with that control and your Radio Buttons and CheckBoxes will be checked/unchecked when you click the associated text, making them easier to use.</p>
<pre class="brush: csharp; wrap-lines: false;">
//Example 1:
&lt;asp:Label ID=&quot;lbTermsUse&quot; runat=&quot;server&quot; AssociatedControlID=&quot;CHKTerms&quot;&gt;
   I agree to
   &lt;a href=&quot;TermsAndConditions.aspx&quot; target=&quot;_blank&quot;&gt;terms and conditions&lt;/a&gt;
   &lt;span class=&quot;highlight&quot;&gt;*&lt;/span&gt;
&lt;/asp:Label&gt;
&lt;asp:CheckBox ID=&quot;CHKTerms&quot; runat=&quot;server&quot; class=&quot;required&quot; /&gt;

//Example 2:
&lt;div class=&quot;option&quot;&gt;
   &lt;asp:RadioButton runat=&quot;server&quot; GroupName=&quot;EmergencyCl&quot; ID=&quot;eOneYear&quot; AutoPostBack=&quot;true&quot;
      OnCheckedChanged=&quot;eOneYear_CheckedChanged&quot; /&gt;
   &lt;asp:Label ID=&quot;Label4&quot; runat=&quot;server&quot; Text=&quot;&quot; AssociatedControlID=&quot;eOneYear&quot;&gt;
      One year service for &lt;br /&gt;&amp;pound;&lt;asp:Label ID=&quot;e12Months&quot; runat=&quot;server&quot;&gt;&lt;/asp:Label&gt; per month
   &lt;/asp:Label&gt;
&lt;/div&gt;
&lt;div class=&quot;option&quot;&gt;
   &lt;asp:RadioButton runat=&quot;server&quot; GroupName=&quot;EmergencyCl&quot; ID=&quot;eTwoYear&quot; AutoPostBack=&quot;true&quot;
      OnCheckedChanged=&quot;eTwoYear_CheckedChanged&quot; /&gt;
   &lt;asp:Label ID=&quot;Label5&quot; runat=&quot;server&quot; Text=&quot;&quot; AssociatedControlID=&quot;eTwoYear&quot;&gt;
      Two years service for &lt;br /&gt;&amp;pound;&lt;asp:Label ID=&quot;e24Months&quot; runat=&quot;server&quot;&gt;&lt;/asp:Label&gt; per month
   &lt;/asp:Label&gt;
&lt;/div&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/08/linking-a-label-with-an-input.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paginate Grid Views in C#.Net</title>
		<link>http://www.rubencanton.com/blog/2011/08/paginate-grid-views.html</link>
		<comments>http://www.rubencanton.com/blog/2011/08/paginate-grid-views.html#comments</comments>
		<pubDate>Mon, 08 Aug 2011 19:02:55 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=337</guid>
		<description><![CDATA[Standard pagination
To paginate a Grid view you only need to set the property &#8220;AllowPaging&#8221; to True and set an event for &#8220;PageIndexChanging&#8221;. You can do all this just using the properties panel. Once you have it done you need to set the gridview actual IndexPage and DataBind() it again, something like this:

protected void ResultsGrid_PageIndexChanging(object sender, [...]]]></description>
			<content:encoded><![CDATA[<h2>Standard pagination</h2>
<p>To paginate a Grid view you only need to set the property &#8220;<strong><em>AllowPaging</em></strong>&#8221; to True and set an event for &#8220;PageIndexChanging&#8221;. You can do all this just using the properties panel. Once you have it done you need to set the gridview actual <em>IndexPage</em> and <em>DataBind()</em> it again, something like this:</p>
<pre class="brush: csharp; wrap-lines: false;">
protected void ResultsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
   ResultsGrid.PageIndex = e.NewPageIndex;
   LoadResults(); //This will redatabind the GV
   }
</pre>
<p>Those easy steps will give you a Grid View with standard pagination, you can modify some of its properties like:</p>
<ul>
<li><strong>AllowPaging</strong>: Remember this property has to be set to <strong>True </strong>or pagination will not be enabled.</li>
<li><strong>PageSize</strong>: Lets you decide how many rows will be shown per page.</li>
<li><strong>Position</strong>: Where to show the page navigator: (top, bottom or both, default is bottom).</li>
<li><strong>Mode</strong>: Style of the navigator: numbers, text or some type of combination.</li>
<li><strong>PageButtonCount</strong>: How many pages to be shown in the navigator.</li>
<li><strong>FirstPageImageUrl</strong>, <strong>PreviousPageImageUrl</strong>, &#8230;: To set images for those options.</li>
<li><strong>FirstPageText</strong>, <strong>PreviousPageText</strong>, &#8230;: To set a text for those options.</li>
</ul>
<h2>Custom pagination</h2>
<p>You can, also, design your own page navigator using a <strong>PagerTemplate</strong>:</p>
<pre class="brush: csharp; wrap-lines: false;">
&lt;PagerTemplate&gt;
      Page &lt;asp:DropDownList ID=&quot;ddlPages&quot; runat=&quot;server&quot; AutoPostBack=&quot;True&quot;
      onselectedindexchanged=&quot;ddlPages_SelectedIndexChanged&quot;  &gt;&lt;/asp:DropDownList&gt;
      of &lt;asp:Label ID=&quot;lblPageCount&quot; runat=&quot;server&quot;&gt;&lt;/asp:Label&gt;
&lt;/PagerTemplate&gt;
</pre>
<p>You can add a PagerTemplate manually or using the design menu clicking on the arrow above the GridView and then select &#8220;Edit Templates&#8221; and choose &#8220;PagerTemplate&#8221; on the combo.</p>
<p>You can add different controls to let you paginate here like ImageButtons, LinkButtons or a DropDownList, for example. If you do that, you will most probably to have to fill those controls when the GridView databinds, something like:</p>
<pre class="brush: csharp; wrap-lines: false;">
protected void ResultsGrid_DataBound(object sender, EventArgs e) {
   GridViewRow gvrPager = ResultsGrid.BottomPagerRow;

   if (gvrPager == null) return;
      // get your controls from the gridview
      DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl(&quot;ddlPages&quot;);
      Label lblPageCount = (Label)gvrPager.Cells[0].FindControl(&quot;lblPageCount&quot;);

      if (ddlPages != null) {
         // populate pager
         for (int i = 0; i &lt; ResultsGrid.PageCount; i++) {
            int intPageNumber = i + 1;
            ListItem lstItem = new ListItem(intPageNumber.ToString());
               if (i == ResultsGrid.PageIndex) lstItem.Selected = true;
               ddlPages.Items.Add(lstItem);
            }
         }

      // populate page count
      if (lblPageCount != null) lblPageCount.Text = ResultsGrid.PageCount.ToString();
      }
</pre>
<p>Once you do, you need to set AutoPostBack = true and get the event in backsource to change the GridView PageIndex, <strong>remember that this time the &#8220;<em>PageIndexEvent</em>&#8221; will not be fired</strong> since the control we are firing is a different one now. So you need to do something like this now:</p>
<pre class="brush: csharp; wrap-lines: false;">
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e) {
   GridViewRow gvrPager = ResultsGrid.BottomPagerRow;
   DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl(&quot;ddlPages&quot;);

   ResultsGrid.PageIndex = ddlPages.SelectedIndex;
   oReport.loadResults();
}
</pre>
<p>The little annoying problem of this is that you can have a navigator in top, bottom or both parts of the gridview, and you need to deal with that when doing the custom navigator.</p>
<p>More info: <a href="http://kikosantos.net/tech/2006/05/custom-paging-in-gridview-control/">http://kikosantos.net/tech/2006/05/custom-paging-in-gridview-control/</a></p>
<h2>Independent Navigator</h2>
<p>Once you know how to make a custom navigator using a PagerTemplate its not that hard to make a box with a navigator outside the GridView that will make the same work. So, you will fill that box controls when the GridView databinds, get the events when those controls make a PostBack and change the GridView page.</p>
<p>You could, also, use a WebUserControl for doing this, letting you reuse yor custom navigator and place it at any part of the Page you want to, not having to show it just on the top or bottom of the GridView.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/08/paginate-grid-views.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load dynamic Web User Control in .Net</title>
		<link>http://www.rubencanton.com/blog/2011/07/load-dynamic-web-user-control-in-net.html</link>
		<comments>http://www.rubencanton.com/blog/2011/07/load-dynamic-web-user-control-in-net.html#comments</comments>
		<pubDate>Thu, 21 Jul 2011 20:17:37 +0000</pubDate>
		<dc:creator>Ruben Canton</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[c#.net]]></category>

		<guid isPermaLink="false">http://www.rubencanton.com/blog/?p=317</guid>
		<description><![CDATA[One of the most common controls used in .Net is the Web User Control, which is in fact a website piece to be reused in different pages.
You normally place them in the page while developing it just dropping it into the page and then using them as part of it, but, what if you want [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most common controls used in .Net is the <strong>Web User Control</strong>, which is in fact a website piece to be reused in different pages.</p>
<p>You normally place them in the page while developing it just dropping it into the page and then using them as part of it, but, what if you want more than one of them in the same page and you don&#8217;t know how many of them you are going to use?</p>
<p>For doing that you can always set 10 or more of them in the page and then show as many as you need or, you can dynamically load as many of them as you need this way:</p>
<p>First, I&#8217;m going to place the control in a namespace, <strong>this is not necessary</strong>, but it helps to have things clearer and avoid mistakes. You have to add it just before the partial class of the control begins.</p>
<pre class="brush: csharp; wrap-lines: false;">
namespace MyNameSpace.UserControls {
    public partial class webcontrols_CustomBox : System.Web.UI.UserControl {
...
}
}
</pre>
<p>Now that we have set the namespace at its back code, we have to change the call to the class at the design file (the one with the HTML) <strong>using the new namespace</strong>:</p>
<pre class="brush: csharp; wrap-lines: false;">
&lt;%@ Control Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeFile=&quot;CustomBox.ascx.cs&quot;
Inherits=&quot;MyNameSpace.UserControls.webcontrols_CustomBox&quot; %&gt;
</pre>
<p>Finally, to load a Web User Control in a page, despite we are loading it dynamically, we need to register it at the top of the design page. If you want to go fast just drag it to the page using the solution explorer and delete it again, the register line will keep there.</p>
<pre class="brush: csharp; wrap-lines: false;">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Site.Master&quot; AutoEventWireup=&quot;true&quot; CodeFile=&quot;DynWUC.aspx.cs&quot; Inherits=&quot;DynWUC&quot; %&gt;
&lt;%@ Register src=&quot;./webcontrols/CustomBox.ascx&quot; tagname=&quot;CustomBox&quot; tagprefix=&quot;uc1&quot; %&gt;
</pre>
<p>And now, we can load it declaring a Control object and doing a Cast if we need to access one of its public properties/methods, or just declaring that type of control object using the namespace and <em>casting</em> the LoadControl():</p>
<pre class="brush: csharp; wrap-lines: false;">
//The first way, step to step:
Control DynCustBox = LoadControl(&quot;~/webcontrols/CustomBox.ascx&quot;);
((MyNameSpace.UserControls.webcontrols_CustomBox)DynCustBox).Show();
pnlWhereTheControlGoes.Controls.Add(DynCustBox);

//The second way, better if you need to access different properties:
MyNameSpace.UserControls.webcontrols_CustomBox DynCustBox = (MyNameSpace.UserControls.webcontrols_CustomBox)LoadControl(&quot;~/webcontrols/CustomBox.ascx&quot;);
DynCustBox.Title = &quot;Title&quot;;
DynCustBox.Text = &quot;Some text goes here, lalala.&quot;;
DynCustBox.BGColor = &quot;#FF0&quot;;
DynCustBox.Show();

pnlWhereTheControlGoes.Controls.Add(DynCustBox);
</pre>
<p>As you see, we just load the control, add some values to its properties (if we have declared some on it) and place it in a panel we have for this purpose. Do not forget to add it to the page!!!</p>
<h2>The Web User Control disappears on postback!!</h2>
<p>Yes it does. As it is not part of the page and .Net Web Forms technology does not save it in the viewstate. Yes, you may argue that it should be saved on the Viewstate and I agree, but it seems that it would give some problems on the viewstate validation since it cannot know if that object had to be there or not.</p>
<p><strong>What can you do to show it after PostBack?</strong> Easy. Load it again and put it back on the page.</p>
<h2>The Web User Control does not raise its events!!</h2>
<p>Again the same problem as before. Since the controls disappear on PostBack, they cannot raise their events because they do not exist&#8230; </p>
<p>To raise the dynamic control events (and this works for Web User Controls as well as for any dynamic Control) you have to load them, again, in the Page_Load and give them the same ID they had to avoid .Net giving them a different ID since .Net gives IDs automatically.</p>
<p>Here&#8217;s an approximate example:</p>
<pre class="brush: csharp; wrap-lines: false;">
    protected void Page_Load(object sender, EventArgs e)  {
          if(ViewState[&quot;identificator_to_know_which_controls_to_show&quot;] != null) {
               int myOldID = (int)ViewState[&quot;identificator_to_know_which_controls_to_show&quot;];
               showDynBoxes(myOldID);
          }
    }

    protected void Page_PreRender(object sender, EventArgs e) {
          int myNewId = iveDoneSomeStuffBetweenLoadAndPreRenderAndIHaveANewID();
          showDynBoxes(MyNewId);
          ViewState.Add(&quot;identificator_to_know_which_controls_to_show&quot;, myNewId);
    }

    private void showDynBoxes(int ID){
      List&lt;SqlParameter&gt; pl = new List&lt;SqlParameter&gt;();
      pl.Add(new SqlParameter(&quot;ID&quot;, ID));
     DataReader dr = dao.getDataReader(&quot;some_stored&quot;, pl);
     while(dr.Read()){
        MyNameSpace.webcontrols.webcontrols_CustomBox DynCustBox = (MyNameSpace.webcontrols.webcontrols_CustomBox)LoadControl(&quot;~/webcontrols/CustomBox.ascx&quot;);
        DynCustBox.ID = dr[&quot;ID&quot;];
        DynCustBox.Text = dr[&quot;text&quot;];
        pnlWUC.Controls.Add(DynCustBox);
        }
    }
</pre>
<p>To understand the example, imagine your users can show different boxes at their sidebar (like the ones you can set in a blog sidebar) and you get those boxes depending on the user when you are in the profile page. Well, you will get those boxes from the DB so that let you know how many of them you have to show, their properties and something to use as an ID to identify each one of them.</p>
<p>This is a bit annoying but once you get used to it you will find this dynamic control trick very useful&#8230; despite you will only use it when strictly necessary. <strong>In the case you don&#8217;t need to wait until PreRender to show them</strong>, then you just need to load them in the Page_Load once and that will do. Or, <strong>in the case they have no events to raise</strong>, you do not need to worry about this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubencanton.com/blog/2011/07/load-dynamic-web-user-control-in-net.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

