Introduction to EC2

by Mark 11. March 2011 14:43

I recently gave my first presentation to a local user group. I presented an Introduction to EC2 at the Charlotte ALT NET user group.  It was a great experience I'd recommend everybody present to a local user group at least once. it also gave me some insight into the tools and processes that are interesting to people that present on a consistent basis, such as SlideShare. I'd seen slideshare before but never really looked at it, by creating an account and checking out the features.  My only point is it opened my eyes to some new things.

Anyhow, you can get my slide deck here: Introduction to EC2

Tags:

Who do these people think they are? King.com Prolonged Inactivity Warning Scam

by Mark 11. March 2011 14:28

I'm a little confused, and surprised by how much power some of these web companies think they have.  Recently I received this email from a website that lets you sign up for free and play games online:

Dear Mark,

We're sorry to see that you have been inactive for 5 months. We're writing you to inform you that if you stay inactive, we will start charging an account management fee from the next month onwards. This fee of $2 is deducted monthly from any accounts that have been inactive for 6 or more months.

Of course, we prefer if you play our games instead! If you wish to continue playing, simply login at
www.king.com and your inactivity flag as well as the upcoming account management fee will be removed.

We will start charging the fee in one month's time, counting from the date of this email.

This is an automated email and replies to the sender will not be responded to. If you have any questions or would like to get in contact with us for any reason, please contact our support through the site:
www.king.com.

Yours sincerely,
The King.com team

Apparently, if you are a web company with free user accounts and your users no longer use your site, you just have to email them and say something along the lines of "We know you are no longer interested in our service, but since you have an account record in our database we are going to charge you $2/mo if there isn't any account activity soon."

What is that?  If every website I signed up for all of the sudden just started charging me a $2 fee every month, my monthly payments for these websites would total more than my mortgage, and most of the time I am just checking them out since they are free anyway.

If they have the right to just send me an email and I start getting charged monthly fee, I expect the right to be able to reply to this email and have my account canceled.  I don't want to dig around in their site looking for some "delete" option that probably doesn't exist in the ui anyway.

I just wanted to point this out, because the whole idea to me is a little outrageous, not only have I not used this service in 5 months, but its been more like years since i've used it. It's got to take more than a simple email to start billing someone monthly for something that was never a paid service to begin with.

Tags:

Ordering Providers in the Provider Model

by Mark 3. February 2011 12:17

This post will help, If you're trying to build a framework on the provider model and your framework intends to execute all registered providers in the same order they are configured in. 

I was working on a project where I basically wanted to build a pipeline for augmenting Url's.  I decided I was going to build this pipeline around the provider model. I built it and everything seemed to be working fine. But was it? It wasn't long before I discovered that my modules to augment urls weren't running in the order I expected.  Well, being a pipeline and all, i intended for the providers to run in the same order they were configured in my web.config.  Which, was 50% a bad assumption and 50% a legitimate assumption.  It was obvious to me why the modules ran out of sequence after looking a bit more in-depth at ProviderCollection.  The internal storage of the ProviderCollection is a hashtable which we all know doesn't guarantee a specific order during enumeration. So, the next question is, how does the ProviderCollection use the HashTable when you aren't asking for a specific provider by it's name. 

 Reflector shows the source of ProviderCollection.GetEnumerator as

public IEnumerator GetEnumerator()
{   
      return this._Hashtable.Values.GetEnumerator();
}

The microsoft documentation for HashTable.Values(which is typed as an ICollection) says "The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method."

Prior to looking into the details of the ProviderCollection though, it seemed intuitive to me that ProviderCollection would carry over the document order semantics of xml, but... thats not the case. 

 So based on this, I knew what I had to do.

  1. Add some type of ordered collection as a private member of my derived ProviderCollection

  2. In the override for the Add method, add the concrete provider instance to my ordered collection

  3. Shadow the base GetEnumerator

The resultant class looks as follows:

    public class UrlFilterCollection
        : ProviderCollection, IEnumerable
    {
        List<ProviderBase> ConfigOrderedProviders = new List<ProviderBase>();
        public override void Add(ProviderBase provider)
        {
            ParameterValidation.CheckNotNull("provider", provider);

            if (provider as IUrlFilter == null)
            {
                throw new XiphiSoftException("Provider must implement IUrlFilter");
            }
            this.ConfigOrderedProviders.Add(provider);
            base.Add(provider);
        }
       
        public new IEnumerator GetEnumerator()
        {
            return ConfigOrderedProviders.GetEnumerator();
        }

        new public IUrlFilter this[string name]
        {
            get
            {
                return (IUrlFilter)base[name];
            }
        }
    }

 

I've highlighted the key changes.

 

Tags:

Cleaning my clock...

by Mark 31. January 2011 05:17

Tonight, i was pondering some solutions to a problem I've been having with windows servers on EC2.  The problem is my system clock gets out of sync with the real time; which results in any amazon api requests failing.  I started looking at the problem to determine if I could solve this without code.... I could of sworn I saw a time sycn option somewhere in windows... oh wait? I found it....

  Hrm... it's kind of strange, it's enabled ... so how did my clock get out of sync to begin with? Lets look at help that will definitely get to the bottom of this.    Interesting, so my clock managed to get out of sync by at least 15 minutes within a week which resulted in my api requests to amazon failing.... ahhhh i see: "If synchronization is enabled, your computer clock is synchronized with an Internet time server once a week."

It only sync's once a week. sigh.

which lead me here.... the command line: we can reconfigure the time service with this command and point it at time.windows.com

C:\>w32tm /config /manualpeerlist:time.windows.com /syncfromflags:manual /reliable:yes /update
C:\>w32tm /resync

However, there is one gotcha, none of this resync stuff works if your datetime is more than 15 hours off, because it assumes you want it that way.  Courtesy of windows help "Internet time servers might not synchronize your clock if your computer's time is off by more than 15 hours. To synchronize the time properly, ensure that the date and time settings are set close to your current time in the Date and Time Properties in Control Panel. "

So I'm going to put a scheduled task on my system to execute "w32tm /resync" every 6 hours, just to ensure my calls to the amazon api are always working.

Hope this helps.

 

Tags: , , , ,

Cloud Computing | General | Step by Step Guide

Setting up the AWS Identity and Access Management Command Line Tools on Windows

by Mark 14. December 2010 23:29

This post is a step by step guide for setting up the AWS Identity and Access Management Command Line tools on windows.  

It builds on two previous blog posts that set up the EC2 Command Line Tools, and the EC2 Elastic Load Balancer Command Line Tools; it's recommended you go through these blog posts first:

  1. Setting up the EC2 Command Line Tools
  2. Setting up the Elastic Load Balancer Command Line Tools

You must download the AWS Identity and Access Management Command Line Tools: http://aws.amazon.com/developertools/AWS-Identity-and-Access-Management/4143

I've downloaded my copy to %USERPROFILE%\My Documents\ec2-api\IAMCli.zip

Extract the zip file to %USERPROFILE%\My Documents\ec2-api\IAMCli

Create the folder %USERPROFILE%\My Documents\ec2-api\iam

Copy the contents from %USERPROFILE%\My Documents\ec2-api\IAMCli\IAMCli-1.1.0 to %USERPROFILE%\My Documents\ec2-api\iam

After the files copy you can delete the %USERPROFILE%\My Documents\ec2-api\IAMCli folder if you'd like to and the zip file you downloaded.

Copy the %USERPROFILE%\My Documents\ec2-api\iam\credential-file-path.template to %USERPROFILE%\My Documents\ec2-api\iam\credential-file.txt

Open %USERPROFILE%\My Documents\ec2-api\iam\credential-file.txt in your text editor and modify it to have your accesskeyid and secret access key.

You can retrieve those two keys by going to this url: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key and signing in to your amazon account.  Once you are signed in you will be redirected to a page with a grid that has a highlighted tab with the text "Access Keys".  Copy the Access Key ID from the grid and paste it into the file, then you need to click "Show" and copy the "Secret Access Key" into the file. Save and close the file.

Open your %USERPROFILE%\My Documents\ec2-api\ec2.bat file (which you should have from the first blog post linked to earlier) in the text editor of your choice.

Add the following lines to the file:

set AWS_IAM_HOME=%EC2_API%\iam
set AWS_CREDENTIAL_FILE=%EC2_API%\credential-file.txt

Modify your set path line by adding this to the path:

%AWS_IAM_HOME%\bin;

Save your ec2.bat file.  Here is what mine looks like:

@echo off
set EC2_API=%USERPROFILE%\My Documents\ec2-api
set EC2_HOME=%EC2_API%\ec2
set AWS_ELB_HOME=%EC2_API%\elb
set AWS_IAM_HOME=%EC2_API%\iam

set AWS_CREDENTIAL_FILE=%EC2_API%\credential-file.txt

set PATH=%PATH%;%EC2_HOME%\bin;%AWS_ELB_HOME%\bin;%AWS_IAM_HOME%\bin;

set JAVA_HOME=c:\program files\java\jre6
"%JAVA_HOME%\bin\java" -version

set EC2_PRIVATE_KEY=%EC2_API%\PrivateKey.pem
set EC2_CERT=%EC2_API%\509Certificate.pem

Now you should be able to test that it's working by calling "iam-userlistbypath":

C:\Users\Mark\My Documents\ec2-api>ec2
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

C:\Users\Mark\My Documents\ec2-api>iam-userlistbypath.cmd
arn:aws:iam::000000000000:user/someuser

C:\Users\Mark\My Documents\ec2-api>

The response above shows a user called someuser in my account.

Hope this helps and let me know if you have any problems getting it set up.

Setting up the Elastic Load Balancer (ELB) Command Line Tools

by Mark 14. December 2010 22:37

This post is a step by step guide for setting up the Elastic Load Balancer Command Line tools on windows.   It builds upon the blog post that sets up the EC2 Command Line Tools; it's recommended you go through that blog post first: Setting up the EC2 Command Line Tools

You must download the Elastic Load Balancer Command Line Tools: http://aws.amazon.com/developertools/2536

I've downloaded my copy to %USERPROFILE%\My Documents\ec2-api\ElasticLoadBalancing.zip

Extract the zip file to %USERPROFILE%\My Documents\ec2-api\elb-extract

Create the folder %USERPROFILE%\My Documents\ec2-api\elb

Copy the contents from %USERPROFILE%\My Documents\ec2-api\elb-extract\ElasticLoadBalancing-1.0.10.0 to %USERPROFILE%\My Documents\ec2-api\elb

After the files copy you can delete the %USERPROFILE%\My Documents\ec2-api\elb-extract folder if you'd like to and the zip file you downloaded.

Open you %USERPROFILE%\My Documents\ec2-api\ec2.bat file (which you should have from the first blog post linked to earlier) in the text editor of your choice.

Add the following line to the file:

set AWS_ELB_HOME=%EC2_API%\elb

Modify your set path line by adding this to the path:

%AWS_ELB_HOME%\bin;

Save your ec2.bat file.  Here is what mine looks like:

@echo off
set EC2_API=%USERPROFILE%\My Documents\ec2-api
set EC2_HOME=%EC2_API%\ec2
set AWS_ELB_HOME=%EC2_API%\elb

set PATH=%PATH%;%EC2_HOME%\bin;%AWS_ELB_HOME%\bin;

set JAVA_HOME=c:\program files\java\jre6
"%JAVA_HOME%\bin\java" -version

set EC2_PRIVATE_KEY=%EC2_API%\PrivateKey.pem
set EC2_CERT=%EC2_API%\509Certificate.pem

Now you should be able to test that it's working by calling "elb-describe-lbs", you can also use elb-cmd to describe the available commands:

C:\Users\Mark\My Documents\ec2-api>ec2
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

C:\Users\Mark\My Documents\ec2-api>elb-cmd
Command Name                            Description
------------                            -----------
elb-configure-healthcheck               Configure the parameters f...tered with a LoadBalancer.
elb-create-app-cookie-stickiness-policy Create an application-generated stickiness policy.
elb-create-lb                           Create a new LoadBalancer
elb-create-lb-cookie-stickiness-policy  Create an LB-generated stickiness policy.
elb-create-lb-listeners                 Create a new LoadBalancer listener
elb-delete-lb                           Deletes an existing LoadBalancer
elb-delete-lb-listeners                 Deletes a listener on an existing LoadBalancer
elb-delete-lb-policy                    Delete a LoadBalancer policy.
elb-deregister-instances-from-lb        Deregisters instances from a LoadBalancer
elb-describe-instance-health            Describes the state of instances
elb-describe-lbs                        Describes the state and properties of LoadBalancers
elb-disable-zones-for-lb                Remove availability zones from an LoadBalancer
elb-enable-zones-for-lb                 Add availability zones to existing LoadBalancer
elb-register-instances-with-lb          Registers instances to a LoadBalancer
elb-set-lb-listener-ssl-cert            Set the SSL Certificate fo...ecified LoadBalancer port.
elb-set-lb-policies-of-listener         Set LoadBalancer policies for a port.
help
version                                 Prints the version of the CLI tool and the API.

    For help on a specific command, type ' --help'


C:\Users\Mark\My Documents\ec2-api>elb-describe-lbs
LOAD_BALANCER  prod-pub-web  prod-pub-web-888936501.us-east-1.elb.amazonaws.com  2010-09-15T20:09:32.020Z

C:\Users\Mark\My Documents\ec2-api>

 

Just call me T.O...

by Tim 14. December 2010 21:00

Hi All, my name is Tim, but to most everyone I know, I just simply go by T.O., as in the overpaid NFL player who likes to gripe too much.. Yea, him, but I had the nickname first.  :-)

Anyway, I too am going to be writing here in hopes that I may at least provide a little insight.  I do hope to provide some material/code that will be useful.  My main interests lie in Domain Driven Design, NHibernate, and Sharp Architecture.  Topics that I will definitely be writing about.  I may also hit on things that I run across in my everyday job.

Look for my first post very soon! 

-Tim

Tags:

How to resize an EC2 Windows Instance EBS Boot Device

by Mark 11. December 2010 08:52

Thought I'd give a quick tutorial on how you resize a Boot Drive on an EBS backed EC2 Windows Instance.

So you are running a windows instance on EC2, and you realize you're running out of disk space on your boot drive.  If you work in most companies you don't have time to determine the root cause of the increasing disk usuage and remedy the situation.  Even if you did, who would want to when you can just add another 50gb of disk space for $5/mo and be on your way to other revenue generating task(a task that probably brings in more than $5/mo).

If you pretty much live in elasticfox for managing your aws environment this will be helpful to you, since ElastixFox doesn't allow you to do this.  From looking at the aws console UI, it looks like it will allow you to do this but I haven't tried it.  This tutorial simply describes what you need to do, using the Amazon EC2 Command Line Tools.

** In order for you to follow along with the steps below you will need to have the ec2 command line tools setup correctly on your box.  If you don't have them setup there is a tutorial here: Setting up the EC2 Command Line Tools

We have our EC2 instance, and our C: is half full, but for whatever reason the used space is increasing by 100MB per day, we want to increase out boot drive to 100GB, but elasticfox simply doesn't provide the required field "device"; which is needed to specify that we want to attach an EBS volume as the boot device.

The first thing we do is we "STOP" the instance. Do not "TERMINATE" the instance, just stop it.  In our EC2 Command Line we will do the following:

ec2-stop-instances i-ffffffff

Then wait about 30 seconds or so, and run this command:

ec2-describe-instances i-ffffffff

The purpose of calling describe instances on this instance is to ensure the instance is stopped. We can see in the response that the instance is indeed stopped.

INSTANCE i-ffffffff ami-dddddddd stopped test 0 t1.micro 2010-12-14T14:30:14+0000 us-east-1a

Now since we know this instance is stopped we'll detach the boot ebs volume.

ec2-detach-volume vol-cccccccc

Now this time we don't really care if it's detached yet or not, we don't bother calling describe volumes. We just create a snapshot of this drive.  (To optimize system uptime, you may want make the snapshot before you shut down your instance and detach your volume, but for the purposes of this example I've chosen this sequence.)

ec2-create-snapshot -d "My Snapshot Of My Boot Drive" vol-cccccccc

This drive has about 24gb of used space so I waited about 10 minutes or so and now I'm going to call describe snapshots to make sure my snapshot has completed by using the snapshot id that was in the response from the execution of the ec2-create-snapshot command.

ec2-describe-snapshots snap-aaaaaaaa

The response indicates that my snapshot is complete: 

SNAPSHOT        snap-aaaaaaaa   vol-cccccccc    completed

Now we need to create the new 100GB EBS Volume, and load our new snapshot(snap-aaaaaaaa) on to the new 100GB EBS Volume.  We need to also keep in mind that we must create the new EBS Volume in the same Availability Zone that our EC2 Instance was created in.  The ec2-instance we are working with in this example happens to be in the "us-east-1a" availability zone. 

ec2-create-volume -s 100 --snapshot snap-aaaaaaaa -z us-east-1a

We wait until our volume is created by executing describe volume:

ec2-describe-volumes vol-eeeeeeee

AWS responds that the volume is available:

VOLUME vol-eeeeeeee 100 snap-aaaaaaaa us-east-1a available 2010-12-14T15:36:59+0000

Finally we attach the volume as our boot device, the "-d /dev/sda1" here is the key piece of configuration for windows to recognize this device as your boot device:

ec2-attach-volume vol-eeeeeeee -i i-ffffffff -d /dev/sda1

EC2 should reply with the status "Attaching", and now we start our instance.

ec2-start-instances i-ffffffff

Check that it is running by calling describe instances

ec2-describe-instances i-ffffffff

When describe returns with a status of "running" you should be able to RDP into your instance assuming the OS is ready and configured to accept an RDP connection.  However, when we log back in and go to my computer, it still says Total Space: 50GB.... it didn't work? EC2 says it's a 100GB volume, what is wrong?

So there is one more step involved.  The virtual disk your instance is connected to is actually 100GB, but windows won't automatically add the new storage to your existing logical C: partition. In order to get windows to add the new space to your C: do the following:

  1. Open Server Manager
  2. Expand the Storage Node
  3. Click on Disk Management under Storage on the left hand side
  4. Wait for Disk Management to load, then right click inside the rectangle containing the C: so that it gets diagonal gray lines through it as depicted here:

  5. Click "Extend Volume..."
  6. Click the next and finish buttons all the way through the "Extend Volume" wizard without modifying any of the default values, and you will be left with this:

Your done, you can delete your old EBS Volume that was previously your boot drive and you can delete your snapshot.  Keep in mind this tutorial is for example purposes only, alot of these steps can be done without shutting down your instance.  However once it's time to detach your boot ebs volume you will want to shut your instance down gracefully.

Hope this helps.  Let me know if you have any questions or ideas for new posts, I've gotten a lot of great suggestions so far, keep them coming.

Here is the full command line dialog i ran to do this if you're intested:

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Mark>cd my documents

C:\Users\Mark\My Documents>cd ec2-api

C:\Users\Mark\My Documents\ec2-api>ec2
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

C:\Users\Mark\My Documents\ec2-api>ec2-stop-instances i-f0a39e9d
INSTANCE        i-f0a39e9d      running stopping

C:\Users\Mark\My Documents\ec2-api>ec2-describe-instances i-f0a39e9d
RESERVATION     r-37e7a35d      000000000000    default
INSTANCE        i-f0a39e9d      ami-9801f7f1                    stopped test    0               t1.micro        2010-12-14T14:30:14+0000        us-east-1a                      windows monitoring-disab
led                                     ebs                                     hvm
BLOCKDEVICE     xvdh    vol-ba9243d2    2010-12-14T14:30:20.000Z
BLOCKDEVICE     /dev/sda1       vol-bc9243d4    2010-12-14T14:30:20.000Z

C:\Users\Mark\My Documents\ec2-api>ec2-detach-volume vol-bc9243d4
ATTACHMENT      vol-bc9243d4    i-f0a39e9d      /dev/sda1       detaching       2010-12-14T15:11:56+0000

C:\Users\Mark\My Documents\ec2-api>ec2-describe-volumes vol-bc9243d4
VOLUME  vol-bc9243d4    50      snap-ad3addc0   us-east-1a      available       2010-12-14T14:30:19+0000

C:\Users\Mark\My Documents\ec2-api>ec2-create-snapshot -d "My Snapshot Of My Boot Drive" vol-bc9243d4
SNAPSHOT        snap-49789b24   vol-bc9243d4    pending 2010-12-14T15:17:54+0000                000000000000    50      My Snapshot Of My Boot Drive

C:\Users\Mark\My Documents\ec2-api>ec2-describe-snapshots snap-49789b24
SNAPSHOT        snap-49789b24   vol-bc9243d4    completed       2010-12-14T15:17:54+0000        100%    000000000000    50      My Snapshot Of My Boot Drive

C:\Users\Mark\My Documents\ec2-api>ec2-create-volume -s 100 --snapshot snap-49789b24 -z us-east-1a
VOLUME  vol-a48051cc    100     snap-49789b24   us-east-1a      creating        2010-12-14T15:36:59+0000

C:\Users\Mark\My Documents\ec2-api>ec2-describe-volume vol-a48051cc
'ec2-describe-volume' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Mark\My Documents\ec2-api>ec2-describe-volumes vol-a48051cc
VOLUME  vol-a48051cc    100     snap-49789b24   us-east-1a      available       2010-12-14T15:36:59+0000

C:\Users\Mark\My Documents\ec2-api>ec2-attach-volume vol-a48051cc -i i-f0a39e9d -d /dev/sda1
ATTACHMENT      vol-a48051cc    i-f0a39e9d      /dev/sda1       attaching       2010-12-14T16:07:02+0000

C:\Users\Mark\My Documents\ec2-api>ec2-start-instances i-f0a39e9d
INSTANCE        i-f0a39e9d      stopped pending

C:\Users\Mark\My Documents\ec2-api>ec2-describe-instances i-f0a39e9d
RESERVATION     r-37e7a35d      000000000000    default
INSTANCE        i-f0a39e9d      ami-9801f7f1    ec2-50-16-77-81.compute-1.amazonaws.com domU-12-31-39-0B-5E-92.compute-1.internal       running test    0               t1.micro        2010-12-14T16:08
:20+0000        us-east-1a                      windows monitoring-disabled     50.16.77.81     10.214.97.92                    ebs                                     hvm
BLOCKDEVICE     xvdh    vol-ba9243d2    2010-12-14T14:30:20.000Z
BLOCKDEVICE     /dev/sda1       vol-a48051cc    2010-12-14T16:07:02.000Z

C:\Users\Mark\My Documents\ec2-api>

MVC.net Things that make you go DUH!

by Mark 9. December 2010 14:02

I've made my way through a few MVC.NET apps now, and find that it's incredibly easy to turn your view template into a maze of server side code tags.  This is true even with the extensive use of partials.  I frequently come across or find myself coding view template code like this:

The "SHOULD I INCLUDE IT"?

<% 
  if (ViewData.Get().IsAdmin)
  {%>
      <span>|</span> <a href="<%=ResolveUrl("~/Admin")%>">Admin</a>
<%
  }%>

The "WHICH TO INCLUDE"? / Authenticated vs Anonymous Include / Authenticated Only Include

<%
if (!Request.IsAuthenticated)
{%>
	<li class="current"><a href="<%=ResolveUrl("~/Account/Login")%>">Login</a></li>
	<li><a href="<%=ResolveUrl("~/Account/Register")%>">Register</a></li>
<%
}
else
{%>
	<li class="current"><a href="<%=ResolveUrl("~/Home")%>">Home</a></li>
	<li><a href="<%=ResolveUrl("~/Ladders")%>">My Ladders</a></li>
	<li><a href="<%=ResolveUrl("~/Ladders")%>">Match History</a></li>
	<li><a href="<%=ResolveUrl("~/Ladders")%>">My Stats</a></li>
	<li><a href="<%=ResolveUrl("~/Help")%>">Help</a></li>
<%
}%>

So I decided I wanted a nicer way to do some of these things, and I have no problem at all creating about a million partials, but even with partials those above code sample still have those annoying yellow block tags scattered around.  They simply turn into this:

The "SHOULD I INCLUDE IT"?

<% 
  if (ViewData.Get().IsAdmin)
  {
	Html.RenderPartial("AdminLinks");
  }%>

The "WHICH TO INCLUDE"? / Authenticated vs Anonymous Include / Authenticated Only Include

<%
if (!Request.IsAuthenticated)
{
         Html.RenderPartial("AnonymousNavigation");
}
else
{
         Html.RenderPartial("AuthenticatedNavigation");
}%>

Of course you can even take that and simplify it some more, and there are always a million different ways and styles of doing things but here is the approach I like. I create this class with a few helper methods you may find useful.

public static class HtmlHelpers {

        public static void RenderPartialOnOneCondition(
                      this HtmlHelper helper, bool condition, 
                      string partialName, object model)
        {
            if (condition)
            {
                helper.RenderPartial(partialName, model);
            }
        }

        public static void RenderPartialWhenAuthenticated(
                      this HtmlHelper helper, 
                      string partialName, object model)
        {
            if (HttpContext.Current != null 
                && HttpContext.Current.Request.IsAuthenticated)
            {
                helper.RenderPartial(partialName, model);
            }
        }

        public static void RenderPartialIfElse(
                      this HtmlHelper helper, bool condition, 
                      string partialName, object partialModel, 
                      string elsePartialName, object elsePartialModel)
        {
            if (condition)
            {
                helper.RenderPartial(partialName, partialModel);
            }
            else
            {
                helper.RenderPartial(elsePartialName, elsePartialModel);
            }
        }

    }

Now let's see how the view code looks if we leverage these helpers:

The "SHOULD I INCLUDE IT"?

<% Html.RenderPartialOnOneCondition(ViewData.Get().IsAdmin, "AdminLinks", null)%>

The "WHICH TO INCLUDE"? / Authenticated vs Anonymous Include / Authenticated Only Include

<% Html.RenderPartialIfElse(Request.IsAuthenticated, 
                               "AuthenticatedNavigation", null,
                               "AnonymousNavigation", null)%>

I'm sure a ton of people are doing this already, but I thought it would be appropriate to put out there for more people to grab on to. What do you think? I'm eager to hear your thoughts or other ways that you currently use to try to keep your view code feeling like html? (Aside from the obvious option of using other view engines :-) )

Tags: , , , ,

Coding Ideas

Abstractions are Concrete things also

by Mark 9. December 2010 13:58

When I go up north for the holidays this year, I'm hoping to spend some time with my sister to teach her a little bit about programming.  So I want to share some of my thoughts about how I might approach the introduction to programming.

I'm intending to challenge her current thought process and show how she uses abstractions every day without recognizing it. The end goal of this first talk I have with her is to set the stage so the idea of a variable seems like a very natural and easy concept to grasp.

Basically I think I'm going to say something along these lines:

In grade school you are taught that a noun is a person, place or thing.  What's interesting is there are actually two types of *things* , the first being an ordinary thing, an item with a physical presence(let's call this a "proper thing").  The second type of thing doesn't have a physical presence(lets call this a reference thing); it's purpose is to represent or describe a *proper thing*.

What is "dog"?  The answer, "dog" is a word. Is the word "dog" a proper thing? No.  The word dog is a thing whose purpose is to reference a proper thing which would be an actual physical dog.  Without an actual phyical dog to run around and bark, or if there was no proper thing that was a dog, the word dog would have no meaning, and therefore it is a reference thing and not a proper thing. A reference thing like the word "dog" is dependent upon something else to have meaning. Without dogs, the word dog would not exist as we know it today.

What is interesting about *reference things* is they are representations meant for communicating about a *proper thing*, for example:

In english "dog" represents

In spanish "perro" represents

In french "chien" represents

The examples above specifically demonstrate how words represent things but aren't actually things, don't get hung up on words, the general idea is that some things are meant to communicate or represent other things and some things are ACTUAL THINGS.

All reference things are intended to communicate about a *proper thing*.  What if every day the word "dog" represented something different? We have all asked the question as kids "Why is a tabled called a table? Why isn't a table called a garbage can?"  As kids we realized that the names of things isn't important, as long as the person I am saying "garbage can" to, understands that "garbage can" is referring to the actual physical table. the *proper thing* that is a table.  Then at the end of the day when your mom yells "Kid's come to the garbage can, it's time for dinner" all the kids come into the kicthen and sit on their chairs around the garbage can(which is a )

Is this making sense? 

Thats crazy right? Who would call a a garbage can? It doesn't matter as long as the person we are talking to visualizes when we say garbage can. Right?  What makes understanding this sooooo complex is that you are brainwashed, everytime you look at this picture in your head you are saying "table" as if it's a word, because the two have been so tightly intertwined in your mind for so long. is a table, and a table is a when the truth of it; is that "table" is a word that represents a  but there is nothing about a that requires it to be referenced as a "Table" it could just have easily been a "car", a "duck", a "moose"

 Think about this next time you have to do algebra, algebra is based on this idea.

Let X = 5     Here were are defining that our "reference thing" X references a proper thing 5.

10 = X*2    So now when we communicate in math, we know X =5 because we decided this just a moment ago with Let X = 5

So I'm curious to hear your feedback, I think there is room for improvement and it is still a little abstract, but I think the images really help and I think if this first talk goes well the idea of variables will become a lot easier for people to accept.  Additionally, I think at some point there is room to talk about how "reference things" can reference other "Reference things" like

X = 5

5 in and of itself references a physical quantity of something, and 5 is a reference thing

X is a reference thing that references 5, therefore X is a reference thing that references a reference thing.  I think this understanding is required for someone to fully understand number bases, and that 1111 and 15 both represent the same physical quantity of proper things. But they are binary and decimal representations of the same physical quantitites.  Just like perro and dog represent the same physical entity.

Tags: , , ,

Analysis | General