jQuery DOM Elements…

Here’s the second dose of jQuery bits, with more to come in the near future.  I’ve got a few primary things I am going to point out with today’s code.  With jQuery getting a particular element, type of element, or the whole lot of a particular element is very easy.  Single line of code easy.

[sourcecode language="html"]
    <p>
        This is a sample page to show some basic jQuery operations with the DOM.
    </p>
    <p>
        The unordered list below has two list items within. When the jQuery below executes
        however the number of list items is higher because the master page includes some
        list items also.
    </p>
    <ul>
        <li><a href="http://compositecode.com">Loosely Coupled Human Code Factory Blog</a>
        <li><a href="https://partner.microsoft.com/">Microsoft Partner Network</a>
    </li></ul>
    <p>
        First set of input controls in nested between the form elements.</p>
    <form>
    <input type="checkbox" name="" />
    <input type="radio" name="" />
    <input name="" />
    <input type="button" name="" />
    </form>
    <p>
        Second set of input controls in nested between the form elements.</p>
    <form>
    <input type="checkbox" name="" />
    <input type="radio" name="" />
    <input name="" />
    <input type="button" name="" />
    </form>
    <p>
        Third set of input controls that are within the body elements but not surrounded
        by anything else.</p>
    <input type="checkbox" name="" />
    <input type="radio" name="" />
    <input name="" />
    <input type="button" name="" />
    <p>
        This last snippet of HTML I setup to show how the filter method works.</p>
    <a class="lookingFor" href="#">link</a> 
    <a class="lookingFor" href="#">link</a> 
    <a href="#">
        link</a> 
    <a class="lookingFor" href="#">link</a> <a class="lookingFor" href="#">link</a>
    <a href="#">_</a>
    <a href="#">link</a>
    <a href="#">link</a>
    <a href="#">link</a>


    <script type="text/javascript">

        var alertMessages;

        // alerts there are X elements of type <a> and X elements of type <li>.
        alertMessages = 'Page contains ' + jQuery('a').length + ' <a> elements and ' + jQuery('li').length + ' <li> elements.';

        // searches within all form elements using a wrapper for context.
        alertMessages += '\nselected ' + jQuery('input', $('form')).length + ' inputs';

        // searches the first form element using DOM reference as the context.
        alertMessages += '\nselected ' + jQuery('input', document.forms[0]).length + ' inputs';

        // search within the body element for all input elements using an expression.
        alertMessages += '\nselected ' + jQuery('input', 'body').length + ' inputs';

        // This finds the 4 links marked with the class lookingFor out of all the <a> elements in the page.
        alertMessages += '\n' + jQuery('a').filter('.lookingFor').length + ' lookingFor links'

        // This finds the 4 links marked with the class lookingFor out of all the <a> elements in the page,
        // however it does so with a function instead.
        alertMessages += '\n' + jQuery('a').filter(function (index) { return $(this).hasClass('lookingFor'); }).length + ' lookingFor links';

        alert(alertMessages);
    </script>
[/sourcecode]

The first line that is parsed together for the alertMessages variable shows a simple usage of the jQuery Selector Engine.  The jQuery uses the Sizzle (http://www.sizzlejs.com) Engine for this.  There are other options for selector style functionality, but this is the famous jQuery way.

The second, third, and fourth lines assigning to alertMessages are a simple usage of the jQuery Selector to retrieve elements within a particular context.  Review the comments in the code above for the specifics of what is being selected.

The fifth line are selecting elements with a particular class property.  In this case I’ve called the class lookingFor.  The jQuery call is using a filter function to trace the DOM and find the particular elements by the criteria.

The sixth line applies another filter method using a function.  This is kind of like using a in line delegate in C#.  As with C#, use with caution as you’ll end up with snippets of code copied and pasted everwhere if you use the in line function ability too much.

Shout it kick it on DotNetKicks.com

The Simple Migration to Azure

This is a quick entry just to show how to migrate an existing ASP.NET (or ASP.NET MVC) Web Application to Windows Azure.  Make sure you have the Azure Tools SDK installed before stepping through this, otherwise you’ll get an empty project folder and end up with web page in Visual Studio.  With your existing solution/project open in Visual Studio 2010 right click on the solution and add a new project.  You will see the dialog as shown in the image below (click for large full size image, same goes for subsequent images)

Name your project and then click on OK.  The following secondary dialog will appear.  Since you want to use one of your existing web applications leave the “Cloud Service Solution:” section empty and click OK.

You will then see the following project appear in your Visual Studio 2010 Solution.

Right click on the Roles Folder in the new project as shown below.  You will get the following options as shown;  “New Web Role Project…”, “Web Role Project in solution…”, and “New Worker Role Project…” and select the “Web Role Project in solution…”.

The following dialog will pop up with any available web applications, in my case there is a single ASP.NET Web Application that is listed.  Click OK and you now of a Windows Azure Cloud Deployable Application.  Complete a build and right click on the Cloud Deployment Project and click Publish for the next steps into the cloud.  But I’ll leave that particular exercise’s steps for another entry.

 

Shout it

Kata Kickin’ Some Prime Numbers

Lately I have been interviewing people for prospective positions in the company I work for.  In the various questions that I and others pose during these interviews one popped up as a prospective Kata.  The challenge is really quit simple, “Write a method that would take a int and check if it is a prime number.”  The following snippet is what I came up with.

[sourcecode language="csharp"]
protected bool IsPrime(int theNumber) 
{ 
    bool isPrime = true;

    int theHalf = theNumber / 2;

    for (int i = 2; i < theHalf; i++) 
    { 
        var remainder = theNumber % i; 
        if (remainder == 0) 
        { 
            isPrime = false; 
            break; 
        } 
    }

    return isPrime; 
}
[/sourcecode]

The next idea that popped up was to find X prime number in order.  As the answer a question like, “What is the 6th prime number?”  I came up with the following method for that.

[sourcecode language="csharp"]
protected int GetPrimeByPosition(int position) 
{ 
    int counter = 1; 
    int thePosition = 0; 
    while (true) 
    { 
        if(IsPrime(counter)) 
        { 
            if(thePosition == position) 
                return counter; 
            thePosition++; 
        }

        counter++; 
    } 
}
[/sourcecode]

In the end the Kata is a simple 2 step problem.

  1. Write a method that determines if an int is a prime number.  i.e. “Is 5 a prime number?”
  2. Write a method that determines the prime number based on X order.  i.e. “What is the 3rd prime number?”

So based on these two steps, what would be some other steps to add to this Kata?  What are some other good interview questions that are short and simple for prospective employees to code through?

Windows Azure ASP.NET MVC 2 Role with Silverlight

I was working through some scenarios recently with Azure and Silverlight.  I immediately decided a quick walk through for setting up a Silverlight Application running in an ASP.NET MVC 2 Application would be a cool project.

This walk through I have Visual Studio 2010, Silverlight 4, and the Azure SDK all installed.  If you need to download any of those go get em? now.

Launch Visual Studio 2010 and start a new project.  Click on the section for cloud templates as shown below.

After you name the project, the dialog for what type of Windows Azure Cloud Service Role will display.  I selected ASP.NET MVC 2 Web Role, which adds the MvcWebRole1 Project to the Cloud Service Solution.

Since I selected the ASP.NET MVC 2 Project type, it immediately prompts for a unit test project.  Because I just want to get everything running first, I will probably be unit testing the Silverlight and just using the MVC Project as a host for the Silverlight for now, and because I would prefer to just add the unit test project later, I am going to select no here.

Once you’ve created the ASP.NET MVC 2 project to host the Silverlight, then create another new project.  Select the Silverlight section under the Installed Templates in the Add New Project dialog.  Then select Silverlight Application.

The next dialog that comes up will inquire about using the existing ASP.NET MVC Application I just created, which I do want it to use that so I leave it checked.  The options section however I do not want to check RIA Web Services, do not want a test page added to the project, and I want Silverlight debugging enabled so I leave that checked.  Once those options are appropriately set, just click on OK and the Silverlight Project will be added to the overall solution.

The next steps now are to get the Silverlight object appropriately embedded in the web page.  First open up the Site.Master file in the ASP.NET MVC 2 Project located under the Veiws/Shared/ location.  After you open the file review the content of the <header></header> section.  In that section add another <contentplaceholder></contentplaceholder> tag as shown in the code snippet below.

[sourcecode language="html"]
<head runat="server">
    
    <link rel="stylesheet" type="text/css" href="../../Content/Site.css" />
    <asp:contentplaceholder id="HeaderContent" runat="server">  </asp:contentplaceholder>


[/sourcecode]

i usually put it toward the bottom of the header section.  it just seems the <title></title> should be on the top of the section and i like to keep it that way.

now open up the index.aspx page under the asp.net mvc 2 project located in the views/home/ directory.  when you open up that file add a <asp:content><asp:content> tag as shown in the next snippet.

[sourcecode language="html"]
<asp:content id="content1" runat="server" contentplaceholderid="titlecontent">
    home page </asp:content>   <asp:content id="headercontent" runat="server" contentplaceholderid="headercontent">   </asp:content>   <asp:content id="content2" runat="server" contentplaceholderid="maincontent">
    <h2>&lt;%= html.encode(viewdata[&quot;message&quot;]) %&gt;</h2>
    <p>
        to learn more about asp.net mvc visit <a title="ASP.NET MVC Website" href="http://asp.net/mvc">http://asp.net/mvc</a>. </p></asp:content>
[/sourcecode]

In that center tag, I am now going to add what is needed to appropriately embed the Silverlight obj object into the page.  The first thing I needed is a reference to the Silverlight.js file.

[sourcecode language="html"]
<script type="text/javascript" src="Silverlight.js"></script>
[/sourcecode]

After that comes a bit of nitty gritty Javascript.  I create another tag (and for those in the know, this is exactly like the generated code that is dumped into the *.html page generated with any Silverlight Project if you select to "add a test page that references the application".  The complete Javascript is below.

[sourcecode language="csharp"]
function onSilverlightError(sender, args) {
    var appSource = &quot;&quot;;
    if (sender != null &amp;&amp; sender != 0) {
        appSource = sender.getHost().Source;
    }   var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;   if (errorType == &quot;ImageError&quot; || errorType == &quot;MediaError&quot;) {
        return;
    }   var errMsg = &quot;Unhandled Error
            in Silverlight Application &quot; + appSource + &quot;\n&quot;;   errMsg += &quot;Code: &quot; + iErrorCode + &quot; \n&quot;;
    errMsg += &quot;Category: &quot; + errorType + &quot; \n&quot;;
    errMsg += &quot;Message: &quot; + args.ErrorMessage + &quot; \n&quot;;   if (errorType == &quot;ParserError&quot;) {
        errMsg += &quot;File: &quot; + args.xamlFile + &quot; \n&quot;;
        errMsg += &quot;Line: &quot; + args.lineNumber + &quot; \n&quot;;
        errMsg += &quot;Position: &quot; + args.charPosition + &quot; \n&quot;;
    }
    else if (errorType == &quot;RuntimeError&quot;) {
        if (args.lineNumber != 0) {
            errMsg += &quot;Line: &quot; + args.lineNumber + &quot; \n&quot;;
            errMsg += &quot;Position: &quot; + args.charPosition + &quot; \n&quot;;
        }
        errMsg += &quot;MethodName: &quot; + args.methodName + &quot; \n&quot;;
    }   throw new Error(errMsg);
}
[/sourcecode]

I literally, since it seems to work fine, just use what is populated in the automatically generated page.  After getting the appropriate Javascript into place I put the actual Silverlight Object Embed code into the HTML itself.  Just so I know the positioning and for final verification when running the application I insert the embed code just below the Index.aspx page message.  As shown below.

[sourcecode language="html"]
<asp:content id="Content2" runat="server" contentplaceholderid="MainContent">
    <h2>
        &lt;%= Html.Encode(ViewData[&quot;Message&quot;]) %&gt;</h2>
    <p>
        To learn more about ASP.NET MVC visit <a title="ASP.NET MVC Website" href="http://asp.net/mvc">http://asp.net/mvc</a>. </p><div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
            width="100%" height="100%">
            <param name="source" value="ClientBin/CloudySilverlight.xap" />
            <param name="onError" value="onSilverlightError" />
            <param name="background" value="white" />
            <param name="minRuntimeVersion" value="4.0.50401.0" />
            <param name="autoUpgrade" value="true" />
            <a href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=4.0.50401.0" style="text-decoration: none">
                <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:
            none" />
            </a>
        </object><iframe style="border-right-width: 0px; width: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px; visibility: hidden; border-left-width: 0px" id="_sl_historyFrame"></iframe></div></asp:content>
[/sourcecode]

I then open up the Silverlight Project MainPage.xaml.  Just to make it visibly obvious that the Silverlight Application is running in the page, I added a button as shown below.

[sourcecode language="html"]
&lt;?XML:NAMESPACE PREFIX = [default] http://schemas.microsoft.com/winfx/2006/xaml/presentation NS = &quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; /&gt;<usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" d:designwidth="400" d:designheight="300" mc:ignorable="d" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:class="CloudySilverlight.MainPage">   <grid background="White" x:name="LayoutRoot">
        <button name="button1" click="button1_Click" width="75" verticalalignment="Top" margin="48,40,0,0" horizontalalignment="Left" height="23" content="Button">
    </grid>
</usercontrol>
[/sourcecode]

Just for kicks, I added a message box that would popup, just to show executing functionality
also.

[sourcecode language="csharp"]
private void button1_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(&quot;It runs in the cloud!&quot;);
}
[/sourcecode]

I then executed the ASP.NET MVC 2 and could see the Silverlight Application in page.  With a quick click of the button, I got a message box.  Success!ight 4, and the latest Azure
SDK, this is actually a ridiculously easy process.

Navigate to the Azure Cloud Services web site.


Once that is open go back in Visual Studio and right click on the cloud project
and select publish.


This will publish two files into a directory.  Copy that directory so you can
easily paste it into the Azure Cloud Services web site.  You’ll have to click
on the application role in the cloud (I will have another blog entry soon about
where, how, and best practices in the cloud).


In the text boxes shown, select the application package file and the configuration
file and place them in the appropriate text boxes.  This is the part were it
comes in handy to have copied the directory path of the file location.  That
way when you click on browser you can just paste that in, then hit enter.  The two files will be listed and you can select the appropriate file.

Once that is done, name the service deployment.  Then click on publish.  After a minute or so you will see the following screen.


Now click on run.  Once the MvcWebRole1 goes green (the little light symbol
to the left of the status) click on the Web Site URL.  Be patient during this
process too, it could take a minute or two.  The Silverlight application should again come up just like you
ran it on your local machine.

Once staging is up and running, click on the circular icon with two arrows to move
staging to production.  Once you are done make sure the green light is again
go for the production deploy, then click on the Web Site URL to verify the site
is working.  At this point I had a successful development, staging, and production
deployment.

Thanks for reading, hope this was helpful.  I have more Windows Azure and other
cloud related material coming, so stay tuned.

Getting Ramped for Silverlight 4

Here is a quick walk through of setting up your Silverlight 4 development environment.  The first assumed step is that you have Visual Studio 2010 already installed and any appropriate patches.  Then download the following in order and install each.

Once each of these are installed jump into Visual Studio 2010.  Start a new Silverlight 4 Project by going to File -> New -> Project -> and select the Silverlight Project Templates.  Here you’ll see a new list of projects that are specific to the above listed downloads.

  • Silverlight Business Application
  • WCF RIA Service Class Library
  • Silverlight Unit Test Application

One way to confirm (and what I am going to display here in this entry) Silverlight 4 is installed ok is to select the Silverlight Application Template and start a new project.

On the next screen you will see some of the standard options.  I always go with the ASP.NET MVC Option and with these new installations I am going to select Silverlight 4 (should be selected already) from the drop down and check the Enable WCF RIA Services check box.

I also, for good measure, always create a unit test project for the ASP.NET MVC Project that will host the Silverlight Application Project.  When all is setup, the Solutions Explorer should look like what is shown below.

Add the following code to the XAML of the MainPage.xaml of the Silverlight Project.

[sourcecode language="html"]
<UserControl x:Class="Silverlight4.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="textBlockTest" Text="Hello World!" />
    </Grid>
</UserControl>
[/sourcecode]

Now execute the project, if all runs well you have installed Silverlight 4 successfully.

Bam!  Silverlight 4 ready to go!  I will have more on Silverlight 4 very soon, as I will be starting a project (personal) and blogging it as I work through it.  Also, if you run into any issues I would like to read about them, so please comment.  I had a few issues and also had some design time rendering issues in the VS 2010 IDE when I installed these bits at first.