Enabling MVC5 intellisense in a ClassLibrary Project

This is still relevant, especially if you’re using RazorEngine. This also works for older versions of MVC as long as you have the version strings in the web.config set correctly.

thetoeb

I’ve been searching and searching the internet for someone, somewhere who might know how to enable correct IntelliSense for cshtml (MVC 5.0) in VS2013 when developing in a ClassLibrary type project.

This is the problem I was encountering:

Missing Intellisense

It’s all thanks to Mohammad Chehab, who was also stumped for a while (probably not as long as me), that I was able to find the solution.  His blog post explains that one must change the output path for the class library to bin/ (instead of bin/<release>)  for Intellisense  to work.

So now I can show you the steps for creating a ClassLibrary with cshtml (MVC5 Style):

  1. Create or open an existing class library project (if you open an existing one be sure to remove the MVC5 nuget package)
  2. Add the MVC (5.0) nuget package (right click project in solution explorer -> Manage NuGet Packages -> search for MVC and install “Microsoft…

View original post 463 more words

MVC 5, OWIN and Active Directory Authentication

Update: I’ve replaced the Task.Run calls with Task.FromResult to improve performance.

I’ve seen several questions on Stack Overflow asking how to do “forms authentication” using the new MVC OWIN stack. This is actually really easy, and requires only a small amount of customization of the starter template you get when you make a New Project using Individual Accounts. Keep in mind there will be a bit of work required if you want to get around some of the other components of the default project if you don’t want to require users sign up for a new account with a fake password. That is a project for another time.

First things first, this solution uses System.DirectoryServices.AccountManagement, so you will need to add that to your project.

Since we will need a PrincipalContext for the all of this, we can use a request-wide singleton produced by the pipeline for us by editing App_Start\Startup.Auth.cs.

using System.DirectoryServices.AccountManagement;
public void ConfigureAuth(IAppBuilder app) {
// This is the important part, this is how you will configure the PrincipalContext used throughout your app
app.CreatePerOwinContext(() => new PrincipalContext(ContextType.Domain));
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
}

That was easy, right? Next we need to tackle App_Start\IdentityConfig.cs, since that contains the ApplicationUserManager with a lot of methods you can override (thanks abstract!). Seriously, if you ever get a chance, check out the source or MSDN docs for it.

The key function we want to play with is CheckPasswordAsync. We will also need to modify the constructor so we have access to our PrincipalContext. Also, there is the “Create” method we need to tweak to accept our new constructor.

 public class ApplicationUserManager : UserManager<ApplicationUser>
    {
    private readonly PrincipalContext _context ;
    public ApplicationUserManager(IUserStore<ApplicationUser> store, PrincipalContext context)
      : base(store)
      {
        _context = context;
      }

    public override async Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
    {
        return await Task.FromResult(_context.ValidateCredentials(user.UserName, password, ContextOptions.Negotiate));
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()), context.Get<PrincipalContext>());
        //...SNIP...    
    }
}

That’s it! We simply override the password checking algorithm and checkthe password against AD. The reason for using ContextOptions.Negotiate is because it is required to get IIS Express to work correctly.

If you wanted to get extra fancy, you could add a property to the ApplicationUser to say whether or not that user should authenticate against AD. Then you could have a password checking method that falls back to the built-in authentication method, or even just fall back if AD authentication fails.

public override async Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
    if (user.IsADUser)
    {
        return await Task.FromResult(_context.ValidateCredentials(user.UserName, password, ContextOptions.Negotiate));
    }
    return await base.CheckPasswordAsync(user, password);
}

Happy Coding!

WordPress and Corporate SSL Certificates

After installing an update to WordPress I routinely see the following error when trying to use the “Update Network” function of my multisite installation:

Warning! Problem updating https://example.com/oneofmyMUsites. Your server may not be able to connect to sites running on it. Error message: SSL certificate problem: unable to get local issuer certificate

I run WordPress on an IIS server with correctly configured SSL certificates. Of course, PHP does not use the built-in Windows certificate store for validating Certificate Authorities. It instead maintains a separate bundle of CA certs in [wordpress install dir]\wp-includes\certificates\ca-bundle.crt. If you have a CA that is one one of the ones in that built-in bundle, you will encounter errors. You need to add you CA’s certificate to the bundle, which is unfortunately not a straightforward process.

  1. Open the Windows Certificates Manager
  2. Export your Root CA cert to a “Base-64 encoded X.509 (.CER)” format file
  3. Open that certificate in any text editor (notepad is fine) and copy the entire contents to your clipboard
  4. Open the previously-mentioned ca-bundle.crt file with an editor that understand linux-style line endings (Wordpad (be careful when saving), Notepad++, gVIM, etc). Notepad.exe will not work
  5. Paste the contents of the exported certificate to the bottom of the ca-bundle.crt file and save
  6. Run “Upgrade Network” again and watch as it works!

Keep in mind that you will have to re-apply this fix every time you update WordPress as the ca-bundle.crt file is overwritten during the upgrade process.

SQL to XML

Recently I had to build some XML files for importing into a Desire2Learn instance. They were nice enough to provide an XSD and a little bit of sample XML, but I didn’t want to actually build another console application to generate an XML file. I wanted to just export data straight from my SQL server. Enter FOR XML. There is a lot of documentation available for this feature, but a lot of it assumed that your column names matched very well with the shape of the XML you wanted to make. Thankfully FOR XML is actually quite powerful in letting you designate what shape your XML looks like.

For example, an XML file for importing might look like this:

<enterprise>
 <group recstatus="2">
   <sourcedid>
     <id>MATH_101</id>
   </sourcedid>
   <grouptype>
     <typevalue level="4">Course Template</typevalue>
   </grouptype>
   <description>
     <short>MATH_101</short>
     <long>Basic Math</long>
   </description>
   <relationship relation="1">
     <sourcedid>
       <id>MATH</id>
     </sourcedid>
     <label>A parent of MATH_101 is the Math Department</label>
   </relationship>
   <extension>
     <path>MATH/templates/MATH_101/</path>
   </extension>
 </group>
</enterprise>

You might have the data in your SQL database that could be queried simply like this:

SELECT Template, CourseDescription, Department
FROM Courses

To get from the “Normal” SQL to the XML output, you use FOR XML, and aliasing that looks like XPATH notation. Prefixing the last token in the alias turns that value into an attribute of the previously named tag.

SELECT '2' AS '@recstatus',
Template AS 'sourcedid/id',
'4' AS 'grouptype/typevalue/@level',
'Course Template' AS 'grouptype/typevalue',
Template AS 'description/short',
CourseDescription AS 'description/long',
1 AS 'relationship/@relation',
Department AS 'relationship/sourcedid/id',
'A parent of ' + Template + ' is the ' + Department + ' Department' AS 'relationship/label',
Department + '/templates/' + Template + '/' AS 'extension/path'
FROM Courses
FOR XML PATH('group'), ROOT('enterprise')

Easy!

jQuery 2.0 and NuGet

Recently jQuery 2.0 was released to the world. Yay! It has many breaking changes. Boo! But they are going to keep the 1.x branch updated for the foreseeable future. Yay! NuGet however, does not currently have UI to selectively update only using the 1.x branch of jQuery. Boo!

Enter NuGet version contraints. Simply open up your packages.config, and find the following line:

<package id="jQuery" version="1.9.1" targetFramework="net45" />

Your targetFramework attribute may be different, but that doesn’t matter. What you need to do is edit that line to add the allowedVersions parameter:

<package id="jQuery" version="1.9.1" targetFramework="net45" allowedVersions="[1,2)" />

This tells NuGet that you want to constrain the jQuery package to versions 1 <= x < 2. In fact, if you use Update-Package, you will get a friendly line in the package manager console that reads:

Applying constraint 'jQuery (≥ 1.0 && < 2.0)' defined in packages.config.

Yay! Hopefully the UI for NuGet is updated soon to better support parallel release branches.

Steam and OpenID and MVC

Steam actually offers some options to people who want to build applications and services using their data. One of these options is that they offer Steam as an OpenID provider. MVC 4 actually makes this very easy to consume. I only had to add the following to my AuthConfig.cs to enable it:

using DotNetOpenAuth.AspNet.Clients;
// ... SNIP ....
public static void RegisterAuth() {
    OAuthWebSecurity.RegisterClient(
        new OpenIdClient("Steam", "http://steamcommunity.com/openid"),
        "Steam", null
    )
// ... SNIP ...
}

Magic!

SignalR, easier than you think

I recently became aware of SignalR, an ASP.NET library that allows significantly easier implementation of real-time functionality with web applications. It really became apparent that it  is simple enough that I found an example of a real-time, shared To-Do application called KsigDo with an equally well-written blog post about it. However, when I tried to run and use this application, I found it simply didn’t work. It was written back when SignalR was only at version 0.6, and as happens often enough, the library changed enough that the code no longer worked with SignalR 1.0.1 (latest release at the time of this posting).

All of the changes are detailed in this blog post. If you previously dabbled in SignalR and now stuff isn’t working, you should look here. One of the major changes was that the SignalR nuGet package is now deprecated, and you have to use the Microsoft.AspNet.SignalR package instead. Also, you now have to explicitly call a method to register all of your hubs. You can see the fixed version up on GitHub.