Category Archives: .NET

All things Microsoft .NET related

Amplify.js & ASP.NET Web API: Getting the error message

I’m still learning my way around ASP.NET Web API and have started using Amplify.js in my web apps to consume my web services. I originally learned about Amplify.js from John Papa’s excellent Pluralsight course, “Single Page Apps with HTML5, Web API, Knockout and jQuery”.

Today I noticed that when a server-side error occurs, I was not getting the JSON response that contains the error information in my client-side Amplify error() function (see “Exception Handling in ASP.NET Web API” for an explanation). Taking a look at the Amplify source code revealed that, “out of the box”, Amplify always sends null to the error callback function’s data parameter.

To override this behavior, I created a custom decoder that would use the XHR responseText to feed the error callback data parameter, like so:

amplify.request.decoders.mydecoder =
        function (data, status, xhr, success, error) {
            if (status === "success") {
                success(data, status);
            } else if (status === "fail" || status === "error") {
                try {
                    error(JSON.parse(xhr.responseText), status);
                } catch(er) {
                    error(xhr.responseText, status);
                }
            }
        };

Now I’m able to read the Message property and any other information returned from Web API when a server-side exception is thrown.

Entity Framework DbContext and mapping decimal properties with more than 2 digits of scale

Posting this mostly as a reminder to myself that when more than two decimal places of scale (i.e. to the right of the decimal point) is needed when mapping an EF entity property, you must specify the property’s precision in your DbContext’s OnModelCreating event like so:

public class MyDbContext : DbContext, IDbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      modelBuilder.Entity<OutYearPoolRate>().Property(r => r.Rate).HasPrecision(14, 8);
      base.OnModelCreating(modelBuilder);
   }
...

Failure to do so causes EF to truncate the values to 2 decimal places when updating the database.

ASP.NET Wizard Control Oddness

Haven’t posted anything in over a year, but decided to break the silence to write about something that caused me to waste more time than it should have. Hopefully, it will save someone else (or future me) from wasting more time on it.

I’m developing an ASP.NET site using the Wizard control and have code that saves the user’s progress in a database. The idea here is that the user can return to the site and pick up where they left off. Simple enough, but I got caught in what seemed like a never ending debugging session when I couldn’t figure out why the "Previous" button didn’t work when I came back into the site to resume a previous session. The wizard simply would not step backwards when starting on any step in the middle. To make a long story short, turns out the genius at Microsoft who implemented this control decided to make the "previous" button work like the browser "back" button, i.e. clicking previous steps you back in your "history" since you starting using the wizard. In this case, there is no "history" when starting in the middle, so the button does nothing! Not at all intuitive.

I found this discussion enlightening: http://forums.asp.net/p/973337/1235981.aspx

The workaround is simple. Handle the PrevousButtonClick event and decrement the ActiveStepIndex property:

protected void MainWizard_PreviousButtonClick(object sender, WizardNavigationEventArgs e) { MainWizard.ActiveStepIndex--; }

Hope this helps.

JScript.NET

From the things I didn’t know department comes JScript.NET.  What is JScript.NET?  In a nutshell, it’s a .NET version of JScript, i.e. a .NET version of JavaScript!  Why should you care about JScript.NET?  Well, here’s a scenario I had recently:

The company I work for uses Nagios to monitor it’s mission critical systems.  One common use is to simulate a user logging into a web application by POSTing credentials to a login form and checking for specific strings in the response.  This usually gives you an end-to-end check that all systems (web server, database server, etc.) related to the app are functioning.

I was asked to investigate how we could monitor one app in particular that couldn’t be checked with the simple tools included with Nagios.  This application was encrypting the user’s password two different ways using JavaScript before submitting it to the server.  To make matters worse, it was using a random key generated by the server each time the login page was opened.

Since I’m primarily a .NET developer and have very little experience with *NIX systems and PERL (most Nagios plug-ins are written in PERL), my approach was to build a simple web page that Nagios could check that would act as a proxy to this particular app.  This still left me with the problem of how to simulate what the browser was doing in JavaScript. 

One solution would be to translate the JavaScript to C#.  Another would be to try to host the Windows scripting engine in my .NET app and invoke the existing scripts as-is.  Or maybe I could write a "classic" ASP page using JScript.  None of these options appealed to me much, so I consulted Google.

I eventually came across JScript.NET.  I knew about J# (Microsoft’s attempt to lure Java programmers to the .NET platform), but what the heck is JScript.NET?  When I create a new project in Visual Studio, there’s no JScript options…

Hidden away in the .NET SDK is jsc.exe, the JScript.NET compiler.  So, now it was just a matter of taking the JavaScript code I wanted to use from C# and compiling it using jsc /t:library <source file> and I had a DLL I could reference and call.  A few minor tweaks were needed, like wrapping stuff in a class, but overall it was pretty painless and it worked!

Not sure if I’ll ever need to do something like this again, but it’s nice to know JScript.NET is there…

Crash Course in VSTO

I’ve inherited yet another project at work. This latest one includes a series of reports all done in Excel with VBA macros. The code for these macros is almost unmaintainable, so I’m trying get these rewritten using Visual Studio Tools for Office (VSTO). This is my first experience with VSTO and right now I’m in the “proof of concept” stage, struggling with deploying a test case using ClickOnce.

So far, here’s what I’ve learned:

  • Visual Studio 2008 ships with VSTO “in the box”
  • There are several options, depending on if you want to target Office 2003, 2007, .NET 2.0, 3.0, 3.5
  • You can’t target 2007 specifically and use anything but .NET 3.5
  • Only .NET 3.5 supports deploying VSTO solutions using ClickOnce

As I write this, I’m testing using IIS 7 running under Vista (yes, I’m a glutton for punishment) for my publishing location and have Windows XP running under Virtual PC with Office 2003 for testing the deployment. So far I’ve had several attempts at getting the bootstrap to download and install .NET 3.5 and the VSTO runtime. To work around a couple of the problems I had to manually add application/octet-stream MIME types to IIS for the .MSP and .MSU files that are part of the .NET Framework redistributable.

Everything is downloading now, but the install failed with a “Status of package ‘.NET Framework 3.5’ after install is ‘InstallFailed'” in the installer log file. I’ll update this post once I get that figured out…

UPDATE: Rebooted the VPC and now the .NET Framework installed. Gotta love it.

UPDATE: Needed another MIME type set up for .vsto files: http://msdn2.microsoft.com/en-us/library/bb608629(VS.90).aspx

UPDATE: And after all of that, it doesn’t work with Excel 2003. I get the error: The common language runtime could not be loaded by Excel file path. Contact your administrator for further assistance. I thought maybe if I used the Office 2007 VSTO project template, but saved the Workbook using the 97-2003 compatible format I could open it in Excel 2007 or 2003. No such luck. Looks like if you want to use VSTO + ClickOnce, you have to target Office 2007 users…

Got Athlon? No Silverlight For You!

Bummer. We’ve got an older 1.4Ghz Athlon PC here in our family room and Silverlight does not run on this chip, according to this thread: http://silverlight.net/forums/t/5590.aspx

Someone should update the Silverlight system requirements, as there’s no mention of this. That page says all you need is a “X86 or x64 500-megahertz (MHz) or higher processor with 128-megabytes (MB) of RAM”. Apparently, Silverlight needs a processor that supports SSE instructions, witch the original Athlon chip lacks. AMD added that feature in the Athlon XP.

Tafiti – Microsoft Live Search with Silverlight

This is pretty cool: http://www.tafiti.com/

I think my favorite feature is the newspaper layout for the news results. This might actually get me to use Live search once in while instead of Google, although I’m not so sure about the usability. The font size for the web results seems a bit small and I’m not so sure about the two-column layout (but this might be because I’m so used to seeing the summary below each result). The tree view seems to be there purely as eye candy, I can’t how this is usable at all…

Another Workaround for Expired ClickOnce Code Signing Certificates

Daniel Margetic has posted a workaround for updating a ClickOnce application that has been deployed with an expired Authenticode certificate.  I wrote about this problem back in January and came up with a kludge that involved automatically uninstalling the app and reinstalling from a new location.

Daniel’s solution uses a newer version of the code signing tool, included in the Windows Server R2 SDK, that allows you to sign with two different keys – one for Authenticode and one for the manifest’s “strong name”.  Basically, you continue to sign the manifest using the key from the expired cert and generate the Authenticode signature using the renewed certificate.

Details at Daniel’s blog:
http://blogs.msdn.com/danielma/archive/2007/03/19/clickonce-and-expired-certificates.aspx

ASP.NET Version Mismatch

A colleague was modifying an in-house ASP.NET 1.1 application this past week to use a corporate authentication service. This service works via HTTP redirects from the application to the service and then back to the application, once the user is authenticated. A “ticket” is returned to the calling application, where it is validated and stored in a cookie using ASP.NET Forms Authentication.

My colleague modified the web.config file of his app to use Forms Authentication (it had previously used Windows authentication) and setup a login page that redirected to the corporate authentication service. Everything worked fine, until the next day when he reopened his Visual Studio 2003 solution for this app and was greeted by an “ASP.NET Version Mismatch” dialog that claimed his web server was configured for ASP.NET 1.0. The choices where to cancel opening the web project or make the application “1.0” compliant (whatever that means).

ASP.NET Version Mismatch

He then sought out my assistance and I suggested we use aspnet_regiss.exe to re-register ASP.NET 1.1 with his web server (thinking that the IIS configuration somehow got mangled). That didn’t help. We then turned to Google for answers and after following several wrong turns, each providing clues as to what the real problem was, came up with a solution.

This MS knowledge base article provides some clues as to what is really going on: http://support.microsoft.com/kb/827074

Although the suggested workaround didn’t work, the important piece of information is the reference to the Get_aspx_ver.aspx ASP.NET page. See, Visual Studio 2003 does a GET on this non-existent page using your web project’s virtual folder. You can verify this by examining the IIS logs. Since my colleague had enabled Forms Authentication, this request got redirected to the login page which in turn REDIRECTED VISUAL STUDIO TO A SITE THAT WAS NOT EVEN RUNNING ASP.NET (the corporate authentication server). Visual Studio checks for the ASP.NET version in the HTTP response headers and displays the dialog above when the version doesn’t match the expected ASP.NET 1.1 version.

The fix is simple. Add the following to the web.config file to allow anonymous users (in this case, Visual Studio) to access get_aspx_ver.aspx:

<location path=”get_aspx_ver.aspx”>
   <system.web>
     <authorization>
       <allow users=”?”/>
     </authorization>
   </system.web>
</location>

(this goes after the system.web section)