Introducing AngelaSmith - The Object Initializing Smartypants

Our tooling in the .Net space is getting better and better, as well as the ecosystem that we work in. Take for instance Windows Azure Mobile Services – when we are dealing with greenfield development having your backend services running in minutes is a Godsend and having it work over multiple devices is chocolate on the sundae.  Your database is in place in minutes and you can easily access your data via REST.

What is something that all data-based applications require?  Data!  But missing from the data equation in green field development are two key parts to new app development: sample data and design time data.  If you understand those parts already and want to be able to fire up 250 persons like this:

     var people = Angie
.Configure()
.ListCount(250)
.MakeList<Person>();

…then skip below to the juicy bits.  For the rest of us, a quick primer.

Why It’s Important

For those of us building Windows Store or Windows 8 Phone apps, we have some incredible tools that make designing good looks apps super easy.

First is the MvvmLight Toolkit from Laurent Bugnion that allows you to quickly (and selectively) build out bindable view models, complete with properties, commands and, of course, your data.  If you haven’t worked with the data-binding approach, this is something you should be looking at if you use data at all in your apps.  If you’re not working with data at all in your apps, this is something that you should be looking at if you want users at all in your apps.

Second is the ability to use design time data through tools like Blend or Visual Studio 2012. Design time data sources usually provide static methods that can supply your IDE or editor of choice sample data while you’re designing your view.  It’s tough to build out a good looking UI without having actual data in there to see what things will look like.

When you put these two things together you get this great experience of seeing your app come together without having to build, deploy and run your app.

In other environments (Android, XCode) there may be similar facilities for design, but on all platforms, there’s the actual execution of the app on the device, and you probably want to get some data up there.  How do you test user-level security with only one user?  How do you build a geolocation app presenting points of interest if you don’t have any POI data?  View a contact list with no contacts?  What about just seeing how you app performs under load?  Build screen shots for your app store shots? 

You get the idea. You need data in there.

So You Want to Do the Data Binding Awesomeness

Great, so we agree that some measure of data is needed at some point of the app build process. You need a list of, say, 25 people, but how do you get those in there?  This is how we used to do it:

        List<Person> people = new List<Person>();
people.Add(new Person { FirstName = “Angela”, LastName = “Smith”, Age = 24, PhoneNumber = “867-5309” });
// …do this 23 times…
people.Add(new Person { FirstName = “Susan”, LastName = “Peters”, Age = 22, PhoneNumber = “555-1234” });

But that sucks. Big time.  Because you have to new up every object, and to make it look somewhat interesting, you have to also touch each row (not copy and paste). So you have to sift through 25 lines of code and try to come up with some believable objects.

A Way With Way More Awesome

How about this instead:

        List<Person> people = Angie.FastList<Person>();

Oh yeah. That's how AngelaSmith rolls. One line of code to get a list of 25 people (25 is the default list size).  All the properties are filled in for you as Angie recognizes many common property names. You can use Angie to build out a single object:
        var person = Angie.FastMake<Person>();
Angie’s not alone; she has a friend who can also help fill in a single property:
        string firstName = Susan.FillFirstName();

You can tell her how to build properties:

    var blogTitle = “Angie”;

var post = Angie.Configure()
    .FillBy(<span class="str">"title"</span>, <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> blogTitle; })
    .Make&lt;BlogPost&gt;();</pre>

Or, she can help you fill in properties (because she’s so smart):

     var comments = Angie
.Configure()
.ListCount(1000)
.FillBy(“CommentDate”, delegate() { return Angie.MakeDate(DateRules.PastDates); })
.MakeList<BlogComment>();

And, you can chain it all together to do some cool things.  Here, we’re building a blog post with 5 comments, all the dates are set to a date prior today, and the comments are created using an anonymous function:

  var blogpost = Angie
.Configure()
.FillBy(“CreateDate”, delegate() { return Susan.FillDate(DateRules.PastDate); })
.FillBy(“Comments”, delegate()
{
return Angie
.Set()
.ListCount(5)
.FillBy(“CommentDate”, delegate() { return Susan.FillDate(DateRules.PastDate); })
.MakeList<BlogComment>();
})
.Make<BlogPost>();

At the tail of that, we’re calling “Make” to get a single instance of BlogPost, but we could just as easily call “MakeList” to get a list of entities.

So Get Going!

To install AngelaSmith, use the Package Manager Console:

    install-package AngelaSmith

For more information, check out the AngelaSmith project on GitHub. Of course, you’re welcome to fork and contribute!

Stay tuned for great examples on how to seed data in Windows Azure Mobile Services, Entity Framework and more.

WordPress Conversion & Loss of Comments

In an effort to support some other ongoing initiatives I have migrated away from Orchard and onto WordPress.  For now, I have been able to move over all my old posts, however in spite of how much I have valued them, comments were not able to make the move. 

There also may be some problems with images for the next few days as I make the move, but I will get those restored ASAP.

To all you wonderful folks who have contributed to my blog over the last two years while I was on Orchard, thank you. Your comments, suggestions and questions are very much valued and I’m sorry that they were unable to make the cutover.

Calls to GetManifestResourceStream Always Return NULL

I was trying to load some text from a DLL where the text was saved into text files, included in the project and marked to be compiled as an Embedded Resource. I was using the below approach from the MSDN documentation:

    _assembly = Assembly.GetExecutingAssembly();
_textStreamReader = new StreamReader(_assembly.GetManifestResourceStream(“MyNamespace.MyTextFile.txt”));

I was building the namespace dynamically from the type, and I had the files in a Resources directory in my project. You can load the namespace from your type. When you put an embedded resource in a folder, you’re supposed to prefix the filename with “Folder.”  I thought I was all set.

Yet, this wasn’t working, so I eventually tried to eliminate any of the extra variables, inserting the namespace statically (the default namespace from my project) and moving the file into the root of my project.  Still no love.

I built my DLL and opened it up in ILDASM.  Guess what? No resources were being exported!  Lamesauce!

image

What what?!

So I went back into my project, tried removing and adding the files back again. I double- and triple-checked that my files were marked to be embedded resources.

image

Sanity check. I added a new text file to my project, called TextFile1.txt, the default in Visual Studio, set the Build Action to “Embedded Resource” and went back to my DLL.

image

Sweet jalapeño peppers! What was different!?

…oh.  Right. I am using the pattern “DomainNames.en.txt”, not “DomainNames.txt”. Notice I had the culture in there? That can’t possible make a difference, can it?  I renamed all my txt files, rebuilt and…

image

Booya!

So Remember!

If you are trying to load resources that are compiled into your assembly as Embedded Resources, it appears you can’t use extra “dotting” in your naming convention or the compilers won’t properly add your file to the manifest, at which point all calls to GetManifestResourceStream will return null.

EF5 Code-First Migrations on SQL Azure - Reference Not Supported

I am using EF5 Code-First as my database-backing poison. I’m building a web site – deployed to Windows Azure Web Sites – and have been really enjoying the seamless execution of migrations and the easy publish capabilities of Visual Studio 2012 and Windows Azure.

Some Things Go Bump

I just completed a migration that took a text field and normalized it, creating a separate table and populating that with the distinct values from the original text.  The migration pretty much worked itself out, except I needed to write INSERT and UPDATE statements to populate the strings in the new table.  This allowed me to then turn around and push the ID of the newly create entity back to the original table.

    Sql(“INSERT INTO [Database].[dbo].[DestinationTable] ([Name]) select distinct FieldName from SourceTable”);
Sql(“UPDATE [Database].[dbo].[SourceTable] SET [NewFKId] = (select PKID from DestinationTable where [Name] = FieldName)”);

As a thought exercise, imagine you were storing your Cities and States as text in a table called Locations.  You want to break State out into a separate table, and you want a reference to the State stored in your Location table, not the string version of that state.

With the generated migration, and my code above appended to the end of the Up() method, I was ready to go. Everything worked locally and away I went.

Then Came Production

Happily coding along, all my tests passing, I completed the related UI changes, committed my work and published to Azure using Web Deploy and saved Publishing Profiles.

Unfortunately, when the deployment completed and the site ran, I got this message as part of a YSOD.

Reference to database and/or server name in ‘[Database].[dbo].[DestinationTable]’ is not supported in this version of SQL Server

Gulp. Nothing like taking down a live site.

Side Note: What I Should (and Would) be Doing

Since I have multiple projects in the solution and I’m running with various web.config transforms, I’m unable to currently use GitHub publishing. It’s still early for this source control support in Azure, so there’s green pastures to look forward to.  I’m rolling my own CI here, and I have the project on GitHub, so I can’t fully automate. Thankfully, I have some PowerShell goodness going on that makes deploying to the cloud easy-peasy-lemon-squeezy and just one command from the console.

Down the road, when multi-site solutions and web.config transforms are supported through GitHub publishing, I’ll be able to use Windows Azure Web Sites’ built in capabilities for deployments. If something goes south, you just roll back to the last known good version of the site.

An Easy Fix

While the message points directly at the source of the problem, it’s still not clear on what you need to do to resolve it.  As it turns out, the limitation is in SQL Azure’s ability to use the three-part name of the table.  This doesn’t really matter, because I’m already connected to the database and I can just drop the name from my statements like so:

    Sql(“INSERT INTO [dbo].[DestinationTable] ([Name]) select distinct FieldName from SourceTable”);
Sql(“UPDATE [dbo].[SourceTable] SET [NewFKId] = (select PKID from DestinationTable where [Name] = FieldName)”);

I republished the site and everything worked as I wanted.

So, remember, if you’re getting the message that your database or server name reference isn’t supported in SQL Azure, and if you’re actually connected to the database in question, just drop the reference from the name to curtail this error.  If you’re getting this error because you are legitimately trying to connect to the other table, you should likely read up on it over here for some strategies (one of which might be loading your data into memory on the client to do the work you’re looking to do).

Cheers!

Know Your Network - The Azure Service Dashboard

Having trouble viewing your Windows Azure Website? In spite of all the inner voices’ assurances, it might not be you.

#

A Bump in the Night

I have had a very positive experience with Windows Azure. It just works. There have been a couple of headaches along the way, but I sort of expect that since my preferred flavour of Azure has been all the juicy bits still in preview mode.

I was awakened by the furnace kicking in at 4am – it’s 18 degrees Celsius below zero here right now – and was struck with some creative flair.  I shot downstairs to my basement office to work on an Asp.Net MVC site that I’m hosting on Windows Azure Websites.

After less than 15 minutes of work (sure the flair was creative, but it was also small) I attempted a push to the cloud.  And, yes, Steve, my tests were all passing. Smile The response:

image

Internet Explorer cannot display the webpage? Okay, let’s try Fiddler…

image

The server did not return a response for this request? Le sigh.

The Big Fix. Not.

imageThe thing I’m digging the most about Azure’s tooling is how it’s taking the friction away. When they introduced the “Download Publish Profile” a couple of months ago, it made the process of pushing a web site to the cloud crazy easy. And because your deployment settings (your publish profiles) are now part of your project, you can script this out and push to the cloud from the command prompt or even as part of your build script.

So I thought, “Hey, maybe I somehow mucked my publishing settings up?”.  I’ve been known to…uh….optimize the odd file or two by hand before. I cleaned out my publishing settings through the build menu (Build –> Publish Selection –> Profile –> Manage Profiles) then headed back to my Azure admin portal to pull down my publish profile. I imported it again and hit publish.  To the cloud!  Gold, right? Nope.

So, back to the portal. I knew something was going to be wrong with what I’d just done, so let’s leverage the built-in tooling for Azure: logging, error details and failed request tracing. This was going to give me something for sure.

image

You set these up on your “Configure” tab from your website dashboard.  Then you can access all the logs via FTP, the details are listed on your dashboard under the Diagnostic Logs heading in your sidebar.

Hit the page a couple times, refresh my stats. Still nada. Here’s what I was seeing from the stats chart:

image

Yeah, that’s right. No errors, no requests, no failed connections to the DB.  Zilch.  This is exactly what I want to see at any other time in production except when I’m actually getting errors.

Enough with this cloud business…time to kick it old school. I’ve been around the block and have run into similar things on IIS when there was a mal-formed config file.  Visual Studio didn’t have anything for me as far as errors or warnings, so I darted over to W3Schools to validate the document there. This was a long shot as my site was running locally, but I thought it was worth it.  Still, everything checked out and this failure is not due to my tag skills or lack thereof.

I headed back to my web.config and dropped in this classic, hoping it would spice up my error life:

  <customErrors mode=”Off” />

Still no love. I thought I was going crazy.  Technically, that didn’t have any relevance in regards to this problem, but I like to say that every now and then to keep my ego in check.

I muddled around a bit more in vain, determined to figure out what it was I busted.  An hour and a half in, certain that I had crossed all my i’s and dotted all my t’s, I finally decided to open a support ticket.  The menu option for this is on your portal when you click on your account name:

image

And then the trophy appeared:

image

You can verify the health of the Windows Azure Platform on the Service Dashboard.  Oh how I wish I had known that two hours earlier.  Check this out:

image

Guess which overtired, otherwise confident blurry-eyed developer hosts his Website in West US?

The Moral of the Story

I actually didn’t know that there was a service dashboard.  This is great. I’ve now pinned the site to my home screen on my Windows Phone, and the next time I wake up at 4 AM I’m going to check that little baby first before heading down for 15 minutes of Renaissance-style mid-night creativity.  So, I don’t have a moral to share here, just another tool for the war chest.

Before you pull your hair out fixing “your” problem next time, make sure your hosting provider is giving you all the sweet goods first!

Finally, if there are any shiny happy Windows Azure team members reading this, could you please, please add a notification on my dashboard if a service I am using is experiencing stress, a midlife crisis or apparent loss of network connectivity?  Thanks so much!

(p.s. By the time I finished writing this post, the Service Dashboard showed green checks for all my service friends)

Hack All the Things at Pure Imagination!

imageHackathons are great because they mean no excuses – nothing to get in the way of learning some new tech.  Better still are the great events where there are mentors and vendors with presence to make the event even more engaging.  Pure Imagination is offering this and more by setting you up with deep dive sessions and content from leaders in several of the core subjects you need to build the next big thing.

Shopify and 500px are the key “API sponsors” for the hackathon.  I’ve recently attended an API-themed hackathon (at PrDC Regina) and found this to be an incredible challenge, with results that just drop you. In spite of the fact that everyone’s using (essentially) the same APIs, the variations of themes and treatments and business plans and goals…it’s imageamazing what we clever devs can come up with!

And yet, they’re going even further still with some of Canada’s top VCs in attendance. You’ll get a chance to spend 10 minutes in front of them and pitch your idea, then they’ll help you see forest if your mind’s still in the trees.

All of this is lead by a keynote with Grant Skinner, and some great content on Windows 8, Azure, Visual Studio and concepts such as design, computing in the cloud, authentication and authorization and more.

Register here and follow @purelyimagine on the Twitters!