Quantcast
Channel: ASP.NET Blog
Viewing all 7144 articles
Browse latest View live

Updating the MVC Facebook API

$
0
0

Over the past several months Facebook made changes to their application development APIs that were incompatible with the MVC Facebook support.

We have been working on updates while the Facebook API kept evolving, and on 4/30/2014 Facebook announced a two-year stability guarantee. This was a fantastic announcement because this ensured a similar stability for ASP.NET MVC developers developing Facebook applications. We've fixed the Facebook package and renamed it to Microsoft.AspNet.Facebook. This package is now available on NuGet.

Here are the issues that we’ve fixed.

If you’re new to the world of Facebook application development on MVC you can check out a Birthday application here. Keep in mind this tutorial will be gradually updated so it may not be entirely accurate.

The important new stuff

The original Microsoft.AspNet.Mvc.Facebook package and corresponding API’s at the time had no concept of optional or default permissions. This created friction with some of the updated prompt dialogs that Facebook released. To address this we’ve made the Facebook’s authorize filter more flexible by providing permission prompt hooks to control login dialog flow.

FacebookAuthorizeFIlter now exposes OnPermissionPrompt and an OnDeniedPermissionPrompt hooks.So what do these hooks do? Let’s go over each in detail.

OnPermissionPrompt

Every time a prompt is about to be shown the OnPermissionPrompt is invoked and passed a PermissionContext. The hook enables you to modify the login flow by setting the context's Result property just like you’d do in an authorization filter.

To utilize the OnPermissionPrompt you can create a FacebookAuthorizeFilter like so:

public class CustomFacebookAuthorizeFilter : FacebookAuthorizeFilter{public CustomFacebookAuthorizeFilter(FacebookConfiguration config)
        : base(config)
    { }protected override void OnPermissionPrompt(PermissionContext context)
    {// This sets context.Result to ShowPrompt(context) (default behavior)base.OnPermissionPrompt(context);
    }
}

And then you can apply the filter the same way you’d apply a FacebookAuthorizeFilter in the old world:

GlobalFilters.Filters.Add(new CustomFacebookAuthorizeFilter(yourFacebookConfiguration));

The default behavior of the OnPermissionPrompt hook is to set the PermissionContext's result to a ShowPromptActionResult by calling into the ShowPrompt method. The source code of the OnPermissionPrompt method looks like this:

protected virtual void OnPermissionPrompt(PermissionContext context)
{
    context.Result = ShowPrompt(context);
}

The ShowPrompt method returns an action result that shows the permission prompt to the user. We can do more though; if we really wanted to, we could redirect the user to a different action every time a prompt was about to be shown by overriding the default signature as shown:

protected override void OnPermissionPrompt(PermissionContext context)
{
    context.Result = new RedirectToRouteResult(new RouteValueDictionary{
            { "controller", "home" },
            { "action", "foo" }
        });
}

This would redirect us to the Home controller’s action Foo instead of prompting the user for permissions.

Lastly we could modify the OnPermissionPrompt method to ignore every prompt that’s shown via setting the PermissionContext's Result to be null:

protected override void OnPermissionPrompt(PermissionContext context)
{
    context.Result = null;
}

This would make it so we never prompt a user for permissions. This isn’t ideal but it is possible.

OnDeniedPermissionPrompt

The OnDeniedPermissionPrompt is invoked when we detect that a user has revoked, declined, or skipped permissions. This occurs instead of the OnPermissionPrompt hook when there are denied permissions. Just like the OnPermissionPrompt we can utilize this hook by creating a FacebookAuthorizeFilter like so:

public class CustomFacebookAuthorizeFilter : FacebookAuthorizeFilter{public CustomFacebookAuthorizeFilter(FacebookConfiguration config)
        : base(config)
    { }protected override void OnDeniedPermissionPrompt(PermissionContext context)
    {// Does nothing (default behavior to leave context.Result null)base.OnDeniedPermissionPrompt(context);
    }
}

And then just like the OnPermissionPrompt above you can apply the filter the same way you’d apply a FacebokAuthorizeFilter in the old world:

GlobalFilters.Filters.Add(new CustomFacebookAuthorizeFilter(yourFacebookConfiguration));

The default behavior of the OnDeniedPermissionPrompt hook is to leave the passed in PermissionContext’s Result member null to ignore the “denied” permission prompt. The source code of the OnDeniedPermissionPrompt method looks like this:

protected virtual void OnDeniedPermissionPrompt(PermissionContext context)
{
}

Here we’re doing nothing so the PermissionContext's Result member is null; this indicates that we do not want to show the permission prompt to the user. If we were to do the same thing as OnPermissionPrompt and set the PermissionContext's Result to be a ShowPromptActionResult we’d infinite loop in our login dialogs; the reason why is because every time the method is invoked there would still be denied permissions.

Like the OnPermissionPrompt hook you can modify the login flow with the result that you return. For example, let’s say we wanted to redirect to a “skip” handling page if we detect a user has skipped permissions:

protected override void OnDeniedPermissionPrompt(PermissionContext context)
{if (context.SkippedPermissions.Any())
    {
        context.Result = new RedirectResult("http://www.contoso.com/SomeUrlToHandleSkips");
    }
}

PermissionContext

In the previous sections I did not discuss the PermissionContext object that is passed into both the OnPermissionPrompt and OnDeniedPermissionPrompt hooks. This object exposes a significant amount of information that enable developers to modify the login flow. Let’s examine what the PermissionContext has to offer:

  • IEnumerable<string> DeclinedPermissions
    • Permissions that were previously requested for but not granted for the lifetime of the application. This can happen by a user revoking, skipping or choosing not to allow permissions in the Facebook login dialog.
  • FacebookContext FacebookContext
    • Provides access to Facebook-specific information.
  • AuthorizationContext FilterContext
    • Provides access to filter information.
  • IEnumerable<string> MissingPermissions
    • The entire list of missing permissions for the current page, including DeclinedPermissions and SkippedPermissions.
  • HashSet<string> RequiredPermissions
    • The entire list of requested permissions for the current page. Includes permissions that were already prompted for.
  • IEnumerable<string> SkippedPermissions
    • Permissions that were previously requested for but skipped. This can happen from a user hitting the "skip" button when requesting permissions.
  • ActionResult Result
    • The ActionResult that should be used to control the login flow. If value is null then we will continue onto the action that is intended to be invoked. Non-null values short-circuit the action.

With all of the information the PermissionContext has to offer you should be able to fully control the login flow.

Hook flow chart

For reference sake I’ve created a flow chart to indicate how Facebook’s login dialog and our hooks interact.

clip_image001

Upgrading Existing Facebook Applications

To upgrade an existing Facebook application follow these steps:

  1. If your application does not currently run; migrate to the latest Facebook application platform.
  2. In the package manager console run: Uninstall-Package Microsoft.AspNet.Mvc.Facebook
  3. Rename all Microsoft.AspNet.Mvc.Facebook namespaces to Microsoft.AspNet.Facebook.
  4. In the package manager console run: Install-Package Microsoft.AspNet.Facebook

Conclusion

We’d love to see people try out the new Microsoft.AspNet.Facebook package and let us know what you think. If you have any questions feel free to reach out below.

To find or file issues do so here.

Note: Facebook changed the way their “user_friends” permission works.  It used to return all of a users friends and now only returns friends that also have your application.  This will obviously be a limiter when using the existing Facebook template and the Birthday App tutorial.


Announcing the Release of ASP.NET MVC 5.2, Web API 2.2 and Web Pages 3.2

$
0
0

The NuGet packages for ASP.NET MVC 5.2, ASP.NET Web API 2.2 and ASP.NET Web Pages 3.2 are now live on the NuGet gallery!

Download this release

You can install or update the NuGet packages for ASP.NET MVC 5.2, ASP.NET Web API 2.2 and ASP.NET Web Pages 3.2 using the NuGet Package Manager Console, with the following commands:

  • Install-Package Microsoft.AspNet.Mvc -Version 5.2.0
  • Install-Package Microsoft.AspNet.WebApi -Version 5.2.0
  • Install-Package Microsoft.AspNet.WebPages -Version 3.2.0

Prerequisites for this release

What’s in this release?

This release primarily includes great new features for Web API OData v4 as summarized below but has bug fixes and minor features that bring in a lot more goodness to MVC, Web API, and Web Pages:

ASP.NET MVC 5.2

ASP.NET Web API 2.2

ASP.NET Web Pages 3.2

You can find a complete listing of the features and fixes included in this release by referring to the corresponding release notes:

Additional Documentation

Tutorials and other information about this release are available from the ASP.NET web site (http://www.asp.net).

Questions and feedback

You can submit questions related to this release on the ASP.NET forums (MVCWeb APIWeb Pages).Please submit any issues you encounter and feature suggestions for future releases on our CodePlex site.

Thanks and enjoy!

 

Changes to Google OAuth 2.0 and updates in Google middleware for 3.0.0 RC release

$
0
0

This article explains the recent changes made to Google OpenID and OAuth 2.0 along with the corresponding updates to the 3.0.0 RC release of Google OAuth  middleware.

Here we will first look at the experience of using Google OAuth middleware in an MVC application with the OWIN 2.1.0 release bits. We will then explain the current changes to Google OAuth API and implications on applications that would continue to use the 2.1.0 version of the packages. Finally we will look at the changes made in the recent 3.0.0 RC release of Google middleware.

Deprecated Google OpenID 2.0

In the Visual Studio 2013 RTM and Update 1 releases, the MVC web applications template using Individual Authentication used Google OpenID by default. The below code (found in Startup.Auth class) registered the middleware

app.UseGoogleAuthentication();

As of April 20, 2014 the Open ID  was deprecated by Google and hence using Google OpenID for external login would throw an error as below

clip_image002

Google OAuth in OWIN 2.1.0 middleware

Applications can solve the above issue by using the Google OAuth 2.0 in the application. This is done by navigating to Google Developer Console to create a new project under users Google account and use the keys. For more detailed information on how to create an application and get the keys check this link.

Once the keys are obtained the they are used to register the middleware in the Startup.Auth as below

 

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
  {
 ClientId = "XXXXX.apps.googleusercontent.com",
 
ClientSecret = "XXXXXXXXXX"
  });
 

Set the callback url in the application created in Google console to {app-url}/siginin-google instead of the default

clip_image004

This should allow applications using Google middleware version 2.1.0 to use Google as an external authentication provider. For a complete sample, see MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on.

Changes to Google OAuth 2.0 and updates to Google middleware

On September 1, 2014 Google will deprecate the earlier version of OAuth 2.0 and will no longer support it. To accommodate these changes, the recent 3.0.0 RC release of Google middleware has been updated. For more information on the changes to the OAuth 2.0 login from Google, please refer this link.

Once the current application is updated to the 3.0.0. RC bits, using Google as an external authentication provider may fail. Below is the screen shot of the Fiddler trace with the failure message for a default MVC application:

clip_image006

The end point for the OAuth has been changed to https://www.googleapis.com/plus/v1/people/me and needs changes to the application created on the developer console.

To make these change, go to Google Console where the application is created. Navigate to the ‘APIs’ tab under the ‘APIS & AUTH’ section and you can see that for the app the Google+ API are not enabled by default.

clip_image008

Click on ‘OFF’ and read and accept the terms to enable the Google+ API. Now run the application and try to login using Google. Logging in should be a success.

Conclusion

This article showed the previous experience of using Google as an external login provider and the upcoming changes in Google OAuth 2.0 and the corresponding updates to Google middleware in the 3.0 RC release. These are some of the updates that are included in the new 3.0.0 RC release of other middlewares as well. Please provider feedback on issues in this article or on codeplex (https://katanaproject.codeplex.com/workitem/list/basic). You can also follow me on Twitter (@suhasbjoshi).

Thanks to Praburaj, Chris and Rick for reviewing the article

ASP.NET vNext in Visual Studio “14” CTP 2

$
0
0

Today we released various runtime and tooling updates for ASP.NET vNext in the Visual Studio “14” CTP 2. This CTP includes our alpha2 runtime packages for ASP.NET vNext. You can find all the details on the specific enhancements added and issues fixed in the published release notes on GitHub.

For information on how to get started with ASP.NET vNext using Visual Studio “14” check out the article Getting Started with ASP.NET vNext and Visual Studio "14".

The existing MVC Music Store and Bug Tracker sample projects have been updated with the bits for this release. You can find instructions on how to open, build, run and publish these sample ASP.NET vNext projects in the documentation for the corresponding GitHub repos.

We’d love to hear your feedback. For VS tooling related issues, please submit bugs through Connect; send suggestions on UserVoice and quick thoughts via Send-a-Smile in the Visual Studio IDE. For ASP.NET vNext, please provide feedback in Github or the ASP.NET vNext forum. If you ask a question in Stack Overflow, use the asp.net-vnext tag.  Thanks for being with us in this exciting time!

Release Candidate for Katana 3 and the ASP.NET Security Components

$
0
0

One step closer to GA! The release candidate NuGet packages for Katana 3 are now available on the NuGet.org gallery, published with version 3.0.0-rc2.

Most of this release consists of bug fixes and stabilization updates, with the exception of the ASP.NET security components.

What’s New with the ASP.NET Security Components in the Release Candidate

You can install or update the release candidate bits through the Package Manager Console. If you were using WS-Federation, get the corresponding package with the following command:

Install-Package Microsoft.Owin.Security.WsFederation -Pre

If you were using OpenId Connect, use the following:

Install-Package Microsoft.Owin.Security.OpenIdConnect -Pre

Finally, you’ll want the new cookie middleware and, if you develop against IIS, you’ll want SystemWeb too:

Install-Package Microsoft.Owin.Security.Cookies -Pre

Install-Package Microsoft.Owin.Host.SystemWeb -Pre

Once again, this release features both feedback-driven updates and brand new features.

We’ll dig deeper in every new feature in the coming weeks, but to give you a sense of the scope of the changes:

  • In earlier previews we exposed protocol artifacts strictly following the protocol specification and their wire values, which resulted in a lot of property names containing ‘_‘.
    You were very vocal in requesting that we give priority to the .NET naming conventions, hence all underscores are now gone. That means that if you wrote code against preview bits you’ll almost certainly have to update it, but the good news is that it’s a very easy change.
  • We added some features that are not directly visible in the OM, such as the ability for apps to update their validation keys in adaptive fashion – so that apps can self-heal in case of key rollover without requiring a restart. That affected the programming model in indirect ways: for example, this feature called for a refactoring of how protocol options are stored and handled.
  • We added some advanced capabilities: the already described reference mode session, which allows you to write web apps that can be consumed by mobile devices with hard cookies size limits; we added a mechanism for automatically detecting token replay attacks; we made it easier for you to control the duration of sessions; and so on.
  • Of course, we fixed lots of bugs. A big thank you for reporting those!!! Please keep ‘em coming!

The main OM changes are demonstrated in the samples in https://github.com/AzureADSamples/: filter the repos by ‘OpenId’ or ‘WsFed’.

Next

At this point we don’t plan to introduce further changes to the development surface of the components: we’ll be doing stabilization work, and as soon as we’ll hit the right quality bar we’ll make the bits generally available. Please help us to weed out the last bugs as we work through the final stretch! As usual, there are many ways for you to engage:

Thanks and enjoy!

Announcing the beta release of Web Pages 3.2.1

$
0
0

The NuGet packages for ASP.NET Web Pages 3.2.1 beta are now live on the NuGet gallery!

Download this release

You can install or update the NuGet package for ASP.NET Web Pages 3.2.1 beta using the NuGet Package Manager Console, with the following commands:

  • Install-Package Microsoft.AspNet.WebPages -Version 3.2.1-Beta –Pre

Prerequisites for this release

What’s in this release?

This release provides a performance improvement in rendering razor pages.

We worked with the MSN team on rendering large pages. When pages render over 80 Kilobytes of data, we end up with objects on the large object heap. When multiple layers of layouts are used this effect can be multiplied.

The result on the server is extra CPU usage, longer retention of memory, and even long pauses during Gen2 cleanup in the garbage collector.

Below is a table demonstrating the results of analyzing a perfview for a run. The CPU is held constant at about 68%, while large pages are being rendered. The table shows that the number of Generation 2 collections has been almost completely eliminated, and the result is higher request rate and a considerable reduction in pauses due to garbage collection.

AreaBefore (3.2)After (3.2.1)Delta %
Total request (count) 26,986 32,591 20.80%
Trace duration (seconds) 196.20 198.601.20%
Request/second137.53164.1019.30%
CPU Load68.80%68.50%  -0.40%
GC CPU Samples124,323 17,543 -85.90%
Total allocations (count) 55,357,14657,222,949 3.40%
Total GC Pause (samples) 15,0918,515 -43.60%
Gen0 GC (count) 4031,216 201.70%
Gen1 GC (count) 290367 26.60%
Gen2 GC (count) 2292 -99.10%
CPU / request (samples/req) 19.7316.47 -16.50%

 

Update:

How was this done? The Razor page took the data built up in a StringBuilder, and called .ToString() in order to write the string to the wire. Similarly this happened when rendering a Razor page inside a Layout page.

It’s common knowledge that you don’t want to build up a string by concatenating multiple strings. But when the result is large enough, you also don’t want to materialize it into a large string because of the reasons above.

Instead we copy the data into a small buffer, and write to the wire (or the layout page) from this buffer, thus avoiding allocating a large object. Further more the total memory consumed is now reduced because we never have to allocate the full string.

Questions and feedback

You can submit questions related to this release on the ASP.NET forums (MVC, Web API, Web Pages).Please submit any issues you encounter and feature suggestions for future releases on our CodePlex site.

Thanks and enjoy!

Profile and Time your ASP.NET MVC app all the way to Azure

$
0
0

Successful web app dev teams generally consider performance a requirement from the beginning,  not an afterthought. Performance should be considered in all phases of a project, from design and into production, including updates to the app. That's not to say you should try to optimize code before you've measured it, you really don't know what needs to be optimized until you measure perf. This tutorial will primarily use a modified version of Tom Dykstra's EF6/MVC 5 Contoso University app to introduce you to measuring and monitoring performance.

This topic contains the following sections:

Using the StopWatch filter to time every action method

Add the StopWatch NuGet package to your ASP.NET MVC app using the following command in the Package Manager Console:

PM> Install-Package StopWatch

The StopWatch  package will create a Filter directory and add a class containing the UseStopwatch attribute. You can apply this filter to controllers with the following syntax:

[UseStopwatch]public class HomeController : Controller{

To apply it globally (that is to every controller), add the following code to the App_Start\FilterConfig.cs file:

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

Add settings to the root web.config file to control how timing information is sent to the trace system. For development we want all requests to be under 250 MS. Action methods taking more than 500 MS are recorded at the warning level, and requests taking more than 2.5 seconds are considered errors. In the markup below, we've also set ShowTimeInLayout to 1 (true), so every page will display the elapsed time. We will show timing information for each page in development and test, but not in production. Later in the tutorial I’ll show how to set these values outside of source code for the Azure environment.

</connectionStrings><appSettings><add key="webpages:Version" value="3.0.0.0" /><!-- Keys deleted for clarity.  --><add key="TraceErrorTime" value="2.5" /><add key="TraceWarningTime" value=".5" /><add key="TraceInformationTime" value=".25" /><add key="ShowTimeInLayout" value="1" /></appSettings><system.web>

The last change we need to make is to add the timing information to the Views\Shared\_Layout.cshtml file:

<footer><p> @Html.Encode(ViewBag.elapsedTime) </p></footer>

Run the app, each page shows the elapsed time for the action method.

r1

If you're running in Visual Studio, you can see the trace data in the output window:

outputWinTrace

Configure Azure settings from Visual Studio

Deploy the app to Azure where you can see the page level timings.

You can configure Azure settings in the Azure portal or in Visual Studio. Most of the steps in the following section will be done in Visual Studio, but they are easily done in the Azure portal. In Server Explorer,  navigate to your web site (con2 in the image below), right click > View Settings.

Avs

Set the Application Logging level to Verbose. The Verbose level logs all trace message. Setting it to Information logs Information, Warning and Error levels.  Setting it to Warning  logs  Warning and Error levels. You can set the logging level in the Azure portal on the Configure tab of the web site:

configPortal

Run the app on Azure, and in Visual Studio, navigate to your web site, right click > View Streaming Logs:

avs2

The output window in shows the trace data. Note the filter lists all the route data plus any query string data.

AzTrace

Looking at trace data from Visual Studio is interesting, but it's not a viable approach to production monitoring. A good way to save trace data on Azure is to connect the trace provider to Azure storage.

AcreateStorage

In Server Explorer, right click Storage> Create Storage Account.

ACSA

In the Azure portal, click on your web site and select the Configure tab. Under application diagnostics set application logging (blob storage) to On. Set the logging level to Information. Click the manage blob storage button and enter the storage account you created. (Note: if you don't see the storage account you created from Visual Studio, navigate to the storage account in the portal and force a full refresh of the browser (^F5)).

z

Click Save. Test you web app so you can generate trace data.

In Server Explorer,  navigate to the blob storage you created and double click on the container.

z1

Double click on the trace data log to open it in Excel.

You can use Excel to sort the data and hide columns you're not interested in.

e

Configure app settings for Azure

In Server Explorer,  navigate to your web site (con2 in the image below), right click > View Settings.

Avs

Under Application Settings, hit the Add button to add the app settings from the web.config file. The app settings here will override those in the web.config file. On a production app, we won't want to show page timings.

zz

Limitations of the Perf filter

The simple stopwatch filter misses the authorization portion of the ASP.NET pipeline (which can be expensive), and it stops timing after the OnResultExecuted completes. The filter completely ignores client side timing, which can be significant. Glimpse is a much more powerful tool to profile and monitor your ASP.NET app - stay tuned, I'll be blogging on that next.

Announcing new Web Features in Visual Studio 2013 Update 3 RTM

$
0
0

Today, the Visual Studio team announced the release of RTM version of Visual Studio 2013 Update 3.  Our team added a few useful features and did some bug fixing in this update to improve the web development experience. 

Our team also released Azure SDK 2.4 SDK today, you can read the detail here.

Microsoft ASP.NET and Web Tools 2013.3

Added Scaffolding Support for ASP.NET 5.2 technologies (MVC, Web API)

With this update, scaffolding will correctly detect what are the versions of NuGet packages that the project is using. For example, if the project is still using ASP.NET MVC 5.1.2, then scaffolding will use 5.1.2, instead of 5.2.

JSON editor improvements

Added Auto-formatting

Auto formatting is now part of the JSON editor and is turned on by default. You can turn off auto-formatting from Tools->Options->Text Editor->JSON->Advanced:

clip_image002

Added Brace Matching

Brace and brackets match highlighting are just like in C# and JavaScript editors now.

clip_image003

CSS editor improvements

Improved Selectors level 4 IntelliSense

We’ve improved IntelliSense support for Selectors Level 4, which will now support more selector patterns making it easier for developers to implement them in their markup.

clip_image005

Added drag-and-drop of fonts, images and.css files from solution explorer into .css files.

When editing a .css file with only body{} inside, drag and drop the following files from the solution explorer:

1. a font file to anywhere in the editor

2. Drag and drop an image file to somewhere inside the body tag

3. drag a css file (e.g. bootstrap.min.css) file to anywhere in the editor

You will get auto-generated css code like the following:

clip_image007

Added support for two-factor authentication in One ASP.NET templates for MVC and Web Forms

The new MVC template includes basic implementation of “two-factor authentication”. You can follow this instruction to plugin Email service and SMS service, and enable the project for two-factor authentication.

Moved ASP.NET Facebook Template to Visual Studio Gallery

The One ASP.NET new project dialog will no longer list Facebook as an option for a project template. Over the past several months Facebook made changes to their application development APIs that were incompatible with the ASP.NET MVC Facebook support. We've fixed the Facebook package and renamed it to Microsoft.AspNet.Facebook. This package is now available on NuGet gallery. As part of this change and to allow us to change the template more rapidly, we are now shipping the ASP.NET Facebook template as a Visual Studio Extension on the Visual Studio gallery.  The VS gallery link will be available soon.

Enabled creation of ASP.Net projects using AAD when signing in with Microsoft account

To see the change, let’s run the following steps. Step 1 to 3 are the same as in previous version.

1. Login to Azure management portal, go to “ACTIVE DIRECTORY”, click the Microsoft row which is auto enabled with your Microsoft account.

clip_image009

2. Click on DOMAINS to get your domain

clip_image011

3. You can use this domain to create a web application with Organizational Account. Click OK in the following dialog.

clip_image013

4. Click OK, you will see a Sign in page to verify organizational account. You can now use your Microsoft account to sign on, in addition to the user@yourmicrosoftADdomain.onmicrosoft.com. Both account certainly need to have Administrator privilege.

clip_image014[1]

Note: You can use Microsoft account only to provision your application on the AD. When signing into your application at runtime, you still need to use an organizational account user@yourmicorsoftADdomain.onmicrosoft.com .

Added support for publishing Microsoft Azure WebJobs in Update 3.

Now, developers can create standard Console Application projects in their Visual Studio solutions that can be published to Azure Websites as either continuous, triggered, or scheduled WebJobs. Console Application projects can also be published from the Visual Studio Solution Explorer as WebJobs to Azure Websites. It’s never been easier for developers to add background processing to their existing ASP.NET web applications.

On any console application, right click the project name and select “Publish as Azure WebJob…”. You will see the following dialog:

clip_image016[1]

Click OK and go through the normal Azure publish dialog, you’ll publish the WebJob project to the chosen Azure website.

clip_image017[1]

After 1st publish, you will see “webjob-publish-settings.json” file being created, storing the values you’ve set from the “Add Azure WebJob” dialog. From now on, running “Publish as Azure WebJob…” will directly go to the normal Azure publish dialog. Only if you remove this JSON file, you will see the “Add Azure WebJob” dialog again. For more information about the new WebJobs deployment feature, see How to Deploy Azure WebJobs to Azure Websites.

 

ASP.NET MVC 5.2

ASP.NET Web API 2.2

ASP.NET Web Pages 3.2

ASP.NET Identity

Microsoft released ASP.NET Identity 2.1.0 in this update. We added support for SignInManager. SignInManager, making it easier to add Two-Factor authentication, account lockout, and other security features when you log on. For more information about this feature, go to this blog post.

Entity Framework 6.1.1

Microsoft released EF 6.1.1 in this update. For more information, go to this blog post

WebDeploy 3.5 refresh

We released a Web Deploy 3.5 refresh in Visual Studio Update 3 to enable integration with SQL Server 2014. You can also download it from here

IIS Express 8.0 June 2014 Hotfix

We released an IIS Express 8.0 June 2014 Hotfix in Visual Studio Update 3. This hotfix addresses an issue with IIS Express 8.0 where creating a site and using certain character combinations in the site's folder, Internet Information Services (IIS) 8.0 Express does not start. You can also download it from here.

Known Problems

1. If you upgrade to Visual Studio Update 3 RTM from Visual Studio Update 3 CTP1 or Visual Studio Update 3 CTP2 directly, JSON editor or LESS editor does not work.

To work around this issue, run Visual Studio 2013 Update3 repair that will bring the computer to a good state.

 

2. When creating a default C# ASP.NET Web Application from MVC, WebAPI or SPA template with individual authentication, generated Views\Account\ _SetPasswordPartial.cshtml and _ChangePasswordPartial.cshtml files contain invalid model.

In file _SetPasswordPartial.cshtml,

@model <MyProjectName>.Models.ManageUserViewModel
Should be changed to:
@model <MyProjectName>.Models.SetPasswordViewModel

In file _ChangePasswordPartial.cshtml,

@model Microsoft.AspNet.Identity.ManageUserViewModel
Should be changed to:
@model <MyProjectName>.Models.ChangePasswordViewModel

Similar problems exist for generated VB projects as well.

In file _SetPasswordPartial.vbhtml,

@ModelType ManageUserViewModel
Should be changed to:
@ModelType SetPasswordViewModel

In file _ChangePasswordPartial.vbhtml,

@ModelType ManageUserViewModel
Should be changed to:
@ModelType ChangePasswordViewModel

Summary

We hope you can evaluate these new features and let us know about any bugs and suggestions.  For VS features, please use Connect to submit bugs, ASP.NET UserVoice to submit and vote for suggestions, and the ASP.NET Forums for Q&A.  You can also visit the following open source sites to leave suggestions and open issues directly:


Use a Microsoft Account to Create Web Apps Protected by Azure AD - With VS2013 Update 3

$
0
0

Back in December I have posted an article which described a limitation of the organizational identities support in the ASP.NET project templates in Visual Studio 2013.

In a nutshell. The ASP.NET project templates in Visual Studio 2013 have the ability to automatically create an entry for your application in Azure Active Directory – so that your project is created already configured to perform web sign on from the very start. That task requires a write operation in the Azure AD of choice, hence Visual Studio needs to acquire a valid token for performing it. To do so, it prompts you – the developer – for a valid account with administrative privileges in the target directory.
Azure AD admits both “native” directory users (often of the form <user>@<tenant>.onmicrosoft.com) and Microsoft Accounts (abbreviated MSA), however Visual Studio was able to perform this task only via “native” directory users. Given that many Azure subscribers routinely use an MSA to perform most tasks in their subscriptions, and that the default directory in such subscriptions initially contains just that MSA in its users collection, this limitation was something we wanted to resolve soon.

I am happy to announce that the problem has been resolved in VS 2013 Update 3! You can now use an MSA to configure your ASP.NET apps to use Azure AD for authentication. In this post I will show you how to take advantage of the feature. Rather than just giving you instructions, I will also give you some context about the directory assets that every Azure subscribers get out of the box.

Your Default Azure AD Tenant in Your Azure Subscription

Here there’s some background on we are going to work with.

Every Azure subscriber automatically gets a default azure AD tenant, that can be used for development purposes. The rules are slightly different between the case in which your subscription is backed by your organization and connected to your on-premises directory, and the case in which you subscribed as an individual using your MSA. In this post I will focus on the latter.

In fact: to make sure I’d describe the experience as faithfully as possible, for this tutorial I created a brand new MSA (testmsauser@outlook.com) and I used it to get a free trial subscription.

Done that, I headed to https://manage.windowsazure.com.

image

Of course I set up my new MSA with 2 factors authentication, hence the screen below. I am sure that all of you did that already Winking smile but just in case, you can do it here.

image

Once you’re in, you’ll see that your subscription contains a default directory. Let’s click on that.

image

The default directory is a full blown Azure AD tenant, ready for you to develop against. Let’s take a look around: click on USERS form the top bar.

image

At creation time, the only user in the the Azure subscription’s administrator: in our case, testmsauser@outlook.com. It is in the global administrators role for the directory, which means that it can do pretty much anything.

From here you can add new users: they can be guest users (from MSA or other directories), or they can be native directory users, originating from this tenant. You’ll do that later in this tutorial.
Such users will  <user>@<tenant>.onmicrosoft.com. In out case, what is the value of “<tenant>”? To find out, click on DOMAINS.

image

Azure created the default directory by deriving the domain name from the MSA of the administrator: in this case, our tenant is testmsauseroutlook.onmicrosoft.com. You can add custom domains by going through a verification step, but for our purposes the default domain will do just fine.

Before leaving the portal and switching to Visual Studio, let’s take a quick look at the APPLICATIONS tab.

image

As the subscription is brand new, there are no entries here yet.

In order to protect an application with Azure AD, Azure AD needs to know important details about the app: which URLs it will use, which identifiers will be exchanged at authentication time, and so on. You can let Azure AD know about your application by creating a new entry for it via the portal, that’s what the ADD button on the bottom bar does. However, as mentioned at the beginning of the post you can also provision an app entry directly via Visual Studio 2013. That’s pretty handy, given that Visual Studio can automatically provide application properties (like the app URL, which at development time will likely be the URL assigned by IIS Express) that you would otherwise have to type.

Creating an ASP.NET App Protected by Azure AD

Did you install the RTM of Update 3 for Visual Studio 2013? Excellent! Follow along the instructions below to create an Azure AD protected project.

Select new project, web. Pick ASP.NET Web application.

image

In this tutorial I’ll create an MVC app, but you can pick Web Forms or Web API just as well.

image

Clicking on Change Authentication you’ll land on the dialog below.

image

Here you have all the controls you need to tell VS to secure your app with Azure AD.

In the left hand side list, select Organizational Accounts. Leave all the defaults.
In Domain, enter the domain of your default directory (mine is testmsauseroutlook.onmicrosoft.com). Click OK.

image

In this phase, Visual Studio acquires a token from AD that will be used to write in the directory the new application’s details. To do so, it needs you to authenticate. From Update 3 on, you can use an MSA or a native directory user here. Given that in my test directory I have only my MSA, I’ll use that.

You are presented with the Azure AD authentication dialog. As soon as you type your MSA in the username field, you’ll be redirected to the MSA authentication page.

image

My user has MSA enabled, hence I’ll be prompted for a code even if here I am using a rich client (Visual Studio). Pretty handy!

image

Once VS successfully authenticated, all you need to do is hitting OK and your project will be generated.

image

Visual Studio add the app entry to the directory automatically. Want proof? Let’s go back to the portal, head back to the APPLICATIONS list and refresh the browser.

image

As you can see, there is now a new entry – with the same name as the VS project. Click on it, then select CONFIGURE.

image

If you scroll through that page, you’ll see that the app has been correctly provisioned by Visual Studio.

Creating a Test Directory User

We are not quite ready to test the app yet. The app entry in Azure AD is complete and fully functional: however the Azure AD protocol head it uses (WS-Federation) still suffers from the old restriction of accepting only native directory users. This restriction will be lifted soon (and it is already resolved for the OpenId Connect protocol head). In the meanwhile, if we want to test the app right now we need to create a new user in the directory. Luckily, it’s super simple.

Go to the USERS tab and hit ADD. Add any details you want until the Get temporary password screen.

image

image

image

Hit the create button.

image

Azure generates a temporary password for the new user. The user will be forced to change it at first login, so I usually perform a sign in immediately to get that task out of the way. Open an inPrivate browser, and navigate to myapps.onmicrosoft.com, the portal gathering all the apps approved by your admin to be used with AAD. (It does not really matter where you go at this point, as long as it is an AAD protected site. I like myapps because it’s easy to remember!)
You’ll be bounced to the Azure AD authentication page.

image

Enter your temporary password. You’ll be asked to enter a new password right away.

image

Once you’ve done that, Azure AD will make you test your new password by re-entering it.

image

Your new user has its new password. We are ready to give the app a spin.

image

Testing the Project

Let’s get back to Visual Studio. There are no changes required, all you need to do is simply hitting F5.

You’ll be prompted to authenticate, as expected. Enter the credentials of the directory user you just created.

image

And voila’! The new application signed in the directory user, as expected.

image

Summary

If you have feedback, there are multiple venues you can use to reach the team. Please use Connect to submit bugs, ASP.NET UserVoice to submit and vote for suggestions, and the ASP.NET Forums for Q&A.

We hope that this feature will help even more of you to take advantage of the great identity features that come with your Azure subscriptions!

Announcing RTM of ASP.NET Identity 2.1.0

$
0
0

We are releasing RTM of ASP.NET Identity 2.1.0. The main focus in this release was to fix bugs and add SignInManager to make it easier to use security features such as Account Lockout, Two-Factor Authentication for login.

ASP.NET Identity 2.1 is included in the ASP.NET templates which were released with VS 2013 Update 3. The templates have been updated to include Two-Factor Authentication.

Download this release

You can download ASP.NET Identity from the NuGet gallery. You can install or update these packages using the NuGet Package Manager Console, like this:

Install-Package Microsoft.AspNet.Identity.EntityFramework–Version 2.1.0 

Install-Package Microsoft.AspNet.Identity.Core -Version 2.1.0

Install-Package Microsoft.AspNet.Identity.OWIN -Version 2.1.0

What’s in this release?

Following is the list of features and major issues that were fixed in 2.1.0.

SignInManager

SignInManager makes it easier to add Two-Factor authentication, account lockout and other features when you login.

SignInManager was in the samples package in ASP.NET Identity 2.0. In version 2.1, we have added it in the framework

The following tutorials cover account confirmation and Two-Factor Authentication (including account lockout and protecting against brute force attacks against the two factor authentication codes)

http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity

http://www.asp.net/identity/overview/features-api/two-factor-authentication-using-sms-and-email-with-aspnet-identity

Following show the login code of an application which uses two-factor authentication and account lockout.

logincode

List of bugs fixed

You can look at all the bugs that were fixed in this release by clicking here.

Enable Two-Factor Authentication in ASP.NET templates using VS 2013 Update 3

The following steps summarize the experience of enabling Two-Factor Authentication using SMS in ASP.NET MVC. You can follow the same steps for other templates such as Web Forms as well. You can also write your own Two-Factor authentication provider (such as using QR codes using authenticator apps) and plug it in.

For a more detailed walkthrough of the code and the concepts refer to the following article http://www.asp.net/identity/overview/features-api/two-factor-authentication-using-sms-and-email-with-aspnet-identity

  • Create ASP.NET MVC Template and select Authentication using Individual User Accounts
  • Open Views\Manage\Index.cshtml and “Add Phone Number option” by uncommenting the following lines
    Code Snippet
    1. <dt>Phone Number:</dt>
    2.         <dd>
    3.             @(Model.PhoneNumber ?? "None") [
    4.             @if (Model.PhoneNumber != null)
    5.             {
    6.                 @Html.ActionLink("Change", "AddPhoneNumber")
    7.                 @:&nbsp;|&nbsp;
    8.                 @Html.ActionLink("Remove", "RemovePhoneNumber")
    9.             }
    10.             else
    11.             {
    12.                 @Html.ActionLink("Add", "AddPhoneNumber")
    13.             }
    14.             ]
    15.         </dd>

 

  • Open Views\Manage\Index.cshtml and enableTwo-Factor Authentication
  • Code Snippet
    1. <dt>Two-Factor Authentication:</dt>
    2.         <dd>
    3.             @if (Model.TwoFactor)
    4.             {
    5.                 using (Html.BeginForm("DisableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    6.                 {
    7.                     @Html.AntiForgeryToken()
    8.                     <text>Enabled
    9.                         <inputtype="submit"value="Disable"class="btn btn-link"/>
    10.                     </text>
    11.                 }
    12.             }
    13.             else
    14.             {
    15.                 using (Html.BeginForm("EnableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    16.                 {
    17.                     @Html.AntiForgeryToken()
    18.                     <text>Disabled
    19.                         <inputtype="submit"value="Enable"class="btn btn-link"/>
    20.                     </text>
    21.                 }
    22.             }
    23.         </dd>

  • Register a SMS provider in App_Start\IdentityConfig.cs
    • You can use any SMS services such as Twilio or others. For more information on using Twilio see this post. Your SMS service should look like as follows.

Code Snippet
  1. publicclassSmsService : IIdentityMessageService
  2. {
  3.     publicTask SendAsync(IdentityMessage message)
  4.     {
  5.         var Twilio = newTwilioRestClient(Keys.TwilioSid, Keys.TwilioToken);
  6.         var result = Twilio.SendMessage(Keys.FromPhone, message.Destination, message.Body);
  7.  
  8.         // Twilio doesn't currently have an async API, so return success.
  9.         returnTask.FromResult(0);
  10.     }
  11. }

  • Register a user
    • Browse to the site and register as a new user.

  • Go to Manage page: Click your username after logging in and go to Manage page. Here is what the Manage page would look like once you login

Manage

  • Add a Phone Number and verify it
    • You need to add a verified phone number before you can use it to get text messages for two-factor authentication.

phoneNumberAdded

  • Enable Two-Factor Authentication
    • Click on the “Two-Factor Authentication” to enable it.

Enable2FA

  • Logout and Login using username and password
    • When you login you will be prompted to select the Two-Factor authentication provider to use to get the code. You can choose between Email, SMS and you can also write your own Two-Factor authentication providers such as QR code generators using Authenticator apps.

send2facode

  • Get the code you got through SMS and verify it

RememberBrowser

  • Check the Remember the Two-Factor Authentication Option
    • Clicking on the this checkbox will exempt you from needing to use 2FA to log on with that computer and browser. You can do this on any private machine you regularly use. By setting Remember this browser, you get the added security of 2FA from computers you don't regularly use, and you get the convenience on not having to go through 2FA on your own computers.

  • Account Lockout
    • If you enter the code incorrectly then the account will be locked out for 5min after 5 incorrect tries. You will be able to login after 5 min without requiring an Admin action.

AccountLockout

 

    • Account Lockout feature in ASP.NET Identity can be configured inside the ApplicationUserManager in App_Start\IdentityConfig.cs as follows.
    • Code Snippet
      1. // Configure user lockout defaults
      2. manager.UserLockoutEnabledByDefault = true;
      3. manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
      4. manager.MaxFailedAccessAttemptsBeforeLockout = 5;

 

    • When you enter the two-factor verification code, the VerifyCode action uses the SignInManager to complete the two-factor SignIn process and protects for brute force attacks against the two factor codes.
      Code Snippet
      1. //
      2.         // POST: /Account/VerifyCode
      3.         [HttpPost]
      4.         [AllowAnonymous]
      5.         [ValidateAntiForgeryToken]
      6.         publicasyncTask<ActionResult> VerifyCode(VerifyCodeViewModel model)
      7.         {
      8.             if (!ModelState.IsValid)
      9.             {
      10.                 return View(model);
      11.             }
      12.  
      13.             // The following code protects for brute force attacks against the two factor codes.
      14.             // If a user enters incorrect codes for a specified amount of time then the user account
      15.             // will be locked out for a specified amount of time.
      16.             // You can configure the account lockout settings in IdentityConfig
      17.             var result = await SignInManager.TwoFactorSignInAsync(
      18.                 model.Provider, model.Code, isPersistent:  model.RememberMe,
      19.                 rememberBrowser: model.RememberBrowser);
      20.             switch (result)
      21.             {
      22.                 caseSignInStatus.Success:
      23.                     return RedirectToLocal(model.ReturnUrl);
      24.                 caseSignInStatus.LockedOut:
      25.                     return View("Lockout");
      26.                 caseSignInStatus.Failure:
      27.                 default:
      28.                     ModelState.AddModelError("", "Invalid code.");
      29.                     return View(model);
      30.             }
      31.         }
         

Samples/ Documentation

Migrating from ASP.NET Identity 2.0.0

This is a compatible release with 2.0.0 and there are no database schema changes with this release.

Give feedback and get support

    • If you find any bugs please open them at our Codeplex Site where we track all our bugs https://aspnetidentity.codeplex.com/
    • If you want to discuss these features or have questions, please discuss them on Stack Overflow and use the following tag “asp.net-identity”

The ASP.NET Identity team would like to thank you for trying out this release and your feedback for ASP.NET Identity.

Develop ASP.NET vNext applications on a Mac

$
0
0

Hi everyone, this post is in my name but it’s authored by Sourabh Shirhatti. He is a Program Manager Intern from the University of Texas at Austin that I’ve had the pleasure of working with this summer. Below is his story, I hope you enjoy it.

Prior to my internship with Microsoft, my web stack of choice was Node.JS + Express + MongoDB, and I primarily developed on a Mac. Like most of the Node.js community I had a minimalist environment; my tools of trade were Sublime Text, a terminal window and a browser. This kind of lightweight environment was not possible with ASP.NET.

Using Visual Studio at Microsoft showed me the benefits of a full-featured environment. The intelligent auto-completions coupled with an integrated build and test environment made Visual Studio invaluable. However, I still missed the lightning fast experience with Sublime Text.

With that in mind, I set out to build tools to make it easier to develop ASP.NET applications on my Mac. I have tried to identify the features I most missed from Visual Studio and how tooling could make my life easier.

To skip ahead to the download, just click http://github.com/ligershark/kulture/.

Create a new project

Starting out with a clean slate on my Mac. I ran into my first problem. How do I create a new project?

New Project Dialog in Visual Studio

Visual Studio makes it easy to generate the boilerplate for a new project. File -> New Project followed by two more mouse clicks and there you have a project that builds and runs.

Fortunately, the command-line community already has an excellent scaffolding experience through Yeoman. The logical next step was to build a yo generator for ASP.NET. The generator is hosted on GitHub at https://github.com/shirhatti/generator-aspnet where you can have a look and give it a spin. The code snippet below will get you started.

If you would like to follow along, click here for a more detailed instruction guide.

# Install yeoman
npm install -g yo
# Install the ASP.NET generator
npm install -g generator-aspnet
# Run the generator
yo aspnet

 02

Run my Project

Once I scaffolded out an empty project, I ran into another roadblock. How do I run my application?

In Visual Studio, it’s as easy as pressing F5.

I was able to one-up Visual Studio in Sublime Text 3 (ST3) by allowing you to run any of your custom k commands, and like any command in Sublime Text the key-binding is user-configurable. Here’s what my ST3 shows me when I press F5.

03

Thanks to the awesome folks on the Runtime team, you can now run your ASP.NET apps on a Mac using a cross-plat web server called Kestrel

This sounds exciting. How do I try it out?

You can try out the ST3 plugin at https://github.com/ligershark/Kulture

Show me my errors!

I have a boilerplate application that builds. I decide go ahead and add some code.Uh-oh! Looks like it doesn’t build anymore. How do I see the errors?

Visual Studio shows you a concise error list when your build fails with description, file name, line number and column number of each error.

04

Going for feature parity, that’s exactly what I tried to achieve in ST3.
Press F7 in Sublime and here’s what you see

05

Manage Dependencies

One of the key efforts with ASP.NET vNext was to trim the fat; every non-essential feature exists and lives in its own separate NuGet package allowing your app to include only what it needs.

This is great for reducing my footprint, but how do I discover packages and their version numbers to include in my project?

06

Providing completions for Package names and version numbers inside of project.json based on fuzzy matching made it easier to discover packages and add functionality to my application

Code Completions (In progress)

Error lists are awesome, but I wouldn’t have so many errors if ST3 helped me as I type. Can you suggest completions?

Visual Studio offers Intellisense, intelligent code completion and syntax checking that we all know and love. Fortunately, we don’t have to reinvent the wheel; the completions in Visual Studio are powered Roslyn, an Open Source C# compiler.

To achieve the same completions in ST3, we are working on providing out-of-process completions that are powered by Roslyn. I’ve been working with the Open Source community and I’m confident we’ll get this done after some initial promise.

https://twitter.com/sergey_litvinov/status/497391229068247041

https://twitter.com/sergey_litvinov/status/497391229068247041

image

https://twitter.com/jchannon/status/497017361556582400

You can follow the progress for Code Completions here.

Despite the aforementioned features, developing ASP.NET applications on a Mac is still not YET first-class experience. I say not yet because we are making strides in the right direction.

ASP.NET is Open Source.

All the code I’ve worked on this summer is also available on GitHub.

Join the party by opening issues or creating Pull Requests at https://github.com/ligershark/Kulture

Sourabh Shirhatti | @sshirhatti | http://shirhatti.com

ASP.NET vNext in Visual Studio “14” CTP 3

$
0
0

Today we released various runtime and tooling updates for ASP.NET vNext in Visual Studio “14” CTP 3. We included all the features that were included in Visual Studio 2013 Update 3 in this release. This release also has ASP.NET vNext runtime and tooling improvements as outlined below.

ASP.NET vNext Runtime

This CTP includes our alpha3 runtime packages for ASP.NET vNext. You can find all the details on the specific enhancements added and issues fixed in the published release notes on GitHub.

For information on how to get started with ASP.NET vNext using Visual Studio “14” check out the article Getting Started with ASP.NET vNext and Visual Studio "14".

The existing MVC Music Store and Bug Tracker sample projects have been updated with the bits for this release. You can find instructions on how to open, build, run, and publish these sample ASP.NET vNext projects in the documentation for the corresponding GitHub repos.

ASP.NET vNext Tooling

No files listed in the .kproj file

When using ASP.NET vNext, all source files in/under the folder that contains project.json will be automatically included in the project. Visual Studio project files typically list each file that is included in the project. In the previous CTPs if you added a file to your source folder it would automatically be reflected in Solution Explorer in Visual Studio. This was facilitated by a file watcher looking for file events and then modifying the .kproj directly. In this release we have updated the .kproj so that the files are not listed. This is consistent with how the runtime consumes those files. Also, not listing the files in the .kproj should significantly ease merging issues that you’ve had in the past with project files.

Because of this breaking change when going from CTP2 to CTP3 it is recommended that you either:

1. Re-create the .kproj file, or

2. Remove files listed in the .kproj file

To re-create the .kproj file you can delete the .kproj and .kproj.user file. Then in Visual Studio you can go to File->Open Project and select the project.json file. Note: after opening that project you may need to update the Output Type property. Take a look at the Opening project.json as a project may lead to the wrong output type topic in Known Issues below for more info.

Just one more thing that I want to point out here. One other reason that we implemented this feature is to allow Visual Studio developers to work with those that are using the command line to build ASP.NET vNext applications. If we assumed that all ASP.NET vNext developers were using Visual Studio then we could have listed each file in the .kproj. This is evidence that we are committed to providing a cross platform story for ASP.NET vNext. On that note in case you missed it you can now develop ASP.NET vNext applications on Macs :)

If you have a large number of .kproj files from a previous CTP that need to be updated, the process above may be cumbersome. The other option is to delete the files listed in the .kproj file. The .kproj file is an MSBuild file, which means that it is an XML file. You can write a script to remove the files. If you are using Windows I have developed a PowerShell script that you can use at https://gist.github.com/sayedihashimi/f2048fd957f860f38ecd. Note: this script is not officially supported and provided as it is. If you develop a script that works on other platforms besides windows then feel free to fork and comment to my gist so that others can find it later. I’ll accept any new scripts which appear to work.

Unit testing

When developing software, a critical aspect is to develop and execute unit tests. I’m happy to say that in this CTP you will see our initial support for unit testing in ASP.NET vNext projects. Note: we have not yet integrated creating unit test projects as a part of the new project experience, but we will be working on that. To get started with unit testing follow these instructions.

1. Add an ASP.NET vNext Class Library project for your test cases to your solution

2. Update project.json to include the test runner for your unit testing library of choice

3. Author test cases in that class library

You can find a very basic working sample using xUnit at http://bit.ly/basic-unittestctp3. I’ll describe how you can re-create what is in that project. Below you will find the full project.json for the sample test project. In this sample I will show you how to get started with xUnit, but we are not limited to xUnit. You can plug in any unit testing framework of your choice. Keep an eye on the blog and http://asp.net/vnext for more details about how to integrate other unit testing frameworks.

Code Snippet
  1. {
  2.   "dependencies": {
  3.     "Xunit.KRunner": "1.0.0-alpha3"
  4.   },
  5.   "commands": {
  6.     "test": "Xunit.KRunner"
  7.   },
  8.   "frameworks": {
  9.     "net451": {
  10.       "dependencies": {}
  11.     },
  12.     "k10": {
  13.       "dependencies": {
  14.         "System.Runtime": "4.0.20.0"
  15.       }
  16.     }
  17.   }
  18. }

There are two items that are critical here. The presence of Xunit.KRunner in the dependencies section. This will make the xUnit APIs available so that you can author your test cases. The other item is the test command in the commands section. Commands are executable from the command line with the k utility. If you are interested in command line scenarios see the instructions here to get started. When discovering/executing test cases Visual Studio will look for the presence of a test command, and then invoke the necessary command line to discover & execute test cases. Let’s move on to see the test cases in the project and then how to invoke them in Visual Studio.

In the samples there is a single C# file named SampleTests.cs, below you’ll find the full content for that source file.

Code Snippet
  1. using System;
  2. using Xunit;
  3.  
  4. namespace Classlibrary1
  5. {
  6.     publicclassSampleTests
  7.     {
  8.         [Fact]
  9.         publicvoid TrueIsTrue()
  10.         {
  11.             Assert.True(true);
  12.         }
  13.  
  14.         [Fact]
  15.         publicvoid OnePlusOneIsTwo()
  16.         {
  17.             Assert.Equal(2, 1 + 1);
  18.         }
  19.     }
  20. }

Here you can see that we have two simple test cases, TrueIsTrue and OnePlusOneIsTwo. These methods are decorated with the Fact attribute to indicate that they are unit tests and they invoke Assert methods to verify behavior.

After authoring these test cases in Visual Studio you will need to perform an explicit build (CTRL+SHIFT+B for general profile) to discover tests cases. Note: “Run All” does not discover tests cases in this release. After you build the project Visual Studio will discover tests cases and populate the Test Explorer. The image below shows how this will look like for the sample project.

clip_image001[4]

Now that the Test Explorer is populated you can execute them all using the Run All command, or you can select to invoke individual test cases. Let’s click Run All and verify that the test cases pass. You can see the result of that in the image below.

clip_image002[4]

Note: in this release discovering tests cases is a bit slow. You can monitor progress of discovering and executing test cases in the Tests output window. We will be working on improving the performance here in future releases. In this initial release we do not have the ability to debug test cases either. We will light that up soon.

Support for Configuration

We have added support for managing build configurations in the Visual Studio configuration manager. For new solutions/projects you will have two build configurations by default, Debug & Release. If you need to define create new project build configurations you can do so in the configuration manager. In the image below you can see how to invoke the Configuration Manager dialog.

clip_image003[4]

In this case I used the Configuration Manager to create a new project configuration. You can see that there is a new build configuration named Sample in the configurations section. Using build configurations you can customize the options that are passed to the compiler.

Command line scaffolding

In this release you’ll also find our initial support for scaffolding content into existing projects. Currently this is limited to the command line, and is very basic. In future releases you’ll see us beef up the support as well as integrate the experience into Visual Studio. Just like unit testing, we are approaching this in a command-line first approach and having Visual Studio execute those command lines. That way we know that command line and Visual Studio users have similar capabilities. You’ll also be able to create your own custom scaffolders using C# and Razor. Keep an eye out here and on asp.net/vnext for more details on the new command line scaffolding.

Web publish via Web Deploy to Azure Web Sites

In previous CTPs we had enabled publishing your project to Azure Web Sites. We did this through an API which is only available in Azure Web Sites. Since then we have worked with the Web Deploy (aka MSDeploy) team and now publishing is going through Web Deploy. The support is still limited to Azure Web Sites, but this is our first step to enabling a publish experience for other hosting platforms.

There is no visible change from previous releases. All of the changes are under the hood.

If you have tried publishing in previous releases and try publishing in CTP3 you’ll notice that the initial publish experience is much slower than it was in previous releases. In previous releases we had the ability to call specific Azure Web Sites APIs that were optimized for that scenario in particular. This will not be our final experience and you should expect publish times to be much faster in the future.

Most of the time on the initial publish is spent in publishing the NuGet packages that your project references. In later releases we will work with the Web Deploy team to restore known NuGet packages on the server side, thus avoiding the overhead of transmitting each NuGet package from the client to the server. This will significantly improve performance and it will be much faster than previous releases where we used Azure specific APIs.

Known Issues

Opening project.json as a project may lead to the wrong output type

In CTP3, and previous CTPS, when you open project.json as a project, the created project is an ASP.NET vNext Class Library project. If the project is a web project then fixing this is easy. In the properties grid for the project you will find an Output Type property. You can use this to switch from Class Library to Web Application. See the image below.

clip_image004[4]

Summary

We’d love to hear your feedback. For Visual Studio tooling related issues, please submit bugs through Connect, send suggestions on UserVoice and quick thoughts via Send-a-Smile in the Visual Studio IDE. For ASP.NET vNext, please provide feedback in Github or the ASP.NET vNext forum. If you ask a question in Stack Overflow, use the asp.net-vnext tag.  Thanks for being with us in this exciting time!

Thanks to Sayed Ibrahim Hashimi | @SayedIHashimi, who wrote the majority of this blog.

Upgrading to jQuery.UI.Combined 1.11.0

$
0
0

The jQueryUI team released a new version of their library recently. This release has some changes which will impact your apps as you migrate to 1.11.0. This post will highlight the changes you need to do to use jQuery.UI.Combined NuGet package.

Changes

I am going to highlight the change that is relevant to this post. For a full list of changes/ release notes see the changelog and upgrade guide on the  jQueryUI team site.

The jQuery.UI.Combined NuGet package combines the jQueryUI controls and a base theme. In 1.11.0, the jQuery UI team has renamed the files in the base theme. The change was to drop “jquery.ui” from all the CSS and Javascript filenames. This change was done to add AMD support.

The minified files for the base theme have been removed as well.

Migrating apps

  • If you have an app that is linking to these file names then you will have to update the link references to pull in the correct file names.
  • If you are using ASP.NET Web Optimizationfeature, then you would have to update your BundleConfig to add the updated filenames. Web Optimization was used in the ASP.NET Web Forms, MVC, Web API and SPA templates that were shipped with Visual Studio 2012 and 2013.
    • The following code shows the updated BundleConfig. If you are using the ASP.NET MVC or Web API  templates from VS 2012/ 2013, then you can find this file in App_Start folder of your site.
Code Snippet
  1. bundles.Add(newStyleBundle("~/Content/themes/base/css").Include(
  2.             "~/Content/themes/base/core.css",
  3.             "~/Content/themes/base/resizable.css",
  4.             "~/Content/themes/base/selectable.css",
  5.             "~/Content/themes/base/accordion.css",
  6.             "~/Content/themes/base/autocomplete.css",
  7.             "~/Content/themes/base/button.css",
  8.             "~/Content/themes/base/dialog.css",
  9.             "~/Content/themes/base/slider.css",
  10.             "~/Content/themes/base/tabs.css",
  11.             "~/Content/themes/base/datepicker.css",
  12.             "~/Content/themes/base/progressbar.css",
  13.             "~/Content/themes/base/theme.css"));

 

    • The following code shows the updated Bundle.config. If you are using the ASP.NET Web Forms templates from VS 2012/ 2013, then you can find this file in root of your application.
Code Snippet
  1. <styleBundlepath="~/Content/themes/base/css">
  2.   <includepath="~/Content/themes/base/core.css" />
  3.   <includepath="~/Content/themes/base/resizable.css" />
  4.   <includepath="~/Content/themes/base/selectable.css" />
  5.   <includepath="~/Content/themes/base/accordion.css" />
  6.   <includepath="~/Content/themes/base/autocomplete.css" />
  7.   <includepath="~/Content/themes/base/button.css" />
  8.   <includepath="~/Content/themes/base/dialog.css" />
  9.   <includepath="~/Content/themes/base/slider.css" />
  10.   <includepath="~/Content/themes/base/tabs.css" />
  11.   <includepath="~/Content/themes/base/datepicker.css" />
  12.   <includepath="~/Content/themes/base/progressbar.css" />
  13.   <includepath="~/Content/themes/base/theme.css" />
  14. </styleBundle>

Announcing RTM of Katana 3

$
0
0

Dear all,

Today I have the honor and privilege of announcing the general availability of Katana 3!

This is an important update to Microsoft’s OWIN implementation, which offers you powerful new functionality. In a nutshell:

  • Katana 3 takes full advantage of the .NET 4.5 async-await model, affording significant performance improvements in respect to former releases. Note: if you require .NET 4.0 support, you can still use earlier Katana versions.
  • Katana 3 introduces a new set of middlewares meant to support enterprise grade authentication and claims based identity via standard protocols, making integration with Azure Active Directory and ADFS straightforward.
    The new middleware follows a proven extensibility model, which grants you the ability to customize every stage of the authentication pipeline while maintaining an extremely simple programming model for the default cases. Existing components (such as the cookies middleware)have been updated accordingly. At this time, Katana 3 supports the following protocols:
    • WS-Federation
    • OpenId Connect (id_token and id_token+code, via form_post)
    • OAuth2 bearer token authentication for Web API
  • This release includes fixes for issues related to Twitter and Google API changes.

You can find the new packages in the stable feed of NuGet.org. For a complete list please see this page.
The preview stage is finally over: if you were holding back from using those packages given their prerelease status, you can now deploy in production with confidence.
You can find the samples at the usual location https://aspnet.codeplex.com/. For samples demonstrating use of Katana 3 for Azure AD and ADFS integration please refer to https://github.com/AzureADSamples/.

We wanted to thank our fantastic community for all the feedback you gave us during development: this release would not have been possible without your help. Happy coding!

Command line scaffolding for ASP.NET vNext

$
0
0

In previous releases we have added support for scaffolding controllers/views based on project artifacts in both MVC and Web Forms projects. The technology used for those previous releases was tied to Visual Studio. With ASP.NET vNext one of our high level goals is to enable Visual Studio customers to work with non-Visual Studio users. So the most critical aspects of developing/testing ASP.NET vNext projects should be available to the non-Visual Studio. Scaffolding is a good example of this.

Because we need to support scaffolding content into a project for both VS and non-VS scenarios we have gone back to the drawing board for scaffolding in ASP.NET vNext projects. In this post you I will describe how you can get started trying out the scaffolding features. Note: this is a very early preview for scaffolding, many features do not exist yet so please do not be too disappointed when you are trying these out. We are tying to get features into your hands as early as possible so that is one side effect of this.

How to get started with scaffolding

I’ll show you how you can create a new project vNext web application in Visual Studio and then the modifications that are needed to get started with scaffolding. Currently the scaffolding does not work for empty projects, so I’ll start with the ASP.NET vNext Web Application template. We will add support for the empty template in a future release.

OK let’s get you started with scaffolding. The first thing we are going to do is to create a new ASP.NET vNext Web Application project. You can see a screenshot of the selected template below.

image 

After creating this project we need to make a few one-time changes to enable downloading our pre-release NuGet packages. You can do this using the Package Manager Settings button in the Package Manager Console. If you don’t see the Package Manager Console you can open it from View->Other Windows->Package Manager Console.

image

You should configure you’re new feed with the following values.

You can see the screenshot below of what the result should look like. Don’t forget to click Update after setting those values.

image 

Now that we have this configured we have access to the pre-release NuGet packages for ASP.NET vNext. To enable command line scaffolding there are a few edits to the project.json that you’ll need to make. The required changes are summarized below.

  1. Add "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-*" to the dependencies section
  2. Add "gen": "Microsoft.Framework.CodeGeneration" to the commands section
  3. Update alpha3/alpha2 to be * which will enable downloading the latest versions of each package

The final project.json should look like the following.

{"dependencies": {"EntityFramework.SqlServer": "7.0.0-*","Microsoft.AspNet.Mvc": "6.0.0-*","Microsoft.AspNet.Identity.EntityFramework": "3.0.0-*","Microsoft.AspNet.Identity.Authentication": "3.0.0-*","Microsoft.AspNet.Security.Cookies": "1.0.0-*","Microsoft.AspNet.Server.IIS": "1.0.0-*","Microsoft.AspNet.Server.WebListener": "1.0.0-*","Microsoft.AspNet.StaticFiles": "1.0.0-*","Microsoft.Framework.ConfigurationModel.Json": "1.0.0-*","Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0-*","Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-*"
    },"commands": {
        /* Change the port number when you are self hosting this application */"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000","gen": "Microsoft.Framework.CodeGeneration"
    },"frameworks": {"net451" : { },"k10" : { }
    }
}

Now that we have the project configured we will now go to the command line. There is some one-time setup there as well. I’ll get you started with that now.

From an admin command prompt execute the following command.

powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"

You should exit the command prompt after executing this command. Some environment variables are set that need to be applied before continuing.

Now we need to download the latest kvm package. To do this open a new command prompt (Note: for the next few steps do not use a PowerShell prompt) execute the following two commands.

set KRE_NUGET_API_URL=https://www.myget.org/F/aspnetvnext/api/v2

kvm upgrade

This will give us access to the latest version of kvm which is required for scaffolding. This will apply to the current session as well as future sessions for the command/PowerShell prompt. After executing this you should restart any instances of Visual Studio that are currently open so that Visual Studio can pick up that setting.

Now let’s get started with the actual scaffolding. For this sample I’ll show you how you can add a new model to your project and then scaffold some new content based on that. Let’s start by adding the Person class below to the project in the Models folder.

using System;

namespace WebApplication2
{
    public class Person
    {
        public int PersonId { get; set; }

        public string Name { get; set; }

        public bool BoolProperty { get; set; }
    }
}

Now that we’ve added the new model, let’s scaffold a controller and view to so that we can interact with it. In the command prompt you should navigate (cd) to the directory for the project (the directory that has the .kproj and project.json file). From there we will execute the following command.

k gen controller -m Person -dc PersonContext

Note: you could also use the fully qualified name for the model if you have more than one Person class. For example.

k gen controller -m WebApplication2.Person -dc WebApplication2.PersonContext

The parameters passed in indicate that the model (-m) Person and the data context (-dc) to be created is PersonContext. (To learn more about the options you can execute k gen controller --help.)

The command executed will generate some artifacts into your project. During generation the command line will report added/modified artifacts. In the screenshots below you can see the command line output. There is a screenshot of the new files in Solution Explorer as well.

image

image 

This is similar to the content that is generated for projects when using Visual Studio 2013. Now that you’ve generated these artifacts you can navigate to /Person to see the Index view and start interacting with this model. At this point you may want to play around with the views/controllers created in your project to get a sense for the updates. Now that we’ve gone through the basics I will wrap up this post and include some details on what’s next.

Summary

In this post I’ve shown how you can get started with ASP.NET vNext command line scaffolding. Our current support is pretty limited, but we are working hard to extend this support and to bring this functionality into Visual Studio. Keep an eye on this blog as well as http://asp.net/vNext for further updates. If you have any comments/questions please let us know in the comments section below.

Known Issues

  • We do not support scaffolding into an ASP.NET vNext Empty Application, only the ASP.NET vNext Web Application template works today
  • Formatting for scaffolded content is not ideal. After generating the content you can format the document using the Edit menu. In later releases we will format the generated content much better than we do today.

Sayed Ibrahim Hashimi | @SayedIHashimi


Customizing Web API controller selector

$
0
0

In the last few weeks we have encountered a customer reports of performance issues with their Web API applications.

When the 4th report exhibited the same phenomenon I figured it’s time to blog about it.

Why would you customize a controller selector? (hint – try not to)

It gives you a chance to control how the request gets routed. By default Web API uses the controller token from routing to select the controller. If you want a different behavior, such as selection based on an HTTP header, then you need to customize the controller selector.

Wait. Not really. This was true for Web API 1.0. In Web API 2.0 attribute routing and inline constraints were added, with further enhancements in Web API 2.1 and 2.2. Many of the scenarios once handled only by custom controller selectors could now be implemented using features of attribute routing.

Attribute routing allows you to use declarative templates and custom constraints directly on actions and controllers. This means that you are applying custom behavior in a few select places instead of affecting the behavior of the entire application. If instead you need to apply a custom behavior to all of your actions, attribute routing allows you to provide custom route discovery code. They still apply as normal attribute routes, so the rest of the system keeps functioning as default. The release notes for Web API 2.2 demonstrate a custom IDirectRouteProvider, which is used to customize attribute routes.

Most importantly, attribute routing doesn’t replace a core framework component so you don’t need to worry about concerns such as caching descriptors and API Explorer compatibility.

Here are some further samples for attribute routing:

Versioning with attribute routing

Attribute Routing

Back to IControllerSelector

I have seen developers use it to enable multiple controllers with the same type name but that are in different namespaces. I have seen it used for versioning controllers based on extra data from the request, such as in an HTTP header. Changing the controller selector for the above scenarios works well for the purpose of action selection, but might not work as well when you try to use the Web API help page or link generation. In your application that might be good enough for your purposes.

So say you still want to use conventional (non-attribute) routing and customize the controller selector. Go ahead, but watch out for the following problems.

What to watch out for

Let’s start by taking a look at the interface you will implement:

public interface IHttpControllerSelector{HttpControllerDescriptor SelectController(HttpRequestMessage request);IDictionary<string, HttpControllerDescriptor> GetControllerMapping();
}

Take a look at GetControllerMapping. The controller mapping says that a controller is mapped to a name. There is no way to specify the namespace or any more information, so if you are going to make controller selection decisions based on its namespace (like in the sample below), note that ApiExplorer is not aware of controllers with the same name but in different namespaces.

Next is the SelectController method. It returns an HttpControllerDescriptor, which seems innocent, but if you read through the constructor of that class, you will see that it calls Initialize() and then reflects over the controller attributes:

object[] attrs = type.GetCustomAttributes(inherit: false);

And then initializes a new controller settings, and initializes a new configuration.

Still doesn’t sound too bad?

With the default controller selector, this will happen just once because the descriptor is cached, but with a naïve customization this could happen on every request. This logic is relatively expensive, including many memory allocations, and a significant performance degradation can be measured. In some cases we have seen web services that could easily serve around 3000 requests per second, go down to less than a 1,000 just because of such a change.

One other thing to note is that calling the default constructor for HttpControllerDescriptor avoids instantiating the configuration, and can leave your application into an unexpected state. This constructor is marked in the documentation that it is for unit tests only and must not be used in production code.

So what to do

If all you are doing is customizing the controller name, just derive from DefaultHttpControllerSelector and override GetControllerName. The default controller selector will take care of caching the descriptor.

If you are implementing something more elaborate and you want to create your own descriptor be aware that you need to implement a caching mechanism, as the default implementation will not be sufficient.

Sample

Here is a sample that properly deals with controller selection (if not the side effects on API Explorer) and properly caches the controller descriptors:

http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs

Conclusion

Implementing an IHttpControllerSelector is something you don’t want to opt into lightly. But if you do, please consider caching and effects on other parts of the system.

How to customize scaffolding templates for ASP.NET vNext

$
0
0

Yesterday I posted the announcement for command line scaffolding in ASP.NET vNext. Shortly after we received a comment asking.

“Would be interesting to see how easy/hard it is to change the scaffolding template.”

For context in Visual Studio 2013/2012 you could customize the template content by copying files from c:\program files\ into your source project.

When I saw the comment come in, I wasn’t sure if the feature had been implemented yet or not. So I quickly created a sample to try it out. Unfortunately it wasn’t working. In the morning (11:30 so I’m using that term lightly) stand up I brought up the comment and asked about the status of the feature. Pradeep, the dev owner for this feature, confirmed that he had not yet implemented the feature. I asked him how easy/hard it would be and he said he would look into it. A few hours later he comes back and let’s me know that he got the feature implemented and checked in! Now that the build has completed and passed it’s available for everyone to try. So let’s move on to try it out!

When an ASP.NET vNext scaffolder is executed it’s common for those scaffolders to use templates to generate content into the project. It is easy to customize these templates on a per-project basis. Let’s get a new project created with scaffolding enabled so that we can customize the content. Follow these steps.

  1. Create a new ASP.NET vNext Web Application project (we don’t support Empty web just yet)
  2. Update project.json to add dependency for generators and the gen command
  3. Add a Person model which will be used for scaffolding

If you need more details on the previous steps checkout the previous post http://blogs.msdn.com/b/webdev/archive/2014/08/21/command-line-scaffolding-for-asp-net-vnext.aspx.

We have modified project.json to include the following for the generators.

"Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-*"

This will pull the highest version of 1.0.0 that is published on the NuGet repositories. The feature allowing templates to be overridden in the project exists in versions > 1.0.0.-alpha4-10177. The NuGet package actually contains the templates. This enables us to modify them easily and re-ship via NuGet. To customize the templates you’ll just copy the Templates folder from the NuGet package into the root of your project. For ASP.NET vNext, NuGet packages are stored on a per-user basis by default. On my machine, for the 10185 version,  that path is C:\Users\ibrahim\.kpm\packages\Microsoft.Framework.CodeGenerators.Mvc\1.0.0-alpha4-10185\Templates. After you add the templates folder to your project your Solution Explorer should look like the following image.

Screenshot 2014-08-22 16.35.24

The extension of these files is .cshtml. That is because we are using Razor as our templating language in ASP.NET vNext. Two reasons why we are using Razor here; It’s cross platform via ASP.NET vNext and because many ASP.NET developers already know Razor. For this project, you can edit the contents of these files to control what content is generated during scaffolding.

If you customize the contents of these files and you are re-generating some existing content using k gen you can pass the –f (force) switch to overwrite existing files. I modified these templates with the following changes.

  • For generated controllers: move using statements inside the namespace declaration
  • For generated views: modify html element to specify en-us and modify meta tags in the head

You can grab my samples from https://github.com/sayedihashimi/scaffolding-samples/tree/master/CustomizeScaffoldingTemplates/ if you are interested in following along or tweaking what I have. In the screenshot below you can see the customized controller template.

Screenshot 2014-08-22 16.58.38 

After making these changes in this project when you execute the command k gen controller -m CustomizeScaffoldingTemplates.Person -dc CustomizeScaffoldingTemplates the generator will use the customized templates instead of the ones shipped with the NuGet package itself.

That is pretty much it. Please try it out and let us know in the comments below what you think. You never know, it may end up being a new feature :)

Sayed Ibrahim Hashimi | @SayedIHashimi

Announcing the Release Candidates for Web API OData 5.3

$
0
0

The release candidate NuGet packages for ASP.NET Web API OData 5.3 are now live on the NuGet gallery!

Download this release

You can install or update the release candidate NuGet packages for ASP.NET Web API OData 5.3 using the NuGet Package Manager Console, like this:

  • Install-Package Microsoft.AspNet.OData -Version 5.3.0-rc -Pre
  • Install-Package Microsoft.AspNet.WebApi.OData -Version 5.3.0-rc -Pre

What’s in this release?

This release primarily includes great new features for Web API OData v4 as summarized below:

ASP.NET Web API OData 5.3 Release Candidate

Additional Documentation

Tutorials and other information about Web API OData are available from the ASP.NET web site (http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api).

Questions and feedback

You can submit questions related to this release on the ASP.NET Web API forums. Please submit any issues you encounter and feature suggestions for future releases on our CodePlex site.

Thanks and enjoy!

Farewell, EnableViewStateMac!

$
0
0

The ASP.NET team is making an important announcement regarding the September 2014 security updates.

All versions of the ASP.NET runtime 1.1 - 4.5.2 now forbid setting <%@ Page EnableViewStateMac="false" %> and <pages enableViewStateMac="false" />.

If you have set EnableViewStateMac="false" anywhere in your application, your application will be affected by this change and you should read on. Otherwise there is no action you must take, and the behavior of your application will not be affected.

In December 2013, we released a security advisory warning that the configuration setting EnableViewStateMac=false is dangerous and could allow an elevation of privilege attack against the web site. At the time we issued a statement that the next version of the ASP.NET runtime would forbid setting this switch, and indeed when ASP.NET 4.5.2 was released it forbade applications from setting this insecure switch.

Along with the December 2013 advisory, we issued KB 2905247. This KB was an optional patch that customers could install if they immediately needed to deploy the "forbid setting this dangerous switch" logic throughout their infrastructure but couldn't wait for ASP.NET 4.5.2.

Today we are enforcing this previously optional patch for all versions of the ASP.NET framework. If you are running the ASP.NET framework on your machine, this behavior will be picked up automatically the next time you check for updates.

We're aware that this change could affect a substantial number of web applications. It is never our intention to break web applications in an in-place update, but we felt it necessary to address this issue head-on due to the prevalence of misinformation regarding this switch and the number of customers who are running with it set to an insecure setting.

Just what is a "view state MAC" in the first place?

MAC in this context stands for message authentication code, which is a cryptographic code generated by the server and appended to the __VIEWSTATE hidden form field. The MAC ensures that the client hasn't tampered with these fields.

When EnableViewStateMac is set to true, this code is validated by the server when the client submits the __VIEWSTATE hidden form field during post back. This setting has been enabled (true) by default for all versions of ASP.NET.

Why forbid setting EnableViewStateMac=false?

We're forbidding it because it is never safe to set EnableViewStateMac="false". As called out in the December 2013 advisory, an attacker may be able to leverage this setting to upload and execute arbitrary code on the web server. This would grant her complete control over the web application subject to the permissions of the web worker process.

After the initial advisory was released, we received questions from customers regarding conditional cases. What if I have set EnableViewState="false"? What if I'm running over SSL? What if I've only set this on one page and it's an admin-only page? What if my site just runs on the local intranet?

In all of these cases, the answer remains the same: not a single one of these "what ifs?" will prevent an attacker from exploiting this vulnerability. The web site is still open to remote code execution attack as long as EnableViewStateMac="false" is present.

Will installing this patch change break my application?

If you have set EnableViewStateMac=false anywhere in your application, this change will affect you. Whether the new behavior breaks the application is scenario-dependent. If the reason the MAC was disabled was to enable cross-page posts, the application will generally continue to work correctly. If the reason the MAC was disabled was to avoid synchronizing the <machineKey> setting in a web farm, the application will probably break. See the below sections for more information on these particular scenarios.

If you are using EnableViewStateMac=true throughout your application, this change will not affect you.

Additionally, if you never touch the EnableViewStateMac switch at all in your application, this change will not affect you. Remember: the default value for this setting is true, and this change only affects applications where the developer has explicitly set the value to false.

What about cross-page posts?

Once KB 2905247 is installed, the ASP.NET framework treats cross-page posts specially to minimize the risk of errors at postback time. However, setting <form action="some-different-page.aspx" /> has never been the recommendation for cross-page posts in WebForms. Consider using PostBackUrl instead to make this scenario work.

What if my servers are in a farm?

You are required to create a <machineKey> element and synchronize it across machines in your farm. See KB 2915218, Appendix A for full instructions on how to generate a <machineKey> element. That appendix contains a block of code that you can copy and paste into a PowerShell window. Then you can run the Generate-MachineKey command from within the PowerShell window to generate a <machineKey> element.

PS> Generate-MachineKey
<machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />

You can then copy and paste this <machineKey> element into your application's Web.config file.

See KB 2915218, Appendix A for more information on the parameters that can be passed to the Generate-MachineKey function. See also Appendix C for information about using protected configuration to encrypt the contents of the <machineKey> element in the Web.config file.

Note: these keys are sensitive. Anybody who has access to them could end up with full administrative control over your web application. For this reason we suggest that you never use an online "click here to generate a <machineKey> element" utility. Only ever use <machineKey> elements that you generated yourself on your own machine. And use caution not to leak these keys in public places like online forums.

What if I encounter MAC validation errors as a result of this change?

We updated the "validation of view state MAC failed" error message to contain a link to KB 2915218, which lists common reasons that the MAC verification step might fail. Check that article to see if it calls out an item specific to your scenario.

Are there any other behavioral changes as a result of this?

Yes, there is a minor behavioral difference as a result of this patch, but this behavior will not break existing applications. If a __VIEWSTATE form field is written out to the response, it will now be accompanied by a new form field <input type="hidden" name="__VIEWSTATEGENERATOR" ... />. This new form field is used by the ASP.NET runtime to help determine whether a postback is going to the same page or is cross-page. It's similar in concept to the __PREVIOUSPAGE form field that is written when a control's PostBackUrl property is set.

Is today's rerelease of KB 2905247 different than the original December 2013 release?

Yes. The original release of the patch contained a bug where the value of the Page.IsPostBack property could be incorrect. The new version of the patch released today contains a fix for this issue.

If you are a server administrator and you have already deployed an earlier version of the KB, it is recommended that you deploy the latest version so that you get this bug fix.

What versions of ASP.NET is KB 2905247 applicable to?

This KB is applicable to all versions of ASP.NET from 1.1 through 4.5.1. The KB is not applicable to ASP.NET 4.5.2 or later, as the ASP.NET runtime already contains the patch built-in starting with version 4.5.2.

Why is KB 2905247 being made available on Windows Update now? Why not back in December 2013?

There are many factors that are taken into account when making a decision like this: the severity of the vulnerability, the number of customers who are vulnerable, and the impact of patching affected customers' machines.

In the case of this specific vulnerability, the official Microsoft guidance many years ago was that web applications could sometimes get away with setting EnableViewStateMac="false" in certain cases and that performance would be improved if the application were to do this. The original guidance was bad: this setting is categorically insecure, and this setting doesn't improve performance. We have since corrected this guidance, but the damage was done. There was now a very large number of ASP.NET web sites which ran with this insecure setting.

Given the severity of the issue, when we released the original advisory back in December 2013, we wanted to push out the update to all customers worldwide and fix the issue immediately. However, given the large number of customers involved and the potential impact this change brings, we didn't want to risk surprising customers with something this large. So we compromised: release an advisory stating that the configuration is insecure, allowing customers to proactively (rather than reactively) fix their sites. At the same time we made available to system administrators an optional patch which they could deploy on their servers to close the vulnerability outright.

It has now been nine months since the original advisory. This has given customers who wanted to secure their sites proactively ample time to test and deploy their changes. For our many customers who simply depend on the normal Windows Update / Microsoft Update mechanisms, however, the time has come for us to make sure that their applications are also protected against this.

Further resources

More information about the patch can be found at the original advisory page or on the Microsoft Support site.

Information about resolving "validation of view state MAC failed" error messages can be found on the Microsoft Support site under KB 2915218.

The ASP.NET team also maintains a document on common mistakes we see in typical ASP.NET applications and they can be corrected.

Finally, you can get in touch with us via the ASP.NET web site. We're also active on StackOverflow. Prefer Twitter instead? The team is available at @aspnet.

Thanks for reading, and happy coding!

Announcing Microsoft.AspNet.Facebook 1.1 beta

$
0
0

This past June we released the first version of the Microsoft.AspNet.Facebook NuGet package and the corresponding Visual Studio template. Today we released an update to this package: Microsoft.AspNet.Facebook1.1 beta. In this release, we enabled better support for the Safari browser and added a new feature that gives developers the ability to add custom logic for browsers that do not have cookies enabled. The Visual Studio template that uses this updated package will be released soon. To read more about the features in the 1.0 package, please see the blog post from the initial announcement. The Visual Studio 1.0 template can be found here.

The Microsoft.AspNet.Facebook package tracks permissions requested of the user in a cookie to determine skipped permissions. Prior to this update, skipping optional permissions for ASP.NET Facebook Applications resulted in infinite loops when run in Safari. This was happening because Safari blocked cookies that the Microsoft.AspNet.Facebook package attempted to create. Because cookies were not created, the package did not have a way to determine which permissions were skipped so the permissions dialog would repeat infinitely. Also, there was no error message that could inform the user what was happening. We made this experience much better in this release. Developers can now redirect to an error page when cookies are not enabled.

Features added in this release

CannotCreateCookieRedirectPath Configuration

You can set the CannotCreateCookieRedirectPath in web.config to control where users are redirected when the framework cannot create cookies. If the configuration value is set, the framework redirects the user to the error page; otherwise, it redirects to https://www.facebook.com.

clip_image001[3]

OnCannotCreateCookies Hook

As the name suggests, this hook gets called if the Microsoft.AspNet.Facebook package cannot create cookies due to browser restrictions or the user’s settings. By default, it looks for a redirect path provided by the CannotCreateCookieRedirectPath in FacebookConfiguration.

NOTE: Once this hook gets called NO other prompts are triggered unless the default OnCannotCreateCookies logic is overridden.

Developers can override this hook to add their custom logic if needed.

A few examples are mentioned below.

Set permissionContext.Result to null

Instead of redirecting to an error page or https://www.facebook.com, this takes the user directly to the app without prompting for permissions.

protectedoverridevoid OnCannotCreateCookies(PermissionContext permissionContext)
{
    permissionContext.Result = null;
}
Redirect to an action

The developer can redirect to an action when this hook gets called.

protectedoverridevoid OnCannotCreateCookies(PermissionContext permissionContext)
{
    permissionContext.Result = newRedirectToRouteResult(
        newRouteValueDictionary
        {
            { "controller", "home" },
            { "action", "foo" }
        });
}
Do NOT set permissionContext.Result to ShowPrompt

Setting permissionContext.Result to ShowPrompt within the OnCannotCreateCookies hook causes infinite prompt loops.

Enabling consistent behavior with cookie enabled browsers

The OnPermissionPrompt and OnCannotCreateCookies methods can be overridden to enable consistent behavior between cookie and non-cookie enabled browsers. In such cases, the requested permissions (that would normally be stored in a cookie) should be persisted to a database. Here is one way to do that.

This example uses EntityFramework to access the database. It creates a class called FacebookPermission to store permissions and a class called FacebookPermissionDbContext for storing permissions in a database.

To get started, open Visual Studio 2013, create a new ASP.NET Facebook application. Then, add the following classes to the project:

publicclassFacebookPermission
{
    [Key]
    publicint FacebookPermissionId { get; set; }
    publicstring User { get; set; }
    publicstring RequestedPermissions { get; set; }
}
publicclassFacebookPermissionDbContext : DbContext
{
    public FacebookPermissionDbContext()
        : base("DefaultConnection")
    {
    }

    protectedoverridevoid OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

   publicvirtualDbSet<FacebookPermission> FacebookPermissions { get; set; }
}

Next, create a custom authorization filter that derives from FacebookAuthorizeFilter and override the OnPermissionPrompt and OnCannotCreateCookies methods.

OnPermissionPrompt reads RequestedPermissions from the database and derives skipped permissions. Based on these permissions either OnDeniedPermissionPrompt or OnPermissionPrompt will be invoked.

The OnCannotCreateCookies method persists the requested permissions to the database and calls OnDeniedPermissionPromt on the base class

publicclassCustomAuthorizeFilter : FacebookAuthorizeFilter
{
    privatestaticFacebookPermissionDbContext db = newFacebookPermissionDbContext();

    public CustomAuthorizeFilter(FacebookConfiguration config)
        : base(config)
    {

    }

    protectedoverridevoid OnPermissionPrompt(PermissionContext context)
    {
        FacebookPermission storedPermission = db.FacebookPermissions.Where(p => p.User == context.FacebookContext.UserId).FirstOrDefault();
        if (storedPermission == null)
        {
            // This calls into base implementation, you can replace this with your own logic.
            base.OnPermissionPrompt(context);
        }
        else
        {
            IEnumerable<string> requestedPermissions = storedPermission.RequestedPermissions.Split(',');
            IEnumerable<string> declinedPermissions = context.DeclinedPermissions;
            context.SkippedPermissions = requestedPermissions.Except(context.DeclinedPermissions);
            bool deniedPermissions = context.MissingPermissions.Where(
                permission => context.DeclinedPermissions.Contains(permission) ||
                              context.SkippedPermissions.Contains(permission)).Any();

            if (deniedPermissions)
            {
                // This calls into base implementation, you can replace this with your own logic.
                base.OnDeniedPermissionPrompt(context);
            }
            else
            {
                // This calls into base implementation, you can replace this with your own logic.
                base.OnPermissionPrompt(context);
            }

        }
    }

    protectedoverridevoid OnCannotCreateCookies(PermissionContext context)
    {
        FacebookPermission storedPermission = db.FacebookPermissions.Where(p => p.User == context.FacebookContext.UserId).FirstOrDefault();
        IEnumerable<string> requestedPermissions = context.RequiredPermissions;
        string permissionString = String.Join(",", requestedPermissions);
        if (storedPermission == null)
        {
            db.FacebookPermissions.Add(newFacebookPermission
            {
                User = context.FacebookContext.UserId,
                RequestedPermissions = permissionString
            });
        }
        else
        {
            if (String.IsNullOrEmpty(storedPermission.RequestedPermissions))
            {
                storedPermission.RequestedPermissions = permissionString;
            }
            else
            {
                IEnumerable<string> unPersistedPermissions = requestedPermissions.Except(storedPermission.RequestedPermissions.Split(','));

                foreach (string p in unPersistedPermissions)
                {
                    db.Entry(storedPermission).State = EntityState.Modified;
                    storedPermission.RequestedPermissions = String.Join(",", storedPermission.RequestedPermissions, p);
                }
            }
        }
        db.SaveChanges();

        // This calls into base implementation, you can replace this with your own logic.
        base.OnDeniedPermissionPrompt(context);
    }
}

Open FacebookConfig.cs and replace

GlobalFilters.Filters.Add(newFacebookAuthorizeFilter(configuration));

with

GlobalFilters.Filters.Add(newCustomAuthorizeFilter(configuration));

You can find the complete solution here.

NOTE: This is a guidance sample for simple one page Facebook application. For multi-page Facebook applications, you may have to add additional logic.

Conclusion

Please try this feature and let us know what you think. To find or file issues do so here.

Viewing all 7144 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>