Using the Windows Phone 8.1 Start Background to personalize your phone

A great way to personalize your Windows Phone 8.1 device is a custom start background.  You are no longer limited to using the 20 or so accent colors as the default tile color.  You can now select an image file to use as the background.

When you select an image, it becomes a fixed background.  When you scroll the start page, the location of the image stays fixed,   Most of the bundled apps will use a transparent background when a background image has been select, allowing the background image to show through.

This allows you to personalize your phone even more to your tastes.  You can use any image that is on your phone or accessible through OneDrive.  I have found that using darker, muted colors worked well, providing a good contrast with the foreground tile color.

You can select the image under “start+theme”, in the settings app. You should see something like this:

start+theme, under settings

When you click choose photo, you get the standard image picker and you can select an image that is on your phone or in your OneDrive account.

The image that I used here is from the DeviantART web site.  I did a search on “grunge” and selected a couple of images that I liked.  This image is named Hazard Grunge and is from the user named WheelOfFish.

After selecting the picture, you will then select which area of the picture to use as the background.  Since the image will mostly likely not match the aspect ratio of your phone, you select which part to use.

Clip the image

With the final result, you get a much cooler looking start page.  And it looks more like your phone than just another Windows Phone.

My Phone

Resolving the “The ‘CctSharedPackage’ package did not load correctly.” error message

"'a' stands for headache" by Eduardo Ortiz

After launching an Azure project in Visual Studio 2013, I was handed a “The ‘CctSharedPackage’ package did not load correctly.” error message.

The 'CctSharedPackage' package did not load correctly.

I was unfamiliar with that one, and a quick check of the forums showed that a few people had reported this happening after installing the latest Windows 8.1 update. An update that I had installed two nights ago.

If you check the Visual Studio activity log in %APPDATA%\Microsoft\VisualStudio\12.0\ActivityLog.xml, you’ll see something like this

<entry>
  <record>1638</record>
  <time>2014/04/14 02:36:02.772</time>
  <type>Information</type>
  <source>VisualStudio</source>
  <description>Begin package load [CctSharedPackage]  </description>
  <guid>{77A5A151-6A9B-4D08-BC38-340AB29566E2}</guid>
</entry>
<entry>
  <record>1639</record>
  <time>2014/04/14 02:36:02.773</time>
  <type>Error</type>
  <source>VisualStudio</source>
  <description>SetSite failed for package [CctSharedPackage]  </description>
  <guid>{77A5A151-6A9B-4D08-BC38-340AB29566E2}</guid>
  <hr>80070002</hr>
  <errorinfo>Could not load file or assembly 'Microsoft.VisualStudio.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.</errorinfo>
</entry>

Something in the Windows 8.1 April Update blew out at least one assembly that Visual Studio needed. This has an easy work around. Shut down any instances of Visual Studio that you may have running. Go to “Programs and Features” in the “Control Panel” and look for an item that starts with “Windows Azure Tools for Visual Studio 2013″.

Double-click that item to bring up the modify setup dialog. On that dialog select “Repair”.

Azure Tools Modify Setup dialog

That will churn for a minute or two. After that completes, you should be back in business. If you are using the Azure Tools with other versions of Visual Studio, you may may to repair them as well.

An alternative means of fixing this is by re-installing the missing assembly into the GAC as described on Stefan Camilleri’s blog.

<code>C:\Program Files (x86)\Windows Azure Tools\Visual Studio 11.0&gt;gacutil /i .\Microsoft.VisualStudio.WindowsAzure.Diagnostics.dll</code>

I chose the self repair option of the Azure Tools installer, because I had no idea if anything else was broken.  That’s the why Windows Installer technology has the repair option.  It will fix the stuff under the hood that you can’t easily see.

Once I got that straightened out, I checked to see if there was a later version. I was at v2.2 and v2.3 was released during //Build. So I grabbed that and installed. I probably could have just upgraded straight from 2.2 to 2.3 without repairing the v2.3, but I did this way with out any problems.

*The “a” is for headache image is from Eduardo Ortiz’s collection on Flickr

Best single source for dealing with iOS battery drain

If you or anyone you care about has been dealing excessive battery drain on the iPhone, a former Apple Genius Bar staffer has written the single best resource.  Scotty Loveless posted The Ultimate Guide to Solving iOS Battery Drain on his blog.  Bookmark it, print it, Instapaper it, just keep a copy of it somewhere.

His article was aimed towards iPhone users, a few of the tips are applicable to all smart phones.

Bundling jQuery 2.x and jQuery 1.x in ASP .Net MVC and staying NuGet fresh

Fork in the road
If you use Nuget to install jQuery into your application, you’ll need to take some extra steps to support multiple versions of jQuery.  By default, NuGet will uninstall previous versions of a package.  The way around this is to create another folder inside the scripts folder and put the older jQuery-1.. files in it. I got the idea for doing this from a post on StackOverflow

Right click on the Scripts folder and select Add->New Folder.  Give the folder a name that has some meaning to you, I used “compatibility”.  Select the jquery-1.* files and move them to the new folder.  You can copy them or move them, it doesn’t really matter.

Then install the latest version of jQuery using NuGet.  From the Tools menu, select Library Package Manager->Package Manager Console.  From the package manager window run the following:
Install-Package jQuery

You should see something like this:

Package Manager Console
Package Manager Console

It installed jQuery 2.1 and then it removed the jQuery 1.10 package.  It complained that it couldn’t find the intellisense file for the previous version. That’s because I had moved it to the new folder.

Now it’s time to update the bundles. When you create a new web project, ASP .Net will create some bundles for you. A bundle is a collection of scripts and stylesheets and does a neat little trick where at debug time you get the individual files as if you had specified each one in the web page. At runtime, the files are minified and consolidated into a single file. This compresses the payload and saves on loading time as the browser only needs to make a single request to get the files in the bundle. Any hoo, if you create a ASP .Net project in the current version of VS, you will get this bundle definition in BundleConfig.cs:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));
        // Other code removed...
    }
}

This call to bundles.Add creates a new bundle named “~/bundles/jquery” and uses the {version} regex placeholder, (\d+(?:.\d+){1,3}), to match the jQuery file without having to specify the version. You don’t have to worry about your code breaking due to an invalid reference to jQuery when NuGet updates jQuery.

What we do now is add a second bundle that will use the older version of jQuery. Since we copied those files to a new folder, NuGet is blissfully unaware of their continued existence and will not remove them. We just create a ScriptBundle with a new name and have it specify the folder that we put the old version of jQuery in.

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jqueryold").Include(
            "~/Scripts/compatibility/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js"));
        // Other code removed...
    }
}

The final step is to update the shared layout view that MVC puts the jQuery script reference in.

With a new project, you will edit the Views\Shared_Layout.cshtml file. The default jquery reference will look like something this:

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

What we need to do is the replace the @Scripts.Render line with a conditional block of code that checks for older versions of Internet Explorer.

    <!--[if lt IE 9]>
    @Scripts.Render("~/bundles/jqueryold")
    <![endif]-->
    <!--[if gte IE 9]><!-->
    @Scripts.Render("~/bundles/jquery")
    <!--<![endif]-->
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

We use IE’s Conditional Comments to detect previous versions of IE. This a feature specific to IE versions 5 through 9. All other browsers will treat the Conditional Comments as regular HTML comments.

<!--[if lt IE 9]>

With this line, IE 5-9 (and 10 in compatibility view) will treat this as the start of a block of code. All other browsers will treat this as the start of a comment block. The block is closed when it hits “–>”.

    <!--[if gte IE 9]><!-->
    @Scripts.Render("~/bundles/jquery")
    <!--<![endif]-->

With this block, we are saying if IE is greater than or equal to version 9, to use this block. The “<!–>” on that line tells IE 10 and the other browsers to close out this comment block which makes that block of code available to the browser. This will allow you to stay current by letting NuGet updating jQuery, while still keeping some level of compatibility with older versions. This is one of the times where IE extending HTML in a proprietary way is useful.

The fork in the road image was modified from an creative commons licensed image posted by Eric Hamiter to his Flickr collection.

Sometimes 42 is the right answer

Prime Meridian

I was skimming the Codist blog when I read the following

One of my favorite data errors was when the latitude would be randomly in the 1000s even though the longitude was correct. MapKit would toss a fit so since I can’t know what the right value is, I just use 42 which puts the pin at the wrong location but at least it’s not crashing.

I just started laughing. Been there, done that, want it on a t-shirt.  When collecting positional data from other sources, sometimes you just get bad data in.  And in this case, 42 is the Ultimate Answer.

A while back I had written a data collection service that was collecting vehicle positions from onboard GPS device.  Every now and then, the locations became random.  This app was running in the continental US,  any latitude/longitude values outside that range for that area were just ignored.  In my case, any wrong location was unusable data.

The Prime Meridian image comes from Lindsay Holmwood’s Flickr feed.

A file versioning helper class in C# to make a backup copy of a file and keep the last N copies of that file

Cicero denouncing Cataline

While testing my configuration editor app, one of the QA guys asked if it made a backup copy of the file being edited.  My reply was “not yet”.  And I thought about it a bit and decided to implement the backup feature and to kick it up a notch.

In prehistoric times, VMS would automagically version your files when you saved them.  When you saved a file, the file system  would append a version number starting at 1.  You could open any version of a file by including the version number.  If you left out the version number, you got the latest version.  This goes back to the days when monitors supported both colors, green and not green.  To clear out older versions, you would periodically need to run the purge command.

Prehistoric times for web developers

Prehistoric times for web developers

I wanted something close to that in my code, except without having to manually purge the file system.  I wrote a simple static class that takes the name of the file and the number of versions to keep.

public static class FileHelper
{
    /// <summary>
    /// Make a numbered backup copy of the specified files.  Backup files have the name filename.exe.yymmdd##, where yymmdd is the date and ## is a zero justified sequence number starting at 1
    /// </summary>
    /// <param name="fileName">Name of the file to backup.</param>
    /// <param name="maxBackups">The maximum backups to keep.</param>
    public static void MakeBackup(string fileName, int maxBackups)
    {
        // Make sure that the file exists, you don't backup a new file
        if (File.Exists(fileName))
        {
            // First backup copy of the day starts at 1
            int newSequence = 1;

            // Get the list of previous backups of the file, skipping the current file
            var backupFiles = Directory.GetFiles(Path.GetDirectoryName(fileName), Path.GetFileName(fileName) + ".*")
                .ToList()
                .Where(d => !d.Equals(fileName))
                .OrderBy(d => d);

            // Get the name of the last backup performed
            var lastBackupFilename = backupFiles.LastOrDefault();

            // If we have at least one previous backup copy
            if (lastBackupFilename != null)
            {
                // Get the last sequence number back taking the last 2 characters and convert them to an int. And add 1 to that number
                if (Int32.TryParse(Path.GetExtension(lastBackupFilename).GetLast(2), out newSequence))
                    newSequence++;

                // If we have more backups than we need to keep
                if (backupFiles.Count() >= maxBackups)
                {
                    // Get a list of the oldest files to delele
                    var expiredFiles = backupFiles.Take(backupFiles.Count() - maxBackups + 1);

                    foreach (var expiredFile in expiredFiles)
                    {
                        File.Delete(expiredFile);
                    }
                }
            }

            // Create the file name for the newest back up file.
            var latestBackup = String.Format("{0}.{1:yyMMdd}{2:00}", fileName, DateTime.Now, newSequence);

            // Copy the current file to the new backup name and overwrite any existing copy
            File.Copy(fileName, latestBackup, true);
        }
    }
}

You would use this method like this:

FileHelper.MakeBackup("web.config", 5);

The first time you called it, you would get web.config.14031401. The next time would get web.config.14031402. When web.config.14031406 was created, web.config.14031401 would be deleted to keep the number of backups limited to 5.

We had a great TVUG meeting this week

Peter

A couple of nights ago, @PeterLanoie did a great presentation on IIS administration.  This was at the March TVUG meeting.  We had a good sized crowd and there were plenty of questions and discussions from the audience.  Peter had some cool tricks to show off.  Like how to use an App_Offline.htm file to take a site offline while making updates.

We spent a lot of time going over session management, multiple levels of configuration files, deployments, and how to handle those types of thing when you have a web farm.  As developers, we don’t always have the experience or knowledge to optimize IIS for large traffic sites.

Peter spent over two hours drilling in deep on these topics.  It’s great when a user group member can step up to the plate and Peter knocked this one out of the park.

TVUG

If you are in the Albany, NY area, check out TVUG.  That’s the Tech Valley .Net User Group, located right in the middle of Tech Valley, NY.  We usually meet on the second Tuesday of the month.  We have a mailing list that you can sign up for and we have a MeetUp page.  You can also find us on Facebook and Twitter.

Validating a GUID input, TryParse vs RegEx

Once again I’m validating some text inputs, this time I need to verify that a user has entered a GUID in a valid format.  While I can’t verify that the user has entered the correct GUID, I can check to make sure that I have the right characters in the string.

The choice is between a method in the .Net Framework for parsing GUID values or using a regular expression. The commonly accepted formats for a GUI are the following

  • {0C885DD3-7DD9-484B-9B20-3E6552BCA144}
  • 0C885DD3-7DD9-484B-9B20-3E6552BCA144
  • 0C885DD37DD9484B9B203E6552BCA144

You usually see it written as 32 hexadecimal characters, separated by hypens into 5 groups.  There are some other variations, but this is what you see for text representations of GUIDs.

Going via the .Net Framework, we can use the Guid.TryParse() method. This method takes two parameters, the string to parse and an out parameter that gets the parsed GUID.  TryParse() returns true if it can parse the string, false if the string input is not a valid GUID format.  It happily takes GUIDs in all three formats list above.

The regular expression that I found for GUID validation is, as with almost all regular expressions, a hideous mess of seemingly random characters.  A well crafted regular expression should look like line noise from a 300 baud modem.  This regular expression would validate a GUID:

^[{]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[}]?$

That’s not very friendly when you first see it. Lets break it down:

^$

The ^ and $ characters match the start and the end of string, everything else takes place with the string to match. We are basically saying, use the entire string input to validate against.

[{]?

This says match the “{” character and the question mark states that it is optional

[0-9a-fA-F]{8}[-]?

This says match 8 characters using all of the digits and the letters from A to F. It’s case insensitive and there is an optional “-”.

([0-9a-fA-F]{4}[-]?){3}

This says match 4 characters with an optional hyphen, 3 times in a row.

[0-9a-fA-F]{12}

This matches the final block of 12 characters (with optional hyphen)

[\)|}]?$

We end with an optional match for “}”.

The source for this regular expression was one submitted by Nicolas Berardi on the RegExLib site.  There were a few other GUID validation strings on that site, his looked the best. I did change his expression, it was also allowing for “(” and “)” in addition to the curvy brackets.  I don’t think that makes the GUID valid, so I removed it. The “{” and “}” are not part of the IETF 4122 standard, if you are matching UUIDs, then you may want to take out the part that allows for those characters.

The problem is that it would validate text inputs that shouldn’t validate.  If your GUID string had a single hyphen, it would pass the regex test, but would fail when used by the .Net Framework.  It was also much slower than the TryParse() code, roughly 25 times slower on average.

For user interaction, the performance hit would be negligible. If you were doing a batch import program and were validating the data, you’re going to take a performance penalty hit when you use regular expressions.

The following code shows both implementations with some samples to parse:

The last two sample strings should fail the parsing. The last one only is short one character, the one before it has only one hyphen. The TryParse method works correctly for all of the values, the RegEx fails on the one with a single hyphen. You should be able to tweak the expression by testing for 5 hyphens or for no hyphens. Then you would get this easy to remember version:

^[{|\(]?[0-9a-fA-F]{8}[-]([0-9a-fA-F]{4}[-]){3}[0-9a-fA-F]{12}[\)|}]?|[{|\(]?[0-9a-fA-F]{8}([0-9a-fA-F]{4}){3}[0-9a-fA-F]{12}[\)|}]?$

For C# code, I’ll stick with TryParse(). The RegEx version, I’ll save for Javascript.  If you wanted to validate GUID text entry in a browser, the same expression can be used.

For the record, having the user enter in GUID values is a mind boggling UX failure. In this case, this is for an admin tool where the admin user would be copying and pasting in the GUID value from an email.

In case dotnetfiddler falls down, the source code is available on Github Gist.

Getty Images now providing a huge selection of images free for non-commercial use

Getty Images is how made available a large selection of images from their gallery free for non-commercial use in social media. For free. Which is pretty cool. There are times when you want to add an image to illustrate a point and a screen shot isn’t always applicable. And you may not have an image that you own that fits the theme.

It’s pretty simple to use. You just browse or search the Getty Catalog until you find an image that you want to use. If you hold hover your mouse over the image, you’ll see a pop-up window with additional details for that image. If that images has a link button, “</>”, then it’s available for linking on your blog or web site.

Getty Image pop-up

When you click the embed button, a new window will popup.  This window will have the HTML code needed to display the image.  It’s wrapped inside of an <iframe> and will have all of the branding required for the acceptable usage of the image.

The HTML code required to display the image

As long as you are OK with the Getty branding at the bottom of the image, you now have a high quality source of free to use images for your blog.  Just paste that <iframe> block into your blog post and you are set to go.  Sometimes there is such a thing as a free lunch.

Today I remembered that every URL is an URI, but not vice versa

I was writing some validation code for a desktop app and there are some fields require web page URLs.  My first thought was to a regular expression to validate the input, then this quote came to mind.

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Jamie Zawinski

Regular expressions can solve many problems, but if there is a method in the .Net Framework that will solve the problem, I’ll use that first.

I started off using the IsWellFormUriString method from the Uri class.

I created a string extension method called ValidateUrl() and tried it with the following examples

  1. http://foo.com
  2. htp.foo.com
  3. ftp://foo.com
  4. what://foo.com

You can see the results of those examples with the following .Net Fiddle:

The first is valid and we expected that. The 2nd is not valid and is expected. The 3rd is valid and I didn’t account for that in the code. The last one, what://foo.com, that was unexpected. That is obviously not a valid URL. Or at least not valid for the purposes of my app.

But I wasn’t check to see if the URL was valid, I was checking to see if the URI was valid. A URI consists of a scheme name (“http”, “ftp”, “mail”, etc), followed by the “:” character, and then by the path the resource. The Uri.IsWellFormedUriString method does not validate the scheme name, it’s just validating that the resource was assembled correctly.

Validating for a web page URL would be on me. I can use Uri.IsWellFormedUriString, but I would need to add an additional check to verify that the URI started with http:// or https://. With that modification, the example from above becomes this Fiddle:

And with the same inputs, I now get the results that I need. The one that starts with “ftp:” is a valid URL, I’m returning it as invalid because that meets the requirements of my app. Your mileage may vary.

While testing the code, I came across an example of a valid URL that IsWellFormedUriString will return as invalid. It fails on URLs with embedded unicode characters. Like this one:

http://foo.com/unicode_✪_

This apparently broke in .NET 4.5 and was logged as bug. And according to the notes attached to that bug, it’s not going to be fixed any time soon. For this project, I know that the URLs that could be entered in by the user would not have unicode characters, so I don’t have to worry about that.

If I did have to handle unicode characters, that’s when I would use a regular expression. Someone already went in search of the perfect URL validation regex and found one from Diego Perini that handles all sorts of use cases.

Weighing in at 502 characters, this handles just about any valid URL.

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS

In that format, that regex is what you would call write-once code. Diego posted a commented version of it as a gist, you can read that without your eyes bleeding.

A work in progress

%d bloggers like this: