May 2015

Basic ASP.NET 5 with Visual Studio 2015

The next version of ASP.NET is making a lot of progress and after watching Introducing ASP.NET 5 and Deep Dive into ASP.NET 5 from Build I decided to give it a try. The idea is to get the same Contacts application running in the new version of ASP. This will be a new solution so I am not trying to convert my existing solution and projects. With ASP.NET 5 Visual Studio is not the only option (Code is another option) for development, but Visual Studio is the route I am using for now.

The first step is to download and install Visual Studio 2015. Visual Studio 2015 has a ton of new stuff which I am not going to cover, but if you are interested check out this post from the Visual Studio Blog.

Next open Visual Studio and click File > New Project. This will show the new project dialog. At the top make sure you have .NET Framework 4.6 selected. Under Installed > Templates > Visual C# > Web select ASP.NET Web Application.aspNet5NewProjectNext the New ASP.NET Project dialog shows. Under the ASP.NET 5 Preview Temples select Web Site. This template will give the closest match to my existing Contact application.

aspNet5NewAspNetProjectAfter a minute or so the new project will be created and you will have something similar to the screenshot below.

aspNet5SolutionExplorer

For some reason I had a lot of problems getting the project to create properly. The project would get created but would be missing Models, Migrations and the views and controllers related to authentication. To get around this issue I cloned the ASP.NET Docs repo. The samples folder contains a project call WebApplication1 which contains all the needed files.

With WebApplication1 rename I was able to build and publish with no problems. I was going back to make screenshots for this post and the project creation actually worked. I am not sure if the act of publishing fixed something for Visual Studio, but now any Web Site temple project works fine.

At this point you will have a runnable application. I recommend checking out the Project_Readme.html that will be in your project as it has tons of information about all the stuff that has changed in ASP.NET 5. The videos linked at the top of the post are also a good place to start getting a handle on the new world that ASP.NET 5 is creating.

Other than the hiccups with project creation it is just as easy to get an application up and running in ASP.NET 5 as it was in ASP.NET 4. Compare a newly created project in ASP.NET 4 vs the one created here and you will notice tons of differences. Over the coming weeks my plan is to get this new application up to the point that the Contacts ASP.NET 4 application was at. From there the plan is to continue its development, and more importanly my learning, in ASP.NET 5.

Basic ASP.NET 5 with Visual Studio 2015 Read More »

More OAuth

Last week I covered using OAuth with Google for authentication. I thought I would try GitHub next only to find out Microsoft does not have a built in provider. After a little searching I came across OWIN OAuth Providers on GitHub. This project has a ton for providers ranging from BattleNet to Yammer.

To install run the following from the package manager console.

Install-Package Owin.Security.Providers

The rest of the process is very similar to last weeks post. I am going to walk through GitHub for this example but the others are very similar. The big difference for each provider is getting API access.

At the top of Statup.Auth.cs in the App_Start folder add the following.

using Owin.Security.Providers.GitHub;

And at the bottom of the ConfigureAuth function.

app.UseGitHubAuthentication(
    clientId: "Your Client ID",
    clientSecret:"Your Client Secret");

The next setup is to set up API access with GitHub. Login to GitHub and go to Developer applications.

oauthgithub

Click the Register new application button in the upper right of the page. On the registration page enter an application name, homepage URL and authorization callback URL. As last week the URL options will be need to be based on your project settings. After entering all your information click Register application.

oauthgithubRegisterApplication

Then next page will show your client ID and client secret which just need to be entered in Statup.Auth.cs. That is all there is to adding an additional OAuth provider and give your users even more authentication options.

oauthgithubLogin

Using OWIN OAuth Providers makes adding access other OAuth providers just as simple as the providers from Microsoft.

More OAuth Read More »

OAuth 2.0 with Google

After getting Basic Authentication and Authorization working I thought it would be neat to add login via Google which involves using OAuth 2.0. To get started I used NuGet to update all the OWIN related packages in my project. I ran across some people who had issues with older versions of OWIN so I recommend getting the latest to avoid any potential problems.

Some third parties require SSL when using their auth services so I decided to go a head and change my application to use SSL. I hit a couple of issues during this part of the process that I want to point out. The first is that when you change to SSL IIS Express defaults to using port 44300. I missed this the first try and it took a good bit of searching before I spotted the problem. Even after reverting all my changes I could not get my site to load without errors. A reboot got my reverted site working which I am assuming was a configuration issue with IIS Express that got reset on reboot.

To enable SSL select the project in Solution Explorer and press F4 to bring up the properties window (which has different options that the project properties you get if you right-click the project and click properties). Set the SSL Enabled property to true. Copy the SSL URL to use when updating the project.ContactsPropertiesSsl

Back in the Solution Explorer right-click on the project and click properties. On the Web tab under the Servers section paste the SSL URL from above into the Project Url and save.ContactsProjectPropertiesSslUrl

When running the first time after enabling SSL Visual Studio will prompt asking if you would like to trust the self-signed certificate that IIS Express generated. I chose to trust in order to avoid warnings from the browser.

OAuthTrustIISSSL

The last change need in the project is in the Statup.Auth.cs found in the App_Start folder. In the ConfigureAuth function add the following code using your own ClientId and ClientSecret.

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "Your Client ID",
    ClientSecret = "Your Client Secret"
});

If you don’t have a client ID and client secret head to the Google Developers Console. The first step in the process is to Click the Create Project button.

GoogleDevelopersConsoleEnter a project name and project ID. The refresh button on the project ID field will randomly generate project IDs in case the one you want is already in use. When finished click Create.
GoogleDevelopersConsoleNewProjectAfter the project creation process finishes click on the name of your project. Next click on the APIs & auth section and then click the Consent screen option. This set of options determines what the user sees when Google prompts a user for consent to use information from their Google account. The minimum needed is email address and product name. For a live application I would recommend filling out as much as possible to give the user the best experience. When done click Save.GoogleDevelopersConsoleAPIsAndAuthConsentScreenIn the same APIs & auth section click the APIs option. Search for Google+ API. Click the name Google+ API and on the next screen click Enable API.GoogleDevelopersConsoleAPIsAndAuthApisGooglePlusAgain in the APIs & auth section click on Credentials option and then in the OAuth section fo the page click Create new Client ID.
GoogleDevelopersConsoleAPIsAndAuthCredentialsThe following dialog will show. Select the appropriate Application type which is Web application for this example. For Authorized JavaScript origins use the value from Project Url listed above which in my case is https://localhost:44300/. For Authorized redirect URIs the base URI is the same but with an added level. For MVC 5 the redirect should be set to https://localhost:44300/signin-google changing the base URI as needed of course. Click Create Client ID and you will be returned to the previous page that will now list the Client ID and Client Secret needed in Statup.Auth.cs.
GoogleDevelopersConsoleAPIsAndAuthCredentialsCreateClientId

Now the login page will have a button for Google which will allow users to create an account and associate it with their Google account. After the association users will be able to login with their Google account.LoginWithGoogle

 

From this point adding Microsoft, Facebook or Twitter would just be a matter of adding the desired options to ConfigureAuth Startup.Auth.cs and going to each service and requesting API access.

OAuth 2.0 with Google Read More »

Basic Authentication and Authorization

When I created my contact application I did so with authentication set to Individual User Accounts as seen below.
vs2013NewAspProject

 

By choosing an authentication option during project creation Visual Studio takes care of a lot of the work involved with getting authentication and authorization up and running. For individual user accounts the default data store is SQL and Visual Studio sets up the need classes and data using entity framework to create a database and the needed tables to store authentication data. An AccountController and associated views are also created to handle user creation and login.

I am not going to cover everything that Visual Studio created automatically. I will be walking you through the other changes are needed to start using authentication and authorization with all the bits Visual Studio has provided.

The first step is to add AuthorizeAttribute to the FilterConfig which is found in the App_Start folder.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthorizeAttribute());
    }
}

Now that the AuthorizeAttribute is added to the applications filters any page that is requested by a user that is not authorized will be redirected to a login page to authenticate.

With authorization and authentication now in play any controller action that should allow anonymous usage will need to have the AllowAnonymous attribute added. The following example is using AllowAnonymous on the index action of the home controller.

public class HomeController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }
}

That is all there is to get the very basics going. This is a big subject, but Visual Studio and .Net do a lot of work to make getting basics up and going simple.

Basic Authentication and Authorization Read More »

Adding Paging

As the number of contacts grows it is overwhelming to see in single page. To address this I am going to add paging to the contact list and only show 10 contacts per page.

To generate a large set of realistic date I am using Mockaroo. They offers data in CSV, Tab-Delimited, SQL, Excel, JSON and DBUnit XML with up to 1,000 rows of data per generation for free. The data Mockaroo is way better than the crazy stuff I was coming up with. If you need more than 1,000 rows at a time they do have a pay option.

For paging I am going to take advantage of the PagedList.Mvc NuGet package. Using the package manager console it can be installed with the Install-Package PagedList.Mvc command as seen in the following screenshotPackageManager-PagedListMvc.

To start using PagedList.Mvc I need the following changes to ContactsController. Add new using for PagedList and the index action needs a page parameter. As part of this change I also refactored the contact query to the GetContacts function so the Index action is much less cluttered than before. The function is now shown below but I moved the distinct city query to the GetDistinctCities function.

        
public ActionResult Index(string filterCity, string filterSearch, int? page)
{
    ViewBag.filterCity = filterCity;
    ViewBag.filterSearch = filterSearch;
    ViewBag.city = new SelectList(GetDistinctCities());

    var contacts = GetContacts(filterCity, 
                               filterSearch)
                   .ToPagedList(page ?? 1, 10);

    if (Request.IsAjaxRequest())
    {
        return PartialView("_ContactList", contacts);
    }

    return View(contacts);
}

private IQueryable<Contact> GetContacts(string city, string search)
{
    var contacts = from c in db.Contacts
                   select c;

    if (!string.IsNullOrWhiteSpace(search))
    {
        contacts = contacts.Where(c => c.Name.Contains(search));
    }

    if (!string.IsNullOrWhiteSpace(city))
    {
        contacts = contacts.Where(c => c.City == city);
    }
     return contacts.OrderBy(c => c.Name);
}

Notice that I am now saving the parameter values of the city and search filters to the ViewBag in the index action which will be used when changing pages when a filter is in play.

In GetContacts I had to add an order by statement to the contacts being returned. This is to make sure the list is always in the same order. It will also be a good spot to add different ordering options in the future.

The last change in the Index action was to take the return value from GetContacts and call ToPagedList on it. This function takes a page number and number of items per page and returns a paged list as the name implies. In my case if page is null I am using page 1 and each page will contain 10 items.

In both Index.cshtml and the partial view _ContactList.cshtml the models need to be changed to PagedList.IPagedList. In addition @Html.DisplayNameFor also needs to be changed from model.Name to model.FirstOrDefault().Name. The last step is to add the paged list control to the bottom of the view. Here is the code from the contact list partial view.

@using PagedList.Mvc
@model PagedList.IPagedList<Contacts.Models.Contact>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().State)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().ZipCode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstOrDefault().Country)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.State)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ZipCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>

@Html.PagedListPager(Model,
                     page => Url.Action("Index",
                                        "Contacts",
                                        new { ViewBag.filterCity,
                                              ViewBag.filterSearch,
                                              page }),
                     PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
                          new AjaxOptions
                          {
                              HttpMethod = "GET",
                              UpdateTargetId = "contactList"
                          }))

The Url.Action on the PagedListPager is the function that will be called when the user want to changes pages. Index is the action that will be called, Contacts is the controller that the action will be called on. Next is an anonymous type that will be processed to determine what parameters the index action will be called with. It is important that the existing filters are passed to the index action or else when the pager requests a different page it will return all contacts instead of next page of the filtered set of contacts.

The other nice option that the PagedListPager offers is the option to use ajax when requesting a different page. Since the contact page is using ajax when filtering it would be silly not to do the same when paging. To enable ajax just use the PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing with the same AjaxOptions as the filter form.

As a side note I have changed the AjaxOptions on the index view that are used for filtering to match what is shown above for paging. I also removed the accepted verbs from the index action so it only responds to get requests. The request for a new set of data based on a filter change is really more of a get operation than a post operation.

Adding Paging Read More »