in

Platinum Bay

Peace, Love, Team System, and Community

This Blog

Syndication


.NETicated

  • What is Community?

    I’ve travelled the world and the seven seas… ok, ok, just North America, but since September of 2007 I’ve had the opportunity to visit nearly 100 community events from user group meetings, code camps, micro-conferences to major tradeshows such as Tech-Ed and PDC. During my travels I’ve been able to talk one on one with numerous user group leaders and influentials and there are widely varying views as to what community is. A lot of community leaders base their metrics on how many butts in a seat they were able to achieve at their latest meeting. I’m here to tell you my friends that this is not community. Not in the slightest. It’s an association, a club.

    True community is what happens outside of organized events.

    Here are a couple thoughts:

    • How much time do you spend mentoring other developers? Jesse Riley has a great post spawned by a Jim Holmes talk on this. I’d recommend seeing Jim’s talk if you ever have the opportunity.
    • Do you invite your attendees out for food and/or adult beverages after each event? This is a great way to not only build relationships, but to find motivated up-and-coming influentials and community leaders. Less than 10% of your attendees will regularly come out afterwards, but those that do tend to have the spark and can be mentored into strong community leaders themselves
    • Is your Microsoft Developer Evangelist organizing all the events? Some of the best Developer Evangelists I’ve met rarely organize events themselves, rather they support those that are already organizing events. If folks in your local community aren’t organizing events however, that’s a great opportunity to step up and be a leader.
    • Do you make yourself available? I make it a habit to freely share my personal contact info, and unless I’m overdue on a deadline (hypothetically speaking of course), I try to make myself available. For the record:
      • Phone: (610) 883-7667
      • Email and Live Messenger: steve [at] platinumbay [dot] com
      • Twitter: SteveAndrews

    To me, community is not about a place to hang my hat and pat myself on the back. It’s a place where I can both learn and teach, mentor and be mentored, and build meaningful and lasting relationships with my peers. I’d encourage you to do the same.

    Posted Dec 24 2009, 07:00 AM by Steve with 2 comment(s)
    Filed under:
  • Tips for Releasing Sample Code

    When I’m learning a new technology, I’ll frequently download code samples that help me better understand the concepts. Often though I find myself frustrated by having to deal with formatting and extraneous information before even looking at the code. To that end I have some rules for releasing sample code.

    Format Every Document
    The keyboard shortcut for this is Ctrl+K+D. Nothing is more frustrating than looking at unformatted code.

    Code Order
    Code should be ordered in the following structure from top to bottom:

    • events
    • fields and automatic properties
    • constructors
    • abstract methods
    • methods
    • abstract properties
    • properties
    • subclasses

    Code Statements
    Include a blank line before return statements and before and after decision blocks (including using, if, switch, while). In C#, opening and closing brackets should be on their own line.

    Remove Excess Blank Lines
    There should never be more than one consecutive blank line between any lines of code. With consecutive closing brackets as well as #endregion notations in C#, there should be no blank lines between them. There should also be no blank lines between fields or at the beginning or end of method or property bodies.

    Separate Code
    There should be one blank link between properties and methods to allow the user to see logical breaks in the code.

    Code Files
    There should only be one class, interface or enumeration per file.

    XML Comments
    Always remove unnecessary XML comments from your code files. For example, this XML comment should be removed:

    /// <param name="param"></param>

    Import Namespace Placement
    Import (C#) or using (VB) directives should be placed above the namespace. Also use the Organize Usings > Remove and Sort refactoring built-in to Visual Studio 2008 and Visual Studio 2010 to remove any unnecessary directives. This also helps to make the directives more readable.

    Wrapping Lines
    Don’t manually wrap long lines of code. Visual Studio has a feature to allow a user to wrap long lines if they so choose.

    Properties
    Use automatic properties in .NET 3.0 code and above whenever possible.

    These are a few of the rules. I’ll try to keep the list updated as I run across more frustrations.

  • Visual Studio Code Formatting

    Working on a website in Visual Studio I found myself annoyed again by the extra spaces around <script /> tags when I type Ctrl+K+D (Format Code). It turns out however that this is easy to change. As with most Visual Studio customizations, the answer lies in Tools > Options.

    Under Tools > Options > Text Editor > Html > Format, click the ‘Tag Specific Options…’ button. Under ‘Client HTML Tags’ find ‘script’. Finally, under ‘Line breaks’, change the default value from “2 Before opening, within, and 2 after closing” to “Before and After”, like the Rush song.

    This isn’t specific to HTML though, most of the languages under Text Editor support formatting options. Another change I typically make is for CSS to use the Compact rules.

    Happy Formatting!

    12-20-2009 6-29-49

  • Help Rebuild New Orleans At Tech·Ed NOLA

    Just announced, registration is now open for Microsoft Tech·Ed 2010, June 7-10, in New Orleans, Louisiana. Tech·Ed isn’t the only reason you should come to New Orleans though.

    It has been four years since Hurricane Katrina devastated the gulf coast as the worst civil disaster in American history. It is estimated that 400,000 jobs were lost and 275,000 homes were destroyed, ten times as many as any other natural disaster in US history. The total cost is estimated at $100 billion in damages making Katrina the most costly hurricane in US history. Up to 15 million people were affected by Hurricane Katrina, and New Orleans itself is still struggling to rebuild and one of the biggest needs is for new housing.

    I'd like to help, so I have arranged for a volunteer group to work with Habitat for Humanity to help rebuild New Orleans on Saturday June 5th, 2010, the Saturday before Tech·Ed. This is your opportunity to help an area that still has immense need, as well as to network with fellow geeks and eat more shrimp and oyster poboys! You should try the fried alligator too.

    If you would like to volunteer to help rebuild New Orleans on Saturday, June 5th, 2010, please visit: http://geekgive.org/project/techednola2010

    For more information about working with Habitat for Humanity, please read the FAQ (Microsoft Word) and Safety Guidelines (Microsoft Word).

    I am also looking for sponsors to help with:

    • Hotel Discounts
    • Transportation
    • Breakfast
    • Lunch
    • Water
    • After-Party
    • $50 suggested donation to Habitat for Humanity per person to help cover work gloves and other costs

    If you can help sponsor this volunteer event, please contact me at steve [at] platinumbay [dot] com.

  • Serialization Generics

    I really dislike writing the same code over and over again. For my current project, this involves serialization and I ended up creating the following generic class to handle Xml serialization and thought it might be useful to someone else.

    using System.Xml.Serialization;
    
    public class SerializationHelper<T> where T : class
    {
        public string SerializeXml(T o)
        {
            var serializer = new XmlSerializer(typeof(T));
    
            var sb = new StringBuilder();
            using (var tw = new StringWriter(sb))
            {
                serializer.Serialize(tw, o);
            }
    
            return sb.ToString();
        }
    
        public T DeserializeXml(string text)
        {
            var serializer = new XmlSerializer(typeof(T));
    
            using (var tr = new StringReader(text))
            {
                return (T)serializer.Deserialize(tr);
            }
        }
    }
  • UX Fail

    I’ve been developing software for over ten years now. In those ten years software technology has grown by enormous leaps and bounds. User experience however has not. I’d argue that user experience has hardly improved at all, and I grow more and more frustrated at the wasted potential as indicated by these tweets from yesterday:

    Ok, ok, I love technology too, but mostly for it's potential. I haven't seen it live up to that yet.

    If I had to do it over, I'd be a loud and vocal critic of bad user experience. To that end, I registered uxfail.org.

    At the end of the day, most software *is* nothing more than user experience.

    I bought the domain name UXFail.org and set up BlogEngine.NET to rant, vent, and hopefully help people improve the user experience of their software solutions. Visit the site, read the posts, and feel free to submit your own fails from the battlefield.

    http://uxfail.org

    Posted Nov 30 2009, 06:23 AM by Steve with 3 comment(s)
    Filed under:
  • Shotokan Development

    Note: There is still so much more I want to say on this topic, but that will have to wait for another post as I further distill my thoughts.

    At the end of my three week stint in Redmond, WA in October and November I was thrilled to be able to support Sara Ford as she tested for her second dan (second degree black belt) in Shotokan karate. Apart from being a cold and rainy night in Bellevue, it was a utterly humbling experience. The strength, speed, focus, and control of all those who tested for 1st, 2nd, and 3rd degree black belts was amazing. More so, what I experienced that evening has really started to change the way I think about software development and community in general.

    As an aside, Sara alone was so completely focused and exhibited such speed and control that I think my eyeballs melted and are just now recovering.

    Dojos and Schools of Thought

    “A dojo (道場, dōjō) is a Japanese term which literally means "place of the way". Initially, dojos were adjunct to temples. The term can refer to a formal training place for any of the Japanese do arts but typically it is considered the formal gathering place for students of any Japanese martial arts style to conduct training, examinations and other related encounters.” – Wikipedia

    Each dojo is unique, both taking practice and methodology from those before them, and molding in their own style and techniques. More importantly though, no dojo is inherently wrong. There are no ‘my camp is better than your camp’ mantras. In the software developer community however, I find people taking sides on any number of issues: databases, version control, testing, design patterns, and even hardware. Similarly, such arguments often fail to take into account all the variables and environmental issues that must be considered to make a decision. This has long troubled me as I tend to be very pragmatic. Sure, I nag the heck out of folks on Twitter about Team Foundation Server and MSTest, but at the end of the day if they’re using a tool and TFS doesn’t solve any pain points they have with that tool then there is absolutely no reason to change. There is no one right answer. There can’t be. Life isn’t that simple.

    Philosophies and Mindsets

    "The ultimate aim of Karate lies not in victory or defeat, but in the perfection of the character of the participant." - Gichin Funakoshi (1868–1957)

    In each Shotokan dojo, the precepts are displayed on a wall somewhere. These precepts typically include seeking perfection of character, being faithful, endeavoring to excel, and respecting others.

    Similarly, I believe that the goal of practicing software development should not be producing software, but rather to continually improve and subsequently solve real business needs. The real value of software is not technical. The real value of software is to improve someone’s life. Whether that involves automating a manual accounting system, building an e-commerce website to provide online revenue, or any other countless systems that software developers build. The philosophy of software development should also not just be about the technology. It should also encompass the attitude and character of the developer.

    Senseis and Teachers

    From Japanese 先生 sensei, literally "one who lived before" - Wiktionary

    In Shotokan, the term Sensei is reserved for those who have achieved fourth dan or higher. Once achieving the sensei status, students are expected to start teaching others. It does not however mean the end of direct learning; senseis continue to be taught by those their senior. Teaching others is to be taught in return; I have been privileged to learn far more by teaching than by simply being taught.

    During the exam, I was immediately hit square in the face by the attitudes of the senseis: learning is never complete and the goal of any good teacher is to help the student improve. During the course of the exam, students were called out periodically for not having demonstrated a particular technique correctly. Many times they were made to re-do the technique solo with instruction from the senseis. Instead of ridiculing or degrading the student however, it was recognized as an important time to provide instruction to help the student become more proficient, and it was done in a loving and fatherly manner with the aim of helping the student improve, not improving the sensei’s position. In fact, it might even be considered shameful to dojo sensei in front of the guest seventh and ninth degree black belts who administered the exam. Nevertheless, the student’s success is their success.

    Unfortunately, I am seeing the opposite in software development. Mistakes or misunderstandings often seem to be used as opportunities to devalue someone and make them feel worthless, especially in non-physical environments such as Twitter and blogs. The underlying reasons for this lies in Relational Dynamics and the Lifeboat Syndrome (think high school), but that’s another topic entirely. At the end of the day though, anyone who attempts to teach or instruct without a real desire to help the student improve is not worthy the title sensei.

    Exams and Measurement

    The exams were broken up into three parts: Kihon, Kata, and Kumite. Kihon, the basics, involves demonstrating individual techniques such as kicks, punches, sweeps, strikes, blocks, and throws. Kata, or forms, is a sequence of choreographed movements sometimes up to ten minutes long that demonstrate Kihon as well as stepping, twisting, turning, dropping to the ground, and jumping. Kata is the practical application of Kihon; understanding perfection via repetition. Kumite, or fighting, is the practical application of Kihon with a real opponent through non-scripted sparring.

    In software technology, our current methods of evaluating an individual’s proficiency in a particular technology has been largely limited to Kihon. Do you know what framework class to use to send mail and the appropriate properties to set? What is the precision of a decimal? And yes, I’ve been asked both questions. The problem with solely using Kihon to test someone’s ability is that no matter how any particular test may be structured, it comes down to nothing more than rote memorization. Anyone can memorize the .NET framework’s namespaces and classes and answer multiple choice questions, but said individual may not have a clue as to how to use them appropriately or use multiple Kihons together in a Kata to form a more perfect solution.

    We as an industry need to find ways to more thoroughly evaluate an individual’s proficiency in a particular technology area or multiple technology areas. This means formulating ways to test individuals at a Kata and Kumite level. Some industries have worked to address this by adopted the idea of apprenticeship or internship.  During such a period, an individual works hands-on with a sensei who not only can evaluate the person’s Kihon, but also their Kata: reasoning, decision making, thought process, practical application, and can provide guidance to help the person improve. Finally, we need to test at the Kumite level before someone can be called a master at any particular level. Microsoft provides some of this in the form of the Masters exams, hands-on Q&A with other recognized masters. But we need a way to provide Kata and Kumite level evaluation at every level of a person’s career, not just the architect level.

    Belts and Expertise

    While the belt system varies somewhat by school, there are 6 levels of colored belts in Shotokan as a student approaches dan, the black belt. There are also ten levels of black belt. One amazing tidbit I learned about belts is that one has to wait 3-5 years before advancing to the next belt level. This could mean 50 or 60 years before reaching tenth dan, a lifetime of dedication. As Sara pointed out to me, “Karate is a way of life,” even if it means missing a Saint’s game.

    Our industry has tried to establish levels of expertise, typically using job titles such as Junior, Mid-Level, Senior, Architect. However, these title can be rather arbitrary as typically no real measure of proficiency has been evaluated other than a simple Kihon interview. As was mentioned above, we need a way to more thoroughly evaluate an individuals proficiency beyond rote memorization. This may include pair programming as part of the interview process (Kata), complex situational analysis for an optimal solution (Kumite), and test-driven technical skills analysis (Kihon/Kata).

    [Similarly, many companies fall victim to the mentality that hiring a team of yellow belt (junior) developers will have the same result as one second degree black belt (senior or architect) developer. This is just simply not the case.]

    Shotokan Development

    So what would Shotokan development look like? Hypothetically:

    First, there would be dojos: schools of similar thought, each one able to reach the same goals though maybe through differing techniques and technology.

    Second, there would be senseis who are the proven masters of their domain who would teach, encourage, and instruct their students, always in a positive manner towards the betterment of the student.

    Finally, there would be belts: skills, techniques and attitudes demonstrated using Kihon, Kata and Kumite to earn the next level.

  • NotAtPDC is back!

    It’s official, we’re back again this year. As you may recall, a bunch of tweeps got together last year to organize an online-only co-conference with PDC. The results and reaction where outstanding, and we’ve decided to do it again.

    Keep an eye on the website (http://www.NotAtPDC.com) as well as the Twitter account (@NotAtPDC) for details and info.

    Want to present? Sign up on the site with your session info.

  • Team Build Property Reference Guide

    TeamBuildPropertyTargetReferenceI’ve been working quite a bit with Team Build lately, and overriding properties is a method of customization I’ve found quite useful in certain scenarios. Along the way, I found Aaron Hallberg’s excellent Team Build 2008 Property Reference blog post, but it didn’t show me where the properties were referenced. In fact, there isn’t an easy way to determine where any particular Property is being used or set other than reading through the 1,500 lines in the Microsoft.TeamFoundation.Build.targets file. I decided to spend a few hours, read through the file myself, and compile a chart of each Property, what Target it is referenced by, and how it is referenced.

    Hopefully the chart is self-explanatory, but here’s some tips:

    • Target names are along the horizontal axis
      • Base represents the root of the Targets file where global Properties are set
    • Property names are along the vertical axis
    • Legend
      • Set: The Property is Set inside the Target. In the case of
      • Used: The Property is used inside the Target
      • Condition: The Target or a contained Task references the Property in a condition
      • Error If Exists: Team Build will throw an exception if the Property is set, or not set, under the right conditions
      • Null Error: Team Build will throw an exception if the Property is null
      • Depends On: The target has a DependsOn for the Property. The Property contains a semi-colon delimited list of Target names

    I do not claim the chart to be 100% without error, so verify before you use it. Please send any updates or corrections to me.

    As a side note, if you are working with Team Build, Aaron Hallberg’s blog is choked full of Team Build goodness.

  • Neat Visual Studio Test Options

    Digging around in Tools > Options today to find the answer to an inquiry I received, I found some stuff I didn’t know existed. If you work with Visual Studio Test Projects, you will want to know about these options. The Test Tools options are found in Tools > Options > Test Tools.

    Test Execution Options

    The original question I received was from someone asking how to reduce the number of test results that Visual Studio kept around after test runs. The answer lies in the Test Execution options under Test Result Management. There is an option there labeled “Limit number of old Test Results to.” By default, this value is set to 25. While 25 may be an ideal setting if you are running a multitude of test runs and want to compare results, for most of us this is overkill. Personally I set it to three, and that tells Visual Studio to clean up results older than three runs.

    Also take note of the checkbox below it labeled “Double-clicking a Failed or Inconclusive unit test result displays the point of failure in the test.” When you double-click on a failed or inconclusive unit test result, you will no longer be taken to a test result report. Rather, you will be taken to the line of code that failed in the test.

    image

    Test Project Options

    I have always been frustrated when test projects were created with the “About Test Projects” introduction file and the Manual Test. The next step after creation for me was always to delete these items. In digging around today, I discovered that what files are created with test projects is configurable. Under the Test Project node, you will find a two side-by-side list boxes at the bottom of the settings pane. The left side allows you to select a language-specific test project, and the right side contains checkboxes allowing you to specify which files are included by default.

    image

    Conclusion

    I’m sure you will find these tips as useful as I have, I know they’ll be making their way into my Visual Studio Tips and Tricks talk.

  • jQuery and MVC: JSON Form Submission

    In my last two posts (jQuery and MVC: JSON and Favorite Image Icons with jQuery and MVC) I covered some basics of jQuery’s AJAX functionality to improve user experience. One of the scenarios which may not seem particularly asynchronous friendly is form submission. Fortunately, jQuery provides for asynchronous post, and in JSON format too.

    The complete code to perform this is:

    $('form').submit(function(e) {
    e.preventDefault();
    $.post($(
    this).attr("action"), $(this).serialize(), function(json) {
    // handle response
    }, "json");
    });

    First, get a jQuery reference to the form element and add a submit event handler:

    $('form').submit(function(e) {

    Next, we need to cancel the form’s default behavior by using the preventDefault function:

    e.preventDefault();
    Next, and this is the cool part, we call the post method in jQuery. The post method takes four arguments: url, data, callback, and type. The first three should be familiar from the previous blog posts, but the last one is new. The type parameter specifies the type of data and accepts "xml", "html", "script", "json", "jsonp", or "text". The example above is using JSON.

    Rather than hard coding the url, it can be retrieved from the form element itself:

    $(this).attr("action")

    And rather than manually pulling form fields into the data object, as the form may change, we can call jQuery’s serialize function on the form itself:

    $(this).serialize()

    Finally, we can tie it all together with an MVC action. This example uses the Employee entity from the Northwind database. Since the identifier on the Employee entity is EmployeeID and not ID, id needs to be specified as an action parameter in order to retrieve the correct employee from the database.

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Edit(int id, Employee employee)
    {
    // do work
    return new JsonResult { Data = new { Success = true } };
    }

    One common scenario for this functionality is to provide asynchronous searching within a page. Even asynchronous form submits are possible with jQuery, making your arsenal that much more powerful.

    Posted Aug 31 2009, 10:33 PM by Steve with 8 comment(s)
    Filed under: , ,
  • Favorite Image Icons with jQuery and MVC

    User experience, that’s the name of the game these days. Green screens and console applications are (hopefully) becoming a thing of the past. In the web world, this means a more fluid and asynchronous experience. In my last post, I gave a quick introduction to using jQuery and MVC to perform asynchronous requests to the browser. In this post, I will expand on that topic and show how to build a favorite image icon.

    The concept is pretty simple. For example, in the Twitter web UI, an empty star image appears on the right side of a tweet if you mouse over it.If the star is clicked, the icon changes to a flashing dot, and then to a yellow star indicating that the tweet has been favorited. It’s a neat, asynchronous effect, and it’s fairly simple to achieve.

    First, we need three images. Here are the images that Twitter uses:

    Next, a CSS style is defined for the off, on, and loading states. The purpose of each style is to allow style switching to not only change the picture, but also to allow the state to be determined through the style class assigned.

    .favimgoff, .favimgon, .imgload { width: 16px; height: 16px; border: 0px; background-repeat: no-repeat; }
    .favimgoff { background-image: url(images/icon_star_empty.gif); }
    .favimgon { background-image: url(images/icon_star_full.gif); }
    .imgload { background-image: url(images/icon_throbber.gif); }

    On the MVC side, an action is needed to handle the server processing.

    public JsonResult SetOrRemoveUserFavorite(int favoriteId)
    {
    JsonResult result = new JsonResult();

    // do work here, and set SetOn to the proper state
    result.Data = new { Success = true, SetOn = true };

    return result;
    }

    Next, on the client side, add an image tag with the class attribute and id set. The image is set to a one pixel transparent gif otherwise certain browsers may not render the background image.

    <img class="favimgoff" src="<%= Url.Content("~/Content/images/spacer.gif")%>" id="1" />

    Finally, jQuery on the client side takes care of the tying it all together:

    $('.favimgoff, .favimgon').click(function() {
    var $favimg = $(this);
    if ($favimg.attr('class') != 'imgload') {
    $favimg.removeClass().addClass(
    'imgload');
    $.getJSON(
    '<%= Url.Action("SetOrRemoveUserFavorite", "Services") %>', {
    favoriteId: $favimg.attr(
    'id')
    },
    function(json) {
    if (json.Success) {
    if (json.SetOn) {
    $favimg.removeClass().addClass(
    'favimgon');
    }
    else {
    $favimg.removeClass().addClass(
    'favimgoff');
    }
    }
    else {
    alert(
    'Favorite could not be set. Please refresh the page and try again.');
    }
    });
    }
    });

    Let’s step through the jQuery script. First, define the click event handler for both classes, and get a reference to the image clicked:

    $('.favimgoff, .favimgon').click(function() {
    var $favimg = $(this);

    Next, to avoid any duplicate action taken while the process is run, make sure the image isn’t in the loading state. This is necessary because jQuery will still have an event reference to the original image even when the class changes from the original two classes of on or off.

    if ($favimg.attr('class') != 'imgload') {

    Next, remove any existing class and add the loading class so the user gets feedback that their action is being processed:

    $favimg.removeClass().addClass('imgload');

    Then, make a server call to the action defined, and pass the id of the item as a parameter to the action:

    $.getJSON('<%= Url.Action("SetOrRemoveUserFavorite", "Services") %>', {
    favoriteId: $favimg.attr(
    'id')
    },
    function(json) {
    if (json.Success) {

    Finally, based on the SetOn value returned from the server call, remove the loading class and set the appropriate class:

    if (json.SetOn) {
    $favimg.removeClass().addClass(
    'favimgon');
    }
    else {
    $favimg.removeClass().addClass(
    'favimgoff');
    }

    If by chance the server call fails and Success is false, alert the user:

    alert('Favorite could not be set. Please refresh the page and try again.');

    That’s it. Utilizing the baked-in goodness of jQuery and ASP.NET MVC, providing a rich, asynchronous user experience doesn’t have to be complex.

    Posted Aug 29 2009, 08:01 PM by Steve with 7 comment(s)
    Filed under: , ,
  • jQuery and MVC: JSON

    I strongly dislike synchronous browser requests: the request has to be sent to the server, server action is performed, a server response is received, and the page is re-rendered which usually involves reloading images, style sheets, JavaScript files, etc. It takes time, sends an awful lot of traffic across the wire, and it doesn’t provide for the best user experience. In some scenarios this makes sense, but in most cases I find it to be an annoyance.

    Enter jQuery to the rescue. jQuery is the most exciting innovation to happen to JavaScript since, well, maybe JavaScript itself. One of the jQuery features I enjoy the most is the AJAX functionality which allows jQuery to talk to the server asynchronously, or behind the scenes.

    I personally like to use the JSON (JavaScript Object Notion) format, which is lighter-weight than XML. Using jQuery, a JSON GET request is written as:

    $.getJSON('[url]', { [parameters] }, function(json) {
    // callback function code
    });

    Let’s say I want to perform an asynchronous search in my web page for people names without having to reload the page. In MVC, I need an action to handle the request:

    public class SearchController : Controller
    {
    string[] peopleNames = new[] { "Bob", "Steve", "Joe", "Frank", "Lou" };

    public JsonResult Search(string q)
    {
    var results = peopleNames.Where(n => n.Contains(q));

    if (results.Count() > 0)
    return new JsonResult { Data = new { Success = true, Results = results } };
    else
    return new
    JsonResult { Data = new { Success = false } };
    }
    }

    The first thing to notice is the built-in JsonResult type on the Search action. MVC understands and is able to handle JSON data. Simply return a JsonResult object and populate the Data property with the data to be returned. The serialization of that data is handled under the covers.

    Back in the MVC View, call getJSON to make a request to the action and handle the response:

    $.getJSON('<%= Url.Action("Search", "Search") %>', { q: $('input#search') }, function(json) {
    if (json.Success) {
    // results found
    }
    else {
    // nothing found
    }
    });
    Note that Url.Action is used to get the virtual url. Url.Action and Url.Content are great ways to handle relative paths. Next, the search query is passed from an input field with an ID of search. And finally, the callback is handled. jQuery handles the deserialization under the covers, and the values can be handled as simple properties.

    The introduction of ASP.NET MVC and jQuery make asynchronous calls very quick and easy, and help to provide the end user with a better experience. In future posts, we’ll look at more specific examples of utilizing jQuery and MVC to provide a better user experience.

    Posted Aug 28 2009, 07:09 PM by Steve with 4 comment(s)
    Filed under: , ,
  • Reflection-Based Performance Analysis

    Back in 2007, I took some SharePoint training from Todd Bleaker (MVP, owner of MindSharp, and SharePoint guru). At one point he posed a question about the performance of the following methods:

    public string OptionOne()
    {
        string str = "Hello World";
        return str;
    }
    
    public string OptionTwo()
    {
        string str;
        str = "Hello World";
        return str;
    }
    
    public string OptionThree()
    {
        string str = null;
        str = "Hello World";
        return str;
    }
    
    public string OptionFour()
    {
        return "Hello World";
    }

    I took the challenge and wrote the above methods. Then to evaluate the probable performance I compiled the code and opened the resulting assembly in Reflector. Here is the Reflector output:

    public string OptionOne()
    {
        return "Hello World";
    }
    
    public string OptionTwo()
    {
        return "Hello World";
    }
    
    public string OptionThree()
    {
        return "Hello World";
    }
    
    public string OptionFour()
    {
        return "Hello World";
    }

    You may notice that all the methods appear the same. What happened? Compiler optimization? To find out I checked the IL, shown below:

    .method public hidebysig instance string OptionOne() cil managed
    {
        .maxstack 1
        .locals init (
            [0] string str,
            [1] string CS$1$0000)
        L_0000: nop 
        L_0001: ldstr "Hello World"
        L_0006: stloc.0 
        L_0007: ldloc.0 
        L_0008: stloc.1 
        L_0009: br.s L_000b
        L_000b: ldloc.1 
        L_000c: ret 
    }
    
    .method public hidebysig instance string OptionTwo() cil managed
    {
        .maxstack 1
        .locals init (
            [0] string str,
            [1] string CS$1$0000)
        L_0000: nop 
        L_0001: ldstr "Hello World"
        L_0006: stloc.0 
        L_0007: ldloc.0 
        L_0008: stloc.1 
        L_0009: br.s L_000b
        L_000b: ldloc.1 
        L_000c: ret 
    }
    
    .method public hidebysig instance string OptionThree() cil managed
    {
        .maxstack 1
        .locals init (
            [0] string str,
            [1] string CS$1$0000)
        L_0000: nop 
        L_0001: ldnull 
        L_0002: stloc.0 
        L_0003: ldstr "Hello World"
        L_0008: stloc.0 
        L_0009: ldloc.0 
        L_000a: stloc.1 
        L_000b: br.s L_000d
        L_000d: ldloc.1 
        L_000e: ret 
    }
    
    .method public hidebysig instance string OptionFour() cil managed
    {
        .maxstack 1
        .locals init (
            [0] string CS$1$0000)
        L_0000: nop 
        L_0001: ldstr "Hello World"
        L_0006: stloc.0 
        L_0007: br.s L_0009
        L_0009: ldloc.0 
        L_000a: ret 
    }

    What is really happening is that Reflector is making a best guess optimization as to what the original code looked like. We can clearly see in the IL that OptionFour is probably the most performant, and OptionThree is probably the least. This is because OptionThree is loading a null and storing it in local 1, then loading the string and storing it in the same location, making the first load unnecessary.

    Reflector can be a great tool to use for analyzing possible performance, as well as debugging assemblies. If you don’t have it, download it today: www.red-gate.com/products/reflector/

    Posted Aug 28 2009, 04:51 AM by Steve with 2 comment(s)
    Filed under: ,
  • Running T4 Templates with MSBuild

    If you haven’t explored T4 yet, you’re missing one of Visual Studio’s best, and best kept, secrets. T4, which stands for Text Templating Transformation Toolkit, is code generation built right into Visual Studio 2008. It is also available in Visual Studio 2005 if you install the Visual Studio SDK. It is a great feature that I use quite frequently to automate repetitive tasks.

    T4 template execution only occurs though when the template file is open in the editor and saved. In other words, template execution does not occur when you type Ctrl+B to build the project. There are scenarios however where execution of the templates at every build is the desired behavior.

    I did find several custom MSBuild tasks to perform this behavior, but I wanted to avoid additional assembly references. Instead, the following custom MSBuild target was created to address this.

    First and foremost, a .targets file is created in the MSBuild directory (%systemdrive%:\Windows\Microsoft.NET\Framework\v3.5):

    <?xml version="1.0" encoding="utf-8"?>
    <
    Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <
    Target Name="ExecuteT4Templates">
    <
    ItemGroup>
    <
    T4Templates Include=".\**\*.tt" />
    </
    ItemGroup>
    <Exec
    WorkingDirectory="C:\Program Files\Common Files\microsoft shared\TextTemplating\1.2\"
    Command="TextTransform &quot;%(T4Templates.FullPath)&quot;" />
    </
    Target>
    </
    Project>

    There are a couple important things to note. First, a custom target is created, and an item group is added to the target. In the item group, we create a new item called T4Templates that will recurse the project and hold information for each text template that is found. Finally, an execute task is added which calls TextTransform.exe for each file found.

    Once the targets file is create, the project file is edited to import the new targets file using Import. I put it above the first PropertyGroup node so it’s visible when future maintenance is performed, but it can be placed anywhere within the root Project node:

    <Import Project="$(MSBuildToolsPath)\T4Execution.targets" />

    Finally, the DefaultTargets attribute in the Project node is modified to include the ExecuteT4Templates target: Note: This change is required for any project where this behavior is desired.

    DefaultTargets="ExecuteT4Templates;Build"
    Now whenever the project is built (Ctrl+B), template execution occurs. To be fair, there are several issues with the above approach, including:
    • Template execution does not occur when Debug (F5) is triggered unless a project file or property has changed.
    • There is no built-in way to get the number of items in an ItemGroup to use conditional execution.

    How important is this functionality in your projects? How would you do it differently?

  • Pop Quiz: .NET Integers, Unit Testing, and Boundary Checking

    I ask this question in a bunch of my talks, mostly because most folks aren’t aware of this. What is the bug in the following method?

    public int Add(int num1, int num2)
    {
        return num1 + num2;
    }

    Do you see it? In a simple unit test, the method appears to work as expected:

    [TestMethod()]
    public void AddTest()
    {
        MathHelper target = new MathHelper();
        int num1 = 16;
        int num2 = 16;
        int expected = 32;
        int actual = target.Add(num1, num2);
        Assert.AreEqual(expected, actual); // PASS
    }

    However, what if we pass in a different set of parameters, say int.MaxValue?

    [TestMethod()]
    public void AddMaxTest()
    {
        MathHelper target = new MathHelper();
        int num1 = int.MaxValue;
        int num2 = int.MaxValue;
        int result = target.Add(num1, num2);
    
        Assert.Fail("Expected an overflow exception. Received: " + result);
    }

    Any guesses on the outcome of this test? In actuality, no exception is thrown. The test fails with the output: “Assert.Fail failed. Expected an overflow exception. Received: -2”. The output from the fail assert is “-2”. What!? Is it a bug in the .NET framework? What’s going on?

    The answer lies in that I am passing in a signed int. In a signed int, the top bit is flag bit indicating positive or negative, leaving the other 31 bits to indicate the numeric value. When doing binary math that overflows the 31 bits, the 32nd bit is switched as though it is unsigned. In this case a positive becomes a negative and the result becomes –2. Let’s hope the system isn’t trying to deposit $100 into an account with $2,147,483,647.

    But what does this mean to the original method? How do we handle this scenario? The point of this experiment isn’t to demonstrate a potential issue with the .NET framework. Rather, I’d like you to take notice of the first unit test. The test does evaluate the method for proper functioning, 100% code coverage would be achieved on the Add method, and yet the issue at hand is not found. And to this I would like to make an important point:

    Code Coverage is a misleading metric.

    In order to properly test your code, it is important to not only make sure you test as much as possible, but to ensure you also perform boundary checking. If the max values weren’t tested, it might not have been found that the code could erase $2,147,483,749 from some pour soul’s bank account. Well, he’d be poor after the fact. Are here is my second point:

    Boundary check everything.

    To help solve this problem, there is a neat tool from Microsoft Research called Pex. From the Pex website:

    Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Pex performs a systematic analysis, hunting for boundary conditions, exceptions and assertion failures, which you can debug right away. Pex enables Parameterized Unit Testing, an extension of Unit Testing that reduces test maintenance costs.

    What I would really love to see someday is a combination of existing code coverage in Visual Studio Team System with parameter boundary checking in Pex to give a truer sense of test coverage. Maybe for Dev11?

  • LINQ: Porting jQuery’s Each

    As some astute readers pointed out, this functionality does in fact exist in LINQ. The name isn’t terribly obvious however: Aggregate. I was able to update the original tests to use the Aggregate method. The main difference is that a non-generic IEnumerable does not contain this functionality. For that type I had to use:

    .OfType<>()

    The updated test methods are here:

    IEnumerable<string> collection = new[] { "Hello", "World", "!" };
    string result = collection.Aggregate((str1, str2) => (str1 + " " + str2).Trim());
    IEnumerable<int> collection = new[] { 1, 2, 3, 4, 5 };
    int result = collection.Aggregate((num1, num2) => num1 + num2);
    IEnumerable collection = new[] { "Hello", "World", "!" };
    string result = collection.OfType<string>().Aggregate((string str1, string str2) => (str1 + " " + str2).Trim());
    var collection = new List<string> { "Hello", "World", "!" };
    string result = collection.Aggregate((str1, str2) => (str1 + " " + str2).Trim());

    I love learning new stuff, thanks to Steve Gilham and Jordan Terrell for their comments below.

     

    I really like the Each function in jQuery, and I find myself wanting to use it in LINQ. Since it doesn’t exist I decided to write one. Here goes:

    using System;
    using
    System.Linq;
    using
    System.Collections;
    using
    System.Collections.Generic;

    public static class
    ExtensionMethods
    {
    public static TType Each<TType>(this IEnumerable<TType> collection, Func
    <TType, TType, TType> func)
    {
    var result = default
    (TType);

    foreach (var queryable in
    collection)
    result = func(result, queryable);

    return
    result;
    }

    public static TType Each<TType>(this IEnumerable collection, Func
    <TType, TType, TType> func)
    {
    return
    collection.OfType<TType>().Each(func);
    }
    }

    You can then call these extension methods using any IEnumerable type, such as List, Collection, etc. I’m utilizing lambdas to define inline methods, though a delegate to an existing method could be passed in as well.

    IEnumerable<string> collection = new[] { "Hello", "World", "!" };
    string result = collection.Each((str1, str2) => (str1 + " " + str2).Trim());
    IEnumerable<int> collection = new[] { 1, 2, 3, 4, 5 };
    int result = collection.Each((num1, num2) => num1 + num2);
    IEnumerable collection = new[] { "Hello", "World", "!" };
    string result = collection.Each((string str1, string str2) => (str1 + " " + str2).Trim());
    var collection = new List<string> { "Hello", "World", "!" };
    string result = collection.Each((str1, str2) => (str1 + " " + str2).Trim());

    What do you think? Would you do it differently?

    Posted Aug 26 2009, 07:26 PM by Steve with 3 comment(s)
    Filed under: ,
  • Static Page Checking in ASP.NET MVC

    If you have built an ASP.NET web forms site of any substance, you have undoubtedly been bitten when code in the web form becomes outdated due to code change. It’s easy to see when the page is open in Visual Studio, as the code has red squiggles and the error shows up in the Error List tool window. As soon as the page is closed however, that error disappears. Even running a build will be successful. For some of my sites, which have over 150 pages, this can be very annoying to say the least.

    ASP.NET MVC has a neat hidden feature to solve this problem. The MVC team was most likely were stung by the same issue more than once. This feature is static page checking during compilation. Unfortunately, instead of being an option in the Properties window for the project (future release idea?), it is in the *.*proj xml file itself. To enable this feature:

    1. Right-click on the Project node in the Solution Explorer tool window
    2. Choose “Unload Project” - Note: If your project is under version control, you will be prompted to do a check-in. Simply click “Continue” to ignore the check-in request.
    3. Right-click the Project node again
    4. Choose “Edit *.*proj", and the project file will now open in Visual Studio with color coding and IntelliSense
    5. In the first PropertyGroup node, there is a new node named MvcBuildViews
    6. By default this is set to false. Simply change the value to true
    7. Right-click the Project node and choose “Reload Project”
    8. If prompted that the file is already open, click yes to close the xml view.
    9. Build your project

    You will notice that builds take longer than they did prior to this change. This is because under the covers, MSBuild is now making an additional call to aspnet_compiler in the AfterBuild MSBuild target:

    C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe -v temp -p "[physical path]"

    To avoid this delay in day-to-day development, you may choose to copy the MvcBuildViews node into the build-specific PropertyGroup nodes, and set it to false for Debug and true for Release.

    Update: @jglozano points out that this only works with the default WebForms View Engine.

    Hope this helps

    Posted Aug 21 2009, 02:35 PM by Steve with 10 comment(s)
    Filed under: ,
  • Community Radio Episode Two

    I’m proud to announce that episode two of Community Radio has been published to http://live.ineta.org/audio

    In this episode, Steve talks with Heather Kostes, Emily Freet, and Nicole Moser about their roles at Microsoft, the MVP program, MVP benefits, becoming an MVP, karaoke, and more. Narrated by John Blumenauer.

    As always, your feedback is greatly appreciated.

  • European Union Says No to Free Dessert

    As reported all over the web this week, Microsoft has decided to ship Windows 7 in Europe without Internet Explorer. For a long time, the EU has been complaining that Microsoft has been using their dominant position to hawk IE on unsuspecting computer users.

    Horseradish!

    Let’s bring this discussion back across the pond for a second, and look at new home construction. The Department of Justice had a quarrel with Microsoft awhile back over a similar matter. Of course, if they were really going after monopolies they would go after the micro-monopolies of new home builders for charging egregious fees for options. Take for instance the elegant and simple recessed light. The last time I bought a new house the builder wanted $125 for every single one I added. A quick trip to Home Depot confirmed that the hardware costs less than $10, and wiring was equally inexpensive. I wanted to put their lights out.

    And what about the auto industry that forces you to choose from their tires, or their radios, or their floormats. Shouldn’t they be spanked? And what about government in general? Shouldn’t I be able to choose a DMV that offers better service if I want to? I think my four year old nephew could do that, and I’d gladly pay him instead.

    But let’s take a step back for a second and remember that there is a major difference between these comparisons and Internet Explorer. Internet Explorer is free. Free as in no charge. Free as in ‘No sir, you can keep your money’. You buy the operating system, and you get a free browser. Restaurants do the same thing; buy a meal, get a free dessert. Is the European Union really that uptight to complain about getting their dessert for free? And a dessert that can easily be replaced by downloading another browser? Maybe they don't like free things and will soon consider an air tax.

  • Community Radio Episode One

    I’m proud to announce that the inaugural episode of Community Radio has been published: http://live.ineta.org/audio

    In this inaugural episode, I talk with Richard, Carl and Sara about Speaker Idol, speaking at Tech-Ed, podcasting, .NET Rocks, Richard and Carl's back stories, and more. Narrated by Jeff Fritz.

    As always, your feedback is greatly appreciated.

  • Results – Community Radio Narration Contest

    The contest deadline has come and gone, and I received four submissions. After reviewing the submission I have determined that they were all great, so whoever sends me $500 first… just kidding. I’ve decided that the only satisfactory course of action is to use them all on a rotational basis. In fact, I’ve decided to use community contributions exclusively going forward because, well, this is your radio! The first four, in no particular (though apparently alphabetical) order, are:

    Would you like to introduce an episode of Community Radio? Record yourself in high-quality MP3 or WAV format speaking the following phrases. I look forward to your submissions!

    Intro:

    "[Hey, Hi, Howdy, Hey Y’all, etc.], this is [your name] welcoming you to Community Radio: connecting the developer community everywhere. Community Radio is powered by INETA Live and hosted by Steve Andrews: Microsoft MVP for Visual Studio Team System, Director of Technology for INETA North America, and all-around Community Fanatic. And now… to the communitymobile! Enjoy the show!"

    Note: In the second to last sentence, it's communitymobile, as in "To the Batmobile."

    Outro:

    "Thanks for listening to Community Radio: powered by INETA Live, and hosted by Steve Andrews. If you enjoyed this episode, pass us along to your friends and colleagues and check out our podcast archives at live.ineta.org. I’m [your name], join us next time for another edition of... Community Radio."

  • Community Tour 2010

    I think most folks know that I tend to speak at developer events from time to time. Actually in 2008 I gave 48 presentations at 32 events. My goal for 2009 is 52 events and I have 44 confirmed so far. Next year though I thought I’d take it up another notch. No, I’m not going for 72 events as some have suggested, nor am I retiring. Rather, I’m going on a North American tour and I’m currently on the hunt for a class A diesel motor home.

    Note: Image for dramatization only. Logos are for illustrative purposes and do not signify support from any organization. Also, CommunityTour.com is sadly already taken.

    As part of this tour, I am organizing and planning a number of programs, including:

    Community Events:

    continuing to speak at user groups, code camps, and other developer events.

    Guest Lecturing:

    engaging with college and university students about real-world programming, best practices, etc.

    Community Camp:

    teaching up-and-coming influentials about speaking, presentations, writing, blogging, the MVP program, the INETA Speakers Bureau, and more.

    Volunteering:

    continuing the idea of www.GeekFoodDrive.com and www.GeekGive.org by helping to organize volunteer opportunities at community events.

    Mobile Code Camp:

    bringing the code camp idea to smaller and under-represented areas in the US where there aren’t currently any community events

    Community Radio:

    talking with folks along the way, tapping the pockets of knowledge and sharing that knowledge with the community.

    Community TV:

    video interviews with community influentials.

    INETA Live:

    recording INETA Live webcasts from local technologists on the road.
    Community Organizers

    If you would like the Community Bus at one of your events next year, have feedback, are interested in organizing specific programs in your area, or you would be interested in riding along, please contact me.

    Sponsors

    To learn more about sponsoring the tour, please request a Community Tour 2010 Sponsorship Prospectus from the Contact page.

  • Community Radio Narration Contest

    I started recording episodes of Community Radio at Microsoft Tech-Ed 2009 in Los Angeles, California. Since coming back home, I’ve been hard at work editing these episodes and creating the intro/outro music. There is still one element missing however, the narrator. That’s where you come in.

    I’m holding a contest to find the Community Radio narrator. To enter, record yourself speaking the below intro and outro phrases in the highest quality format (either MP3 or WAV). The recorded intro and outro must be no longer than 27 seconds each. To submit your entry, send an email to Steve with a link to download your recordings. Entries must be received by 11:59 PM eastern time on Friday, May 29th.

    Intro:

    "Welcome to Community Radio: connecting the developer community everywhere. Community Radio is powered by INETA Live, located on the web at live.ineta.org, and hosted by Steve Andrews: Microsoft MVP for Visual Studio Team System, Director of Technology for INETA North America, and all-around Community Fanatic. And now… to the communitymobile! Enjoy the show!"

    Note: In the second to last sentance, it's communitymobile, as in "To the Batmobile."

    Outro:

    "Thanks for listening to Community Radio: powered by INETA Live and hosted by Steve Andrews. If you enjoyed this episode, pass us along to your friends and colleagues and check out our podcast archives at live.ineta.org. Narration by [your name]. Join us next time for another edition of... Community Radio."

    Good luck!

  • WinFormsMVC

    I’ve been working on a Windows Forms based project recently, and I quickly became frustrated at how unwieldy it became after just a short while. I have also been working a lot with the ASP.NET MVC framework recently, and I thought this model might work better, so I set out to build a proof-of-concept of what Windows Forms MVC might look like.

    So far I have a very rough framework, but it’s at a point where feedback would be beneficial so I have published the project over on CodePlex. So go take a look, browse the source, and let me know what you think!

    http://winformsmvc.codeplex.com

More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems
© Platinum Bay | Some Rights Reserved Creative Commons License

Disclaimer: The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Feel free to challenge me, disagree with me, or tell me I'm completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or annonymous comments) - so keep it polite, please.