RSS 2.0
# Thursday, January 20, 2011

Ok, well, for whatever reason, I wasn’t able to get the old project working with MvcScaffolding after updating to the RTM of MVC 3.  I had even run the upgrade tool.  We are and were dealing with beta software, sometimes that’s what happens.  Thankfully we weren’t too far along.  So, what I’ve done is created a new project and simply added all our model classes to the new project.

I then reinstalled our packages from NuGet:

image

image

Now we will do some scaffolding.

image

Change the default route to point to our Recipe Controller:

image

And wa-la, we’ve got a running application.

image

Since we never defined a connection string for the application, it created a new database in our Sql Server Express instance with the fully qualified name of the context class.

image

So you can see that outside of create our model classes, everything else can be automated and done very quickly.  Understanding what is actually going on is important, so next we’ll look in more detail at the files that were created.

Technorati Tags: ,
Thursday, January 20, 2011 10:52:44 PM UTC  #    Comments [0] -
.NET | Entity Framework | mvc | SQL Server | Visual Studio
# Saturday, January 08, 2011

If you haven’t already, go install mvc 3 RC.  This will also install NuGet which we will be using.  You can read more about mvc 3 and NuGet on ScottGu’s blog.

Create a new MVC 3 Web Application and use Razor for the view engine.  Probably a good idea to tick on the unit test box to create unit tests.

image

Next get the Package Manager Console open.  View | Other Windows | Package Manager Console

Now we want to install the Entity Framework Code First libraries.  NuGet makes this very easy:

image

The console window support auto-completion, so just type Ins [TAB] and a list of options will show. Choose Install-Package then type EFC [TAB] to choose through a list of packages.  Couldn’t be easier.  I’m not going to go into details about what that does, you can read all about it in ScottGu’s posts and the video of Scott Hanselman’s talk.

In our first post in the series, our first goal was to make a quick site.  Doing it quickly means we are going to let the Entity Framework create the database for us.  We will also be using SQL CE so there won’t be a full database dependency.  SQL CE 4.0 is now bin deployable, so we can just copy it up and it’ll work.

EF, much like MVC, uses convention over configuration.  So, since our context (code to follow) is going to be named Cookbook, if we create a connection string entry called Cookbook, EF will automatically use that.

  <connectionStrings>
    <
add name="Cookbook" connectionString="Data Source=|DataDirectory|KimmysCookbook.sdf" providerName="System.Data.SqlServerCe.4.0"
/>
  </
connectionStrings>

As an aside, if you don’t create a connectionstring at all, EF CTP5 will create a Sql Server CE 4.0 database under the App_Data directory for you using the fully qualified type name as the name of the database.

Now for our Context class.  We’ll create each of our supporting classes as we go.  Right click on the Models folder and add a class.  As you are typing, as you put in the classes for the generic collections, pressing Ctrl-. will present you with a context of options.  Since the classes won’t exist yet, you can have VS create the classes for you right then.  They will of course be empty, but the shell is there.  VS is also intelligent enough to put them in the same folder as the current class with the same namespace.  So, when you type public DbSet<Recipe, you’ll get a squiggly saying that Recipe doesn’t exist.  Ctrl-. and choose to have it create the class for you.

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

namespace KimmysCookbook.Models
{
    public class Cookbook : DbContext
    {
        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<Ingredient> Ingredients { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<Favorite> Favorites { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<Rating> Ratings { get; set; }
    }
}

The above context class is all that is needed for data access.

Let’s fill in the rest of our classes.

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

namespace KimmysCookbook.Models
{
    public class Recipe
    {
        public int ID { get; set; }
        public Guid UserID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public long PrepTime { get; set; }
        public long CookTime { get; set; }
        public int Serves { get; set; }
        public string Instructions { get; set; }
        public string IPAddress { get; set; }

        public virtual ICollection<Ingredient> Ingredients { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }
        public virtual ICollection<Rating> Ratings { get; set; }
        public virtual ICollection<Favorite> Favorites { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KimmysCookbook.Models
{
    public class Ingredient
    {
        public int ID { get; set; }
        public int RecipeID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KimmysCookbook.Models
{
    /// <summary>
    /// This is for user based tagging
    /// </summary>
    public class Tag
    {
        public int ID { get; set; }
        public int RecipeID { get; set; }
        public Guid UserID { get; set; }
        public string Value { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KimmysCookbook.Models
{
    public class Comment
    {
        public int ID { get; set; }
        public int RecipeID { get; set; }
        public Guid UserID { get; set; }
        public string Text { get; set; }
        public string IPAddress { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KimmysCookbook.Models
{
    /// <summary>
    /// This is to tag a recipe as a favorite for a user
    /// </summary>
    public class Favorite
    {
        public int ID { get; set; }
        public int RecipeID { get; set; }
        public Guid UserID { get; set; }
        public DateTime DateFavorited { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KimmysCookbook.Models
{
    public class Rating
    {
        public int ID { get; set; }
        public int RecipeID { get; set; }
        public Guid UserID { get; set; }
        public int Value { get; set; }
        public DateTime RatingDate { get; set; }
        public string IPAddress { get; set; }
    }
}

You’ll notice in the classes that the UserID field is a Guid. In this iteration, we are going to use the Membership provider that is baked into asp.net. In a future release, we plan to use OpenID instead. That being said and to keep it simple, we want to have the membership baked into the database that EF is going to create.  Unfortunately, SQL CE 4 still doesn’t support stored procedures so the current implementation of membership won’t work with it.  According to ScottGu’s post, they are looking into create a set of providers that will work with it. 

Technorati Tags: ,
Saturday, January 08, 2011 8:22:55 PM UTC  #    Comments [2] -
.NET | Entity Framework | mvc | SQL Server
# Saturday, November 06, 2010

Even with the new Windows Phone 7 coming out, I’m sure there are still some of out there that are building applications for the older Windows Mobile platforms.  I’ve been doing them for years but had a break for probably a year.  Most of my older development was either Pocket PC stuff or WinMo 5.x. 

Fast forward to now.  Had a project come up that was with Windows Mobile 6.5.  Being that I love Visual Studio 2010 like it was one of my kids (maybe not quite that much), I sought out the SDK for Mobile 6.x for VS2010.  Well, no such luck, it’s not supported.  Back to VS2008 we go.  So I go download the DTK for it and install it.

Ok, all installed and ready to.  Now it’s time to create the demo for the project.  So I create a quick little something with a few screens and very little functionality just to get ideas down for the client to look at.  Go to build it to test the little bit that’s’ in it and get some screen shots.  F5 and we wait and wait and wait … literally for minutes.  Ok, this can’t possibly be right.  Off to Bingle an answer.  I find a lot of people experiencing the problem (from quite a while ago), but no real answers.  Fine, suck it up and just get moving forward because of the time constraint on the project. 

About once a week or so, I’d get so frustrated at the build times that I’d search again, trying various different search terms.  One person said it had to do with the references being made in the project – poppycock.  One suggestion was to kick of MSBuild via the command line to speed the build. By this time, my build was literally taking about 5 minutes.  This still isn’t a very big solution – it’s one project with 4 screens and a few classes.  Building from the command line took about 5 seconds.  Ok, something to do with the building process in VS.  Search some more.

So I ran across this article from VS2005 days talking about the Platform Verification Task (PVT).  I read through the article (quickly) and tried to implement the fix.  Well, it didn’t work for me.  Frustrated as anything, I shoot off an email to Scott Hanselman and we start trying to narrow it down via email.  He found the same article and pointed me to it. Told him I had already tried it and it didn’t seem to work. So he figured it had to be some add-in or something else and suggested firing up Process Explorer and trying to debug it.  Before going through all that, I decided to check that PVT article again and double check what I had done.  Well, it was BKAC and I had a typo.  Fixed the typo and VS builds in seconds too!  Thank you Scott!

So, I do recommend reading the PVT article referenced above, but here is the nitty-gritty on what needs to be done:

  • As an admin, navigate down to %windir%\Microsoft.NET\Framework\[Target Version].  In my case, it’s 3.5.
  • In there, you will need to edit Microsoft.CompactFramework.Common.targets.  This is just an xml file.

image

  • Find the line (about 2/3s down) that says Name="PlatformVerificationTask" you’ll want to modify it to Name="PlatformVerificationTask" Condition="'$(SkipPlatformVerification)' != 'true'"

image

  • Next, you need to add an environment variable.  Go into the properties of the computer and go into Advanced system settings

 

image

image

 

  • Now create a variable called SkipPlatformVerification either for the user (what I did) or the whole system and set it’s value to true.  If you later want to turn the verification back on, change the value to false.

 

image

  • Restart Visual Studio if you had it open.

I hope this helps some people out, it frustrated me for a LONG time….

Saturday, November 06, 2010 4:44:25 PM UTC  #    Comments [0] -
.NET | Windows Mobile
# Friday, October 29, 2010

Microsoft Press is giving away Charles Petzold’s new book Programming Windows Phone 7.  If you have an interest in this platform, go get yourself a copy.  The book is about 1,000 pages and 24 chapters long.  It covers both Silverlight and XNA programming.  I just downloaded my copy a minute ago and am eager to start reading it.

 

http://blogs.msdn.com/b/microsoft_press/archive/2010/10/28/free-ebook-programming-windows-phone-7-by-charles-petzold.aspx

Technorati Tags:
Friday, October 29, 2010 1:16:34 AM UTC  #    Comments [0] -
.NET | Windows Phone 7
# Monday, August 23, 2010

Microsoft released a beta of Lightswitch the other day.  Here I’m going to do a run through of creating a simple application. I’m doing this without having read much of anything about Lightswitch.

image

So, choosing this project template and after a bunch of churning, we get presented with this:

image

Since this is a fresh new application, we’ll choose to create a new table.  Doing so, we are presented with this:

image

Let’s just make a simple contact table and later build from that.

image

Notice that there are properties associated with the entity that we are creating.  I’m guessing the properties on the generated class will be decorated with attributes from the DataAnnotations namespace.

For the State property, we’ll add a “Choice List” with a few states in the USA:

image

image

Next we’ll create a “screen” from the “Add” bar.

image

Before we do, let’s rename the “table” to “Contacts”

image

We’ll choose “List and Details Screen”, change the screen name to “ContactListDetails” and choose “Contacts” for the screen data:

image

We are now presented with this:

image

Ok, so let’s build it and run to see what we get.

image

Not bad for about 10 minutes worth of work.

Next we’ll play around with this form and see what else we can do.  There was no code written for this at all.  We’ll dig into the files that are created with this project and see what is generated behind the scenes.  Switching from the Logical View to the File View, we can see that there is a hierarchy of files to look into.

Technorati Tags: ,,
Monday, August 23, 2010 3:00:56 AM UTC  #    Comments [0] -
.NET | LightSwitch | Visual Studio
# Friday, May 21, 2010

Was working on the beginnings of a new project and building up a database just by using a file based database connecting with SQL Express.  When it’s actually deployed, it’ll be on a full SQL Server, so I scripted the database and executed the script on my local SQL Server.  The database already had the membership tables built in.  I also knew that I’d not be connecting to it via sa for obvious reasons, so I created a stripped down SQL account to connect with. Good enough.

So, modify web.config to change the connection string and the each of the provider entries to point to the new connection string.  Simple enough.

Run the application connecting to the server and greeted with this:

The 'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'.  However, the current database schema is not compatible with this version.  You may need to either install a compatible schema with aspnet_regsql.exe (available in the framework installation directory), or upgrade the provider to a newer version.

Things that make you go hmmmm…

headscratch 

So, I quickly Google with Bing and find this. http://forums.asp.net/p/985097/1267872.aspx.  Ok, fair enough, I did just script it rather installing it.  So I ran aspnet_regsql to remove everything then ran it again to add it all.  Ok, the schema table that’s mentioned in that article is populated and anything else that might get missed from scripting should be there as well, right?  Right … well…

Run it again and same error.  Ok, change the connection to use sa and run again.  Works.  Ok, permissions issue.  Originally had the permissions set up for the account that I wanted to use for the application:

image

Scrolling up a bit however, I notice a bunch of permissions just for all the membership stuff. 

image

Ah, all I’m using right now is basic reads from the membership stuff, so just gave the account the above permissions and we are in business!

Hope this helps someone else along the way!

Friday, May 21, 2010 12:52:27 PM UTC  #    Comments [0] -
.NET | SQL Server | Visual Studio
# 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
# 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
# Saturday, February 13, 2010

Well, technically it is, but that’s not really my point in this.

Working on a project now that has everything coming in as a DataTable to the UI – single entity records, child entity records, lookup data – everything.  Using one for a simple ListBox or DropDownList is tolerable, but I still prefer to have my own class that I bind to.

I felt bad for the guy that had to deal with it, writing lines like these to deal with it:

NumberOfUnits = Convert.ToInt32(dt.Rows[0][FIELD_NUMBER_OF_UNITS].ToString());

txtLocation.Text = dt.Rows[0][FIELD_LOCATION].ToString();

Not only is this cumbersome and error prone (nevermind the unneeded ToString() in the first example), it is also not DRY at all.  Every time one of these things is needed, the same code was written to extract from the DataTable.  Of course, the argument was to “keep it simple” and we know that usually ends up not being simple.  Taking the extra small step of creating some entity classes that have a constructor that takes in a DataReader would have not only made the other developers life much easier, it would also allow for further extendibility, encapsulation, etc.

Saturday, February 13, 2010 9:33:29 PM UTC  #    Comments [0] -
.NET | ttsbd

I go through quite a bit of other people’s code and I see many things that could be done better and some things that simply shouldn’t be done.  I’m going to post about some of the things that shouldn’t be done (ttsbd).

A Date is a Date

A date is a date, so treat it as a date.  Don’t pass it around as a string.

String Emptiness

I see this a lot:

if (mystring == “”)

Well, if mystring actually equals “ “, that’s probably not what you want either.

Consider the follow:

  1. using System;
  2.  
  3. namespace ConsoleApplication1
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             string s = null;
  10.             Console.WriteLine("string s = null;");
  11.             TestS(s);
  12.             Console.WriteLine("");
  13.  
  14.             s = " ";
  15.             Console.WriteLine("s = \" \"");
  16.             TestS(s);
  17.  
  18.         }
  19.  
  20.         static void TestS(string s)
  21.         {
  22.             Console.WriteLine("\ts == \"\": " + (s == "").ToString());
  23.             Console.WriteLine("\ts == String.Empty: " + (s == String.Empty).ToString());
  24.             Console.WriteLine("\tString.IsNullOrEmpty(s): " + String.IsNullOrEmpty(s));
  25.             if (s != null)
  26.                 Console.WriteLine("\tString.IsNullOrEmpty(s.Trim()): " + String.IsNullOrEmpty(s.Trim()));
  27.         }
  28.     }
  29. }

I’ll post more ttsbds at different times.  These were just a couple that were bugging me recently.

Saturday, February 13, 2010 9:25:59 AM UTC  #    Comments [0] -
.NET | ttsbd
# Thursday, January 14, 2010

Scott Hanselman and the .NET Framework Setup team have a favor to ask … See Scott’s post for all the details.  I’ll be helping out with a few machines I have available to me.

Thursday, January 14, 2010 12:34:56 PM UTC  #    Comments [1] -
.NET
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
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)