Tuesday, November 22, 2011

Troubleshooting Relative URI’s in Silverlight Projects

My Visual Studio Solution contains a minimum of a project for the Silverlight application and a project for the web page that hosts the Silverlight application. The Silverlight application reads and rights files to the local file system.

The solution is structured similar to this:

mySolution (has a minimum of the following two projects)

  • MyApplication.Web - the project that hosts the Silverlight xap file (could be a simple index.html page and Silverlight.js javascript page)
  • MyApplication - the Silverlight application project

When debugging in Visual Studio, the files that the Silverlight application is trying to read from are not necessarily available to the application depending on how you structure the application and which project you put the data files into initially.

While under development, intuition may lead you to believe that if it is the Silverlight application that is actually reading the files, the Data folder should be placed in the Silverlight application project root, not the web project. That would be incorrect.

Example 1

new Uri("/Data/ReadThisFile.xml", UriKind.Relative)

UriKind.Relative with a leading slash (/) in front of the Data folder is relative to the page that is hosting the XAP file. In my solution this is the project root of the web application, not the Silverlight project. The data file would be located at f:\mySolution\myApplication.Web\Data\ReadThisFile.xml


Example 2



new Uri("Data/ReadThisFile.xml", UriKind.Relative)
Without the leading slash in front of the Data folder as in this example, the file is expected to be relative to the Silverlight xap file. In my solution the xap file is in the default location, the ClientBin folder, which is a sub folder of the project root of the web application. The data file in this case would be located at f:\mySolution\myApplication.Web\ClientBin\Data\ReadThisFile.xml


Troubleshooting with Process Monitor


If you are getting File not found exceptions, the file isn’t where your application thought it was supposed to be. A relatively easy way to find out where the application is looking for the file is to use SysInternals Process Monitor.


Once you install and run the Process Monitor, you can set the filters to narrow down the captured events to locate the path to the file. The primary filters I used were “Result is not SUCCESS” and “Path contains ReadThisFile.xml”


 image


The filtered results would look similar to the following, if the the application throws a File not found type of error. (click to enlarge)


image

Monday, November 21, 2011

Could not load file or assembly System.IdentityModel

I added functionality to a Silverlight application I created several months ago and when I attempted to run it in debug mode, I received this error:

Could not load file or assembly 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.

I found very little evidence of why I was getting this error now. My search results did not turn up much useful information either. I did find this link on Stack Overflow, so on a whim I revised the web.config of the web project that hosts the Silverlight application to a add a clear statement to the assemblies node.

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" >
        <assemblies>
          <clear/>
        </assemblies>
      </compilation>
    </system.web>
</configuration>

After making that change, the assembly loads without errors. This was on my development workstation. The application did not throw any errors on the production server after publishing it without the clear statement in the web.config.

Wednesday, October 26, 2011

10 Reasons to Join a PASS or .Net User Group

user groupI am a member and leader at multiple chapters of technology-based international professional associations, like PASS (Professional Association for SQL Server) and INETA. Through that affiliation, I have experienced many, many benefits that such a small percentage of our industry takes advantage of.

  1. Great people – Attendees, speakers, organizers, volunteers, sponsors, and venue hosts. Attend regularly and I promise you will make life long friends.
  2. A place to talk shop with peers, learn about other organizations and practices, scope out job opportunities, help others with their challenges, and mentor people new to the field.
  3. Great content – free training, new technology previews, and deep dives into specific topics.
  4. Access to experts – speakers almost always provide their contact info and give you permission to ask questions outside of the presentation. Get help on your challenges from other attendees during the social networking time. Sometimes you even get to meet Industry celebrities and national conference presenters, such as Brent Ozar, Brad McGehee, and Scott Guthrie.
  5. Food and beverage
  6. Free swag – books, software (Development software, Operating Systems, 3rd party tools, Xbox games, and more), hardware (keyboards, mice, web cams, etc.), training vouchers, discount coupons, quirky and unusual items (such as Bucky Balls),  travel mugs, tote bags, back packs, and the list goes on.
  7. News and announcements about other events and happenings in the industry – training conferences like the PASS Summit and SQL Cruise, all day training opportunities, such as Day of .Net, Codemash, SQL Saturday, virtual training events, contests, free eBooks promotions, Job opportunities.
  8. Save money travelling to regional training or events by carpooling with your fellow user group friends.
  9. Opportunities to present – show off your own proficiency in your craft, get experience to prepare you to speak on regional or national level, establish credibility as a teacher/communicator.
  10. Opportunities to be a board member or volunteer to hone your leadership and logistical skills enhances your career marketability. Also, volunteering or leading a local chapter or regional event is great way to prepare you to become a board member on a national scale, if that is of interest to you.

Really there are few reasons not to attend, join, volunteer, or lead a professional organization. If you’re interested in professional organizations in general, read my popular post about 10 reasons to join a professional association.

What have I missed?

Thursday, October 13, 2011

SQL Server Compatibility Level Testing

upgrading technologyI stumbled on interesting version compatibility issues while working with a database in SQL Server 2008R2. The database was originally developed in SQL Server 2000. It was upgraded to MSSQL 2008R2 as a part of a virtualization initiative, however, the Compatibility Level was still set to 80 (MSSQL 2000).

After seeing columns of type VARCHAR(MAX), it got me wondering about compatibility issues since there was no VARCHAR(MAX) in 2000.

Anomaly #1

Doing some research I found this post with a script for Testing all procs before upgrading to Compatibility Level 90. I ran it on the database (while still set to Compatibility Level 80) and it reported a stored procedure that had a syntax error that was not caught by the syntax checker in MSSQL 2000, 2005, or 2008R2. The SQL is below:

SELECT     ChangeLogID
    , CourseID
    , RecordID
    , RecordTable
    , ChangeType
    , ModifiedDateTime
    , ModifiedByEmpNo
    , CASE RecordTable 
        WHEN 'Course' THEN
        ( SELECT CourseName 
          FROM Course 
          WHERE CourseID = cl.CourseID)
        WHEN 'Lesson' THEN
        ( SELECT LessonName 
          FROM Lesson 
          WHERE LessonID = cl.LessonID)
         WHEN 'Content' THEN
        ( SELECT ContentName 
          FROM Content 
          WHERE ContentID = cl.ContentID)
        ELSE "None"
    END AS RecordName
FROM         ChangeLog cl
WHERE     (CourseID = @CourseID)

The error message was: Invalid column name 'None'. Note the quotation marks around “None” after the ELSE. Strangely, the stored procedure executes without error. It only detects the syntax error on CREATE, not when I ALTER the stored procedure.


Anomaly #2


Using the same database described above, the compatibility error detection script I used (while still having a Compatibility Level of 80) did not detect the error:


Msg 8127, Level 16, State 1, Procedure GetNextLessonForLessonNo, Line 49
Column "Lesson.LessonNo" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.


The SQL generating this error is:


SELECT     TOP 1 MIN(L.LessonNo) AS LessonNo
    , L.LessonID
    , L.CourseID
    , L.LessonName
    , L.LessonDesc
    , COUNT(Content.ContentID) AS NContentPages
FROM     Course C 
         INNER JOIN Lesson L 
            ON C.CourseID = L.CourseID
         LEFT OUTER JOIN Content 
            ON L.LessonID = Content.LessonID
WHERE     (L.LessonNo > @LessonNo 
       AND L.CourseID = @CourseID)
GROUP BY L.LessonID
    , L.CourseID
    , L.LessonName
    , L.LessonDesc
ORDER BY L.LessonNo


This error is not detected in SSMS (in a query window, or by running the detection script) until the Database Compatibility Level is changed from 80 (MSSQL 2000) to 100 (MSSQL 2008). The issue can be resolved in SQL Server 2008 by adding L.LessonNo to the GROUP BY clause.


photo credit: somegeekintn / CC BY 2.0 

Tuesday, September 27, 2011

Image button link options in ASP.Net MVC3

There are several ways to skin this cat, but below are a couple options for using an image, in lieu of text, as a link to content. There are other overloads for the Url.Action and the Html.ActionLink, but in this example I was linking to a different controller passing in the integer id of the item to display a list of child records. The "STEPS” image is displayed if the parent record has child records.

image

Url.Action method

<a href='@Url.Action("ActionName", "ControllerName", new {Id = item.ID}) '><img src='@Url.Content("~/Content/Images/buttonimage.gif") ' alt="View Detail" border="0"  /></a> 

Html.ActionLink method



@Html.ActionLink(" ", "ActionName", "ControllerName", new { Id = item.ID }, new { @class = "steps-button", alt = "View Detail", title = "View Detail" })

Note that the first parameter in the action link is a space (because I didn’t want any text to show over the button background image) and the first argument cannot be null or empty.


In the site CSS layout I added the following steps-button class that adds the image to the link as a background image.



a.steps-button      
{
    background: url(../Content/Images/buttonimage.gif) no-repeat top left; 
    width: 14px;
    height: 44px; 
    display: block;
}

Wednesday, September 14, 2011

Using jQuery datepicker with MVC3 textboxes

Pick a dateThis post addresses two issues:

  1. Using the built-in ASP.NET Development Server vs. IIS to render the datepicker. If you are using IIS, skip to the second section.
  2. Dependencies necessary to get the jquery ui datepicker to work in an MVC3 project.

ASP.NET Development Server

I repeatedly have issues with AJAX controls (like the ModalPopup control) rendering with the correct styles using the ASP.NET Development Server vs. IIS. The jquery datepicker is no exception, but this time it surfaces as the following error “Microsoft JScript runtime error: Object doesn't support this property or method” in the jquery-1.5.1.min.js, which isn’t very helpful for troubleshooting.

image

On a hunch, I decided to configure the project as an application in IIS and access it via localhost/appname instead of the dynamically addressed port of the ASP.NET Development Server - giving me a more meaningful error to troubleshoot.

jQuery UI dependencies

Using the IIS served application, I received the tiny warning triangle in the lower left corner of IE that indicates a javascript error, “Message: Object doesn't support this property or method”. The offending line of code was $("#EstDateStarted").datepicker();.

My project was based on the standard Visual Studio 2010 MVC3 project template which included only the jquery-1.5.1.min.js in the _Layout.cshtml file using the Razor rendering engine. The .datepicker function is not located in that javascript file it is in the jquery-ui-1.8.11.min.js file. All I needed do to enable that functionality and resolve the error was to add the following reference to the head of the _Layout.cshtml file, which includes it on all the pages of the app:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript">

jquery ui datepicker

photo credit: augapfel / CC BY-SA 2.0

Thursday, July 28, 2011

New App Hub Features Still Need Work

LeanBites200The July 18 Marketplace updates look like they still need some tweaking. I updated one of my apps and set the publish status to “hide” after certification. After app certification approval, for  some reason, it showed an update to the app on my phone (doesn’t seem hidden to me). I updated the app to the new version, and the splash screen was updated, but the icons were not updated and the application just showed a “My Application” header at the top of the page with no app content at all.

I thought maybe that was the result of the “Hide” status. So I un-hid the app in the marketplace. It didn’t prompt another update so I uninstalled the app from my phone. When I searched in the marketplace for my app to reinstall, it could not be found.

In order to reinstall the app, I had to navigate to my Lean Bites website on my phone and click the Zune Marketplace deep link in the right column of the website. After following that procedure, the app installed and is working correctly again with the new updated version.

I hope Microsoft gets these issues worked out before the consumer frustration gets to a new high and it doesn’t make my app look like it’s the problem. With so much riding on the new Windows Phone platform, it is unfortunate to see them stumbling over issues that probably should have surfaced in beta testing.

Friday, July 22, 2011

EF “Code-First” Table Mappings for Existing Database

Table MapIf you are using the MvcScaffolding package to scaffold the tables from an existing database and it throws an exception on the following line of the index.cshtml page. (The exception would show up in a different location on other data access pages).

@foreach (var item in Model) {

If the exception is of type System.Data.EntityCommandExecutionException where the inner exception is something to the effect of “Invalid object name ‘dbo.Ranks” where the actual database table name is the singular form like dbo.Rank, you probably need to explicitly define the table schema mappings in the OnModelCreating event of the context class because the existing database table names don’t match the default Entity Framework Convention over Configuration settings.


namespace LPM.Models
{
    public class LPMContext : DbContext
    {
        public DbSet<LPM.Status> Status { get; set; }
        public DbSet<LPM.Rank> Ranks { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Rank>().ToTable("Rank");
        }
    }
}

If you use SQL Profiler to trace the T-SQL statement issued by the application, you can see it was attempting to retrieve data from the [dbo].[Ranks] table which doesn’t exist. In my database it is [dbo].[Rank].

SELECT
[Extent1].[ID] AS [ID],
[Extent1].[RankNo] AS [RankNo],
[Extent1].[RankDescription] AS [RankDescription]
FROM [dbo].[Ranks] AS [Extent1]


This stumped me initially because the first table I used as a test was the “Status” table which by convention has the same name in the singular and plural form. So no exceptions where thrown and I could list, insert, update, and delete the records. After I updated the model from the database and added the Rank table, exceptions started flying until I added the modelBuilder.Entity<Rank>().ToTable(“Rank”) line in the OnModelCreating event.

Scott Guthrie’s Entity Framework 4 “Code-First”: Custom Database Schema Mapping has additional examples with more complex mapping scenarios.


photo credit: aaron13251 / CC BY 2.0

Thursday, July 21, 2011

MvcScaffolding uses SQL Express by Default

Where's WaldoThe fact that the MvcScaffolding package uses SQL Express by default can be both good and deceiving at the same time.

Using an Existing Database (not Code-First)

I used the package on a MVC3 project to scaffold the repository models and controllers for an existing SQL Server Standard database (not SQL Express) that had an existing Ado.Net Entity Framework model. The EF connection string obviously pointed to the existing database. However when running the application, the Index pages didn’t list any of the existing data from my database.

If this looks like the same problem you are having, feel free to skip to the bottom for the solution (convention over configuration).

Where’s the data?

I could add records, but they didn’t show up in the existing database. There was no Express database .mdf file in the application’s App_Data folder. There were no additional  connection strings (other than the EF connection to the existing database) in the web.config files or any of the dbcontext class files. I profiled the existing database with SQL Profiler and the existing database was completely untouched. I even added a <remove name=”LPMEntities” /> line before the EF connection string to make sure any default connection from the server root or machine.config was taken out of the inheritance tree (similar to what you would do for the aspnetdb membership database if you are using a full SQL Server instance).

The new data was being stored somewhere, but where? In a newly created SQL Express database.

How do I See the Data?

Open your SQL Server Management Studio (SSMS) or the version of SSMS for SQL Express. In the Object Explorer window, click Connect. Use .\sqlexpress as the server to connect to using Windows Authentication and voila the new mysterious “hidden” database.

SqlExpress MvcScaffolding package generated database

I hope this helps to clarify for other people attempting to use the MvcScaffoling in a Database-First scenario.

The Solution – Understand the Convention over Configuration

It took me a while to find a small subtle, yet crucial, detail in Scott Guthrie’s Using EF “Code First” with an Existing Database.

The following note is stated at the end of Step 5 – Configuring our Database Connection String:

EF “code first” uses a convention where context classes by default look for a connection-string that has the same name as the context class.  Because our context class is called “Northwind” it by default looks for a “Northwind” connection-string to use.  Above our Northwind connection-string is configured to use a local SQL Express database.  You can alternatively point it at a remote SQL Server.

In my case the Entity Framework connection string in the web.config was named “LPMEntities”. The class implementing the DbContext is named LPMContext as shown below.

namespace LPM.Models
{
    public class LPMContext : DbContext
    {
        public DbSet<LPM.Type> Types { get; set; }
        additional stuff here...
    }
}

Since LPMEntities is not the context class name, the EF generates a local SQL Express database.


I just added a connection string to the web.config with a name of LPMContext (same name as the context class) and my MVC forms are populated from the existing database.


Victory!



photo credit: Si1very / CC BY-SA 2.0

Friday, July 15, 2011

Error using MvcScaffolding with EF4.0

scaffoldingIf you are just starting out with the MvcScaffolding Nuget package to scaffold your basic CRUD operations on an MVC3 project, you should know that it requires EF 4.1 to run correctly without the following error.

The type 'LPM.Project' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject

If you already ran the scaffolding via the Package Manager Console using syntax similar to the following, PM>scaffold controller <table> –Repository –Force, to resolve the error, I needed to:

  1. Delete the scaffolded controller files and view files from the project.
  2. Install the Entity Framework 4.1
  3. Re-Generate the Database From Model (assuming that is how you created the Entities to begin with)
  4. Right click on the .edmx Design surface, click Add Code Generation Item.
  5. Click the Code link in the Installed Templates tree. Select ADO.Net DbContext Generator. Name the code generation template, it ends with a .tt extension.
  6. Rebuild the project.
  7. Re-scaffold the tables.
  8. Run the project

Steps 4 & 5 above were the key to getting it to work after installing the Entity Framework 4.1 and with all my combinations of re-scaffolding, re-generating the model, re-creating the model, etc. That important bit of information came from MVC 3 Scaffolding issue with Entity Framework.

If you look at the Model.designer.cs (or .vb) code prior to adding the ADO.Net DbContext Generator, you will see that the Model entities do inherit from the EntityObject (which is noted in the error message as a potential cause of the exception). Adding the ADO.Net DbContext Generator disables the default code generation and inherits from the DbContext instead.

more information:

Friday, July 8, 2011

Physical to Virtual using SysInternals Disk2VHD

Virtual Prehistoric EraThe hard drive controller was regularly failing on my source control server. What to do? The server was due for an upgrade soon as its hardware was more or less obsolete and the performance was less than satisfactory. While the controller was still mostly working, I used SysInternals Disk2VHD to create a virtual copy of the physical server. In the interim while waiting on the new Hyper-V server to permanently place it on, I can temporarily run the server in VirtualPC 2007 and with three times more RAM than was available on the physical server.

The process was simple, fast, and seamless. I just had to re-activate the OS after the conversion. Just make sure you activate it before the expiration date which I believe was only 3 days on my copy or it will brick your ability to manage the server from the terminal.

While waiting for copying and converting processes to finish I ran across a few related posts that I thought I might want to reference in the future.

Wednesday, July 6, 2011

Database Primary Key Naming Conventions

Train couplingThis post specifically deals with the two naming conventions of a primary key for example “Id” or “<tablename>Id".

Using the convention including the tablename prepended to “Id” makes creating and reading SQL query joins more intuitively readable as in:

SELECT a.AuthorId
    , a.AuthorName
    , b.BookId
    , b.BookName 
FROM Author a
   INNER JOIN Book b 
   ON b.AuthorId = a.AuthorId

Versus the alternative using a standard key name, such as “Id" for all tables, as in the following:



SELECT a.Id AS AuthorId
    , a.AuthorName
    , b.Id AS BookId
    , b.BookName 
FROM Author a
   INNER JOIN Book b 
   ON b.AuthorId = a.Id

However it adds additional abstraction/mapping complexity when using a generic Repository pattern* that uses a standard primary key property name for the Repository base classes and interfaces.


*The design is possibly more correctly labeled as a DAO pattern depending on the specific implementation.


photo courtesy: amboo who? / CC BY-SA 2.0

Wednesday, June 8, 2011

Circumventing the uriMappings in Silverlight

Redirection chaosI created a Silverlight application with the Silverlight Navigation project template that needed to open a link to a PDF file located in a subfolder of the host web application directory. The  project has a convenient uriMapping process defined in the MainPage.xaml XAML to provide search engine friendly links to the various Silverlight pages. It is located in the Windows.System.Navigation namespace. It looks something like this:

<uriMapper:UriMapper>
   <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
   <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
</uriMapper:UriMapper>

 

I needed to link to an absolute Url, not a uri relative to the Silverlight app, like http://www.deanwillson.com/downloads/Continuous-Improvement-professional-Org-1st-Edition.pdf, but if the uriMapper catches that link it attempts to re-map it to a resource that doesn’t exist which generates the following error:


“Content for the URI cannot be loaded. The URI may be Invalid”


Solution


In order to accomplish linking outside of the defined uriMappings, I added the link in the XAML of the HyperlinkButton NavigateUri.



<HyperlinkButton Name="lnkReport" NavigateUri="http://www.deanwillson.com/downloads/Continuous-Improvement-professional-Org-1st-Edition.pdf" Content="Click here to open your document" TargetName="_blank" Margin="116,11,184,10" Width="200" />

All this probably looks pretty obvious, but it started with me trying to open the pdf report using code-behind in the clicked event handler for the button, which kept throwing the Invalid Uri exception. I even added a special uriMapping that mapped to the same link, which also did not work.


photo credit: eirikref / CC BY 2.0

Wednesday, May 25, 2011

Creating a Windows Phone 7 app using WCF, and SQL Azure

Last night I gave a presentation with demos for fwPASS creating a Windows 7 app displaying a list of gymnasts from a SQL Azure database using WCF (Windows Communication Foundation). The WCF service used the Entity Framework and the .Net Membership provider.

The application was surprisingly easy to create despite the fact that were a lot of moving pieces with integration between all the different components.

The presentation covered the following tools:

 

All that in 70 minutes. Yes, I talk fast. This was a first time presentation. Below is the demo script I used:

Marketplace

1. Preview App Hub http://create.msdn.com

· Show app details text, iconography

Database

1. SSMS – show local ChalkChimp database

· Show script for creating additional users?

2. http://windows.azure.com SQL management interface

· No query designer

3. SQL Azure Migration tool

· Scripts out db

· Shows unsupported features

· deploys

4. Azure limitations in SSMS

· No query designer

· Admin account (other users don’t have access to the master database)

WCF

1. Create new project WCF Application

· Highlight Framework version 3.5

· Change binding to basicHTTPBinding

2. New Item à ADO.Net Entity

· Azure connection

3. Switch to finished project

4. Modify Iservice.cs, modify Service.cs implementation

5. Show .Net membership bits in web.config

6. View in browser (copy url)

WP7 client

1. Open Visual Studio (another)

2. New Project à Windows Phone 7 application

3. New item à Phone portrait page

4. Add Service reference

· Show service methods

· Advanced show generate async methods

5. Switch to finished project

· Show xaml bindings

· Show async methods and completed event handlers

· switch device to emulator

6. Run it

Optional

· Show property pages and iconography

 

Friday, May 20, 2011

Download for WP7 Badges

imageSince I never seem to remember where to find the official "Download for Windows Phone 7" Badge and Logos, here is my reminder http://go.microsoft.com/fwlink/?LinkID=202116.