RSS 2.0
# Sunday, May 09, 2010

Ok, one thing that I miss in Outlook 2010 is the ability to get an email’s properties from the listing.

image

Use to be that I could right-click on any of those and get the properties (full headers is what I’m looking at) so I could analyze them without actually opening the message.  Now I have to open the message to be able to see that information easily.  Am I missing something?

Sunday, May 09, 2010 1:53:17 PM UTC  #    Comments [0] -
Office 2010
# Tuesday, May 04, 2010

In this post, we are going to demonstrate some simple Ajax updates.  We will be using the AdentureWorks db for this.  You can download it here if you don’t have it.

Launch VS2010 and create a new ASP.NET MVC 2 Application:

image

For this, we’ll skip creating the test project.

Next we’ll use LINQ to SQL to generate some data models.  Right click on the Models node and Add Item (or Ctrl-Shift-A when the node is selected):

image

When the designer comes up, add the Product and ProductCategory tables.

image

In HomeController.cs create a new method called ProductSearch:

We’ll need to use our model, so add

using AWAjaxDemo.Models;

then we’ll add our new method:

public ActionResult ProductSearch(string query)
{
    IList<Product> products = new List<Product>();
    AWModelsDataContext db = new AWModelsDataContext();

    if (!string.IsNullOrWhiteSpace(query))
    {
        products = db.Products.Where(p => p.Name.StartsWith(query)).OrderBy(p => p.Name).ToList();
    }
    else
        products = db.Products.OrderBy(p => p.Name).ToList();

    if (Request.IsAjaxRequest())
        return View("ProductSearchResults", products);
    else

        return View(products);
}

 

We check to see if we have a query value coming in, if we do, we limit our query to names that start with the query. If not, we return them all.  Also note, that we check to see if this is an Ajax call. If someone has javascript off, we still want this to be functional.

Compile the project so we’ll have the model types available to us when we create our partial view.

Right click on Views/Home and add a View.  We’ll call this ProductSearchResults:

image

We’ll simplify the view down a bit to just include a few fields.  Of course, ideally we’d use a view-model for this to limit what data is even available, but that’s not the point of this post.

<%@ Control Language="C#" 
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<AWAjaxDemo.Models.Product>>" %>

    <table>
        <tr>
            <th>
                Name
            </th>
            <th>
                ProductNumber
            </th>
            <th>
                Color
            </th>
            <th>
                StandardCost
            </th>
            <th>
                ListPrice
            </th>
           
        </tr>

    <% foreach (var item in Model) { %>
    
        <tr>          
            <td>
                <%: item.Name %>
            </td>
            <td>
                <%: item.ProductNumber %>
            </td>
            <td>
                <%: item.Color %>
            </td>
            <td>
                <%: String.Format("{0:F}", item.StandardCost) %>
            </td>
            <td>
                <%: String.Format("{0:F}", item.ListPrice) %>
            </td>
           
        </tr>
    
    <% } %>

    </table>



So, now we have a simplified partial view.

Now we’ll add our main view.  Right-click on the View/Home node and add a strongly typed empty view.  Base it on the AWAjaxDemo.Models.Product type that we did for the partial view.

image

Replace the default code with this:

<%@Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<AWAjaxDemo.Models.Product>>"%>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
  
Product Search
</asp:Content>
<
asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <
script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <
script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <
h2>
      
ProductSearch</h2>
  
<% using(Ajax.BeginForm("ProductSearch", new AjaxOptions { UpdateTargetId = "results"}))
       { %>
    Search: <%=Html.TextBox("query")%> <input type="submit" value="Go" />
    <
div id="results">
  
<% Html.RenderPartial("ProductSearchResults", Model); %>
    </div>
  
<%} %>
</asp:Content>

You’ll notice that the two Ajax scripts are referenced.  They are added to mvc 2 applications by default.  The other thing to notice is how the form is constructed.  Normally the Html.BeginForm extension method is used. Here we are using the Ajax.Begin form method and passing it a new instance of AjaxOptions specifying the target to be updated. In our case, the target is the div with the id result.  Our ProductSearchResults partial view will be rendered there after the Ajax call.

That was pretty easy … of course in a production environment, you’d want to be using caching to reduce the database calls.

Technorati Tags: ,
Tuesday, May 04, 2010 1:56:30 AM UTC  #    Comments [0] -
mvc | Visual Studio
# Monday, May 03, 2010

So I installed Visual SVN the other day on the recommendation of my good friend Paul Mehner and the setup was amazingly simple and with the client ($49 USD), the integration with VS2010 is great!

image

Get nice color coded icons showing the state of the files.

And it’s own toolbar.

image

Technorati Tags:
Monday, May 03, 2010 5:32:56 PM UTC  #    Comments [0] -
Visual Studio
# Wednesday, April 14, 2010

One of the exciting things about mvc2 are Templated Helpers. Templated helpers allow you to create a template for any type – your own or a system type.

Let’s say we have a very simple model for a contact page.  Our model will be called ContactModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace EliteCodersLLC.com.Models
{
    public class ContactModel
    {
        [Required]
        public string Email { get; set; }

        public string Phone { get; set; }

        [Required]
        public string Inquiry { get; set; }

        [Required]
        public string Name { get; set; }
    }
}

We pulled in the DataAnnotations namespace so we could add some simple required validation for the class.  When we use the tooling built into Visual Studio to add a view by right-clicking in the controller action, we end up with a a view like so:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<EliteCodersLLC.com.Models.ContactModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Contact
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="paper">
    <div>
        <h2>
            Contact</h2>
        <% using (Html.BeginForm())
           {%>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Email) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Email) %>
            <%= Html.ValidationMessageFor(model => model.Email) %>
        </div>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Phone) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Phone) %>
            <%= Html.ValidationMessageFor(model => model.Phone) %>
        </div>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Inquiry) %>
        </div>
        <div class="editor-field">
            <%= Html.TextAreaFor(model => model.Inquiry) %>
            <%= Html.ValidationMessageFor(model => model.Inquiry) %>
        </div>
        <p>
            <input type="submit" value="Submit" />
        </p>
        <% } %>
        <div>
            <%=Html.ActionLink("Back to List", "Index") %>
        </div>
        </div>
    </div>
</asp:Content>

However, what we can do is pull all the editor type stuff out and put it into a templated helper.  First thing we want to do is created a directory under Views/Shared called EditorTemplates. This will be where any shared editor templates will reside.  Of course, if you only want the template to be used for a particular set of views, put it in that folder.  For instance, if it should only be used from the Home controller and Views, you would create the EditorTemplates directory under Views/Home.

image

In there we want to create a partial, strongly typed view giving it the name of the type it will be the editor for.  In our case it will be for the ContactModel class, so it will be called ContactModel.ascx.

We’ll put all the editor markup in this new view.  This view can be customized in any way and will be used whenever Html.EditorForModel() is called when the Model is a ContactModel.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EliteCodersLLC.com.Models.ContactModel>" %>
    <div class="editor-label">
        <%= Html.LabelFor(model => model.Email) %>
    </div>
    <div class="editor-field">
        <%= Html.TextBoxFor(model => model.Email) %>
        <%= Html.ValidationMessageFor(model => model.Email) %>
    </div>
    <div class="editor-label">
        <%= Html.LabelFor(model => model.Phone) %>
    </div>
    <div class="editor-field">
        <%= Html.TextBoxFor(model => model.Phone) %>
        <%= Html.ValidationMessageFor(model => model.Phone) %>
    </div>
    <div class="editor-label">
        <%= Html.LabelFor(model => model.Inquiry) %>
    </div>
    <div class="editor-field">
        <%= Html.TextAreaFor(model => model.Inquiry) %>
        <%= Html.ValidationMessageFor(model => model.Inquiry) %>
    </div>

And now our Home/Contact.aspx page simply has this inside the form:

        <% using (Html.BeginForm())
           {%>
        <%= Html.EditorForModel() %>
        <p>
            <input type="submit" value="Send" />
        </p>
        <% } %>

 

The same thing can be done for display templates as well. Do the same process but use DisplayTemplates as the folder name.

Happy coding!

Technorati Tags:
Wednesday, April 14, 2010 4:08:08 AM UTC  #    Comments [0] -
mvc
# Sunday, April 11, 2010

Well, VS 2010 launches tomorrow, and I’m really excited to get my hands on the final bits.  I’ve really enjoyed working with the beta and the RC.  MSDN is down for maintenance until tomorrow morning, probably beefing up the infrastructure to handle the influx of requests that will undoubtedly be coming tomorrow.

There are some wonderful wallpapers to be had here. I set mine to #3.

Technorati Tags: ,
Sunday, April 11, 2010 4:00:18 PM UTC  #    Comments [0] -
.NET | Visual Studio
# Monday, March 29, 2010

Today I’m going through Scott Hanselman’s recent OData post regarding StackOverflow.

I’m also going through a jQuery tutorial.

Monday, March 29, 2010 1:54:52 PM UTC  #    Comments [0] -

Found this one out by accident.  Put the mouse over the top or bottom border as if you are going to stretch the window up or down.  Then double click.  The window will snap full height keeping the current width.  Pretty cool!

Technorati Tags:
Monday, March 29, 2010 12:18:04 AM UTC  #    Comments [0] -
Windows 7
# Sunday, March 28, 2010

In the previous post we started talking about the Model. In this post we are going to add a little more substance to it.  The mason-dixon baseball site is mostly static, but there are a couple places that can benefit from the mvc model.  One in particular is the bat listing page.  This page lists the custom, hand-made bats that the company sells.

There are two listing sections, one for the most popular models which only lists the text and the full listing which shows the model number and an image:

image

There is also a listing for the wood staining:

image

And a listing of finished products and a description of the details of the finished bat:

image

So in looking at these listings, we can pull out the details of a model. 

    • Model #
    • Knob
    • Handle
    • Barrel
    • Unfinished Image
    • Finished Image
    • Popular

The listing of colors doesn’t fit into this model.  So for this exercise we are not going to focus on that.  We’ll concentrate on that when we discuss a ViewModel.

While this still is pretty static, it still qualifies for creating a model.

So, we’ll add both the BatModel and BatController classes and to keep the data easy, a bats.xml file.

image

Our Bats.xml file will be set like so:

<?xml version="1.0" encoding="utf-8" ?>
<Bats>
  <Bat>
    <ModelNumber></ModelNumber>
    <Knob></Knob>
    <Handle></Handle>
    <Barrel></Barrel>
    <UnfinishedImage></UnfinishedImage>
    <FinishedImage></FinishedImage>
    <Popular></Popular>
  </Bat>
</Bats>

 

Keeping our model nice and simple right now, it looks like this:

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

namespace mason_dixonbbaseball.com.Models
{
    public class BatModel
    {
        public string ModelNumber { get; set; }
        public string Knob { get; set; }
        public string Handle { get; set; }
        public string Barrel { get; set; }
        public string UnfinishedImage { get; set; }
        public string FinishedImage { get; set; }
        public bool Popular { get; set; }
    }
}

 

In the Controller class, we’ll use Reflection, so add:

using System.Reflection;

And we’ll be accessing the model:

using mason_dixonbbaseball.com.Models;

So our controller class will look like this:

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Web.Mvc;

using mason_dixonbbaseball.com.Models;

namespace mason_dixonbbaseball.com.Controllers
{
    public class BatController : Controller
    {
        //
        // GET: /Bat/

        public ActionResult Index()
        {
            List<BatModel> bats = new List<BatModel>();

            // Get our type and pull out the public properties
            Type t = typeof(BatModel);
            PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            // Pull the xml into a dataset
            DataSet ds = new DataSet();
            ds.ReadXml(this.ControllerContext.HttpContext.Request.MapPath("~/App_Data/Bats.xml"));

            // loop through the rows in the datatable and create BatModel instances
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                BatModel bm = new BatModel();

                foreach (PropertyInfo prop in props)
                {
                    // set our properties setting empty values = null
                    prop.SetValue(bm, 
                        string.IsNullOrWhiteSpace(dr[prop.Name].ToString()) ? null 
                        : Convert.ChangeType(dr[prop.Name], prop.PropertyType), null);
                }

                bats.Add(bm);
            }

            return View(bats);
        }

    }
}

Next we’ll add a View.  Right click in the Index method and choose to Add View:

image

Simply running that with some beginning css changes that were made, we end up with this output:

image

Technorati Tags: ,
Sunday, March 28, 2010 7:43:14 PM UTC  #    Comments [0] -
.NET | mvc
# Thursday, March 18, 2010

We are going to do this in phases to simulate the progression that might happen over time.  This will also show some of the different ways to work with controllers and views.

The first way we are going to get data from the controller to the view is to put values directly into the ViewDataDictionary.  This is the least flexible and most fragile.  It’s the least flexible because the content (in this example) is compiled into the assembly.  The most fragile because the ViewDataDictionary is keyed by a string.  Mistype and the results will be wrong.

ViewData[“Message”] = “Hello world.”;

Misspell something and you’ve got to recompile the assembly.

ViewData[“Message”] = “Hello wolrd.”;

Rather than put all the content into one entry, you might be tempted to create a separate entry for each item:

ViewData[“Paragraph1”] … ViewData[“Paragraphx”]

Of course since ViewDataDictionary implements IDictionary<string, Object> (among other things), the value is an object, you can put whatever you want in there.  For instance:

ViewData["Message"] = new List<String>() { "Paragraph 1", "Paragraph 2" };

Then in the view cast it back out:

    <% foreach (var item in (List<String>)ViewData["Message"])
       {%>
         <div>
         <%: item %>
         </div>  
       <%} %>

 

Enter the model.  No, not Gisele Bündchen, the mvc model. 

            image        

Views have a Model property on them. This can be anything.  If you don’t use a strongly typed view, it still needs to be cast.  So, we can move the List into the return statement like so:

return View(new List<String>() { "Paragraph 1", "Paragraph 2" });

 

This will populate the Model property with our newly formed list.  Then we modify our view code like so:

    <% foreach (var item in (List<String>)Model)
       {%>
         <div>
         <%: item %>
         </div>  
       <%} %>

 

Still not ideal, but we are getting there.  System.Web.Mvc.ViewPage offers a generic version as well.  We’ll get into that next…

Technorati Tags: ,,
Thursday, March 18, 2010 1:42:43 AM UTC  #    Comments [0] -
.NET | mvc
# Thursday, March 04, 2010

So my company has been tasked with taking over Mason-Dixon Baseball's web site.  It’s currently all just static html pages with a little bit of css (obviously from a tool of some-sort with class names like style25) embedded in the pages.  Having gotten the owner’s approval, I’m turning this into a blog-series and moving the site to asp.net mvc2.

Like I said, it’s all static html right now and there’s not really much need for a database backend, but there are a couple spots that could use a little bit of data storage – primarily for the bats page.

We will be using Visual Studio 2010 RC and asp.net mvc RC2 or our work.

We are going to build this in phases.  First phase will be very basic.  Nothing really going on, we are going to concentrate on breaking the site down and building out basic views, controllers and centralizing css and images.

So, let’s get started! Open Visual Studio 2010 and File | New (or hit Ctrl-Shift-N).  We’ll call our project mason-dixonbaseball.com.

image

Click ok to create the unit test project as well.

The first thing we are going to do is modify our routing.  Since basically we just have static pages, we are going to add a new route.  The route that comes out of the box is this:

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );

We want to keep this one around so we can utilize it later. So, we’ll change the name of that route and add a new one:
routes.MapRoute(
    "Default",
    "{action}",
    new { controller = "Home", action = "Index" }
    );

routes.MapRoute(
    "Id",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

 

This will allow us to have nicer urls like mason-dixonbaseball.com/bats.

In part 2, we’ll flesh out the controller.

Thursday, March 04, 2010 9:07:55 PM UTC  #    Comments [0] -
.NET | mvc
Archive
<May 2010>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
George Handlin
Sign In
Statistics
Total Posts: 51
This Year: 0
This Month: 0
This Week: 0
Comments: 9
All Content © 2012, George Handlin
DasBlog theme 'Business' created by Christoph De Baene (delarou)