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

Making It Better: Updates for ASP.NET 5 in Visual Studio 2015 CTP 5

$
0
0

It's been about two months since we released the first beta of ASP.NET 5, and today we happy to announce that ASP.NET 5 Beta2 is available. For developers using Visual Studio, you'll find great new tools to support and enhance your development process.  All ASP.NET developers will be able to take advantage of a new runtime and many product quality improvements.

You can download and install Visual Studio 2015 CTP5 by following the link at the top of the http://asp.net/vnext page.  If you want to try ASP.NET 5 with an alternate editor or on Mac or Linux, just follow the instructions on our ASP.NET GitHub project Home repo to get setup using just a command prompt.  If you already have ASP.NET installed and only want to update your packages using NuGet you can simply run this command at the command prompt:

kvm upgrade 

and the latest version of the ASP.NET runtime will be downloaded from NuGet and installed for you to use on your workstation.

There are a ton of great new features available with this preview release, and in this post we're going to cover a few of the ones that we have heard the most feedback about. You can also read about all of the new runtime enhancement by checking out the ASP.NET 5 Beta2 release notes on GitHub.

Reference existing projects from ASP.NET 5 projects

In previous preview releases you could only reference other ASP.NET 5 projects from an ASP.NET 5 project. You can now reference your existing projects from an ASP.NET 5 project using the Add Reference dialog. 

 

Run and debug commands defined in project.json

In addition to being able to run and debug your project you can now also run and debug any command defined in your project.json file directly from Visual Studio.

 

The default project.json for the ASP.NET 5 Starter Web template includes commands for self-hosting, MVC scaffolding, and for Entity Framework migrations.

    "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",

        "ef": "EntityFramework.Commands"

    },

 

This update will allow you to continue running in Visual Studio if you don't want to bring up a command prompt to execute these commands. The new "gen" command allows developers with any editor to scaffold ASP.NET MVC components easily at the command line.  Here's a quick example of how easy it is to generate an MVC Controller:

Select which browser to use when running or debugging

Select which browser you want to use (ex. IE, Chrome, Firefox, etc.) when running or debugging an ASP.NET 5 web application from within Visual Studio.

 

Summary

We hope you enjoy these new improvements.  Some of these changes have been implemented due to the feedback we received.  Remember: we are working with the community to ensure that this is the best release of ASP.NET yet.  Get involved, and join the conversation on our GitHub project to let us know what you think!


Debugging ASP.NET 5 framework code using Visual Studio 2015

$
0
0

In the previous versions of ASP.NET it was possible to debug certain parts of the framework stack but setting up the development environment and compiling all the binaries was not the easiest task. ASP.NET 5 changes that and makes debugging framework code as easy as debugging your own application. This article shows how to debug into the ASP.NET 5 framework code using Visual Studio 2015.

Before getting into the How-To part, there is one limitation that you have to understand: you must not mix different versions of the runtime and/or packages. Trying to debug the latest MVC packages using an old runtime might be possible but there is no guarantee that it will work, or trying to use Beta2 and Beta3 packages in the same application can lead to some very strange compilation errors. The recommendation is that if you use a BetaX (X = number) packages, X must be the same for all packages and runtime, while if you using the latest development bits everything must be from the development branches/feed.

When you create a new ASP.NET 5 application and debug it you will notice that, like in the previous versions, you are not able to step into framework code. If you look at the modules that are loaded, you can see which of them have their symbols loaded and which not. In addition, you can see from where each module was loaded. (To open the Modules window while in a debug session navigate to Debug -> Windows -> Modules).

How to get the source code for ASP.NET

For this blog post, I am going to use MVC as the framework component being debugged. MVC and the rest of the ASP.NET 5 framework components are available in GitHub. To get the source code for MVC, you have to clone the MVC repository (downloading it as a zip archive does not suffice because the tags are not included, more on that in the next paragraph).

D:\debug>git clone https://github.com/aspnet/mvc
Cloning into 'mvc'...
remote: Counting objects: 24774, done.
remote: Compressing objects: 100% (5542/5542), done.
remote: Total 24774 (delta 18951), reused 24354 (delta 18617)
Receiving objects: 100% (24774/24774), 6.91 MiB | 3.40 MiB/s, done.
Resolving deltas: 100% (18951/18951), done.
Checking connectivity... done.
Checking out files: 100% (2072/2072), done.

In the beginning of the article, I mentioned that you must have matching packages and source code. You can see in Visual Studio that all the packages are from the Beta2 release. When you clone an ASP.NET GitHub repository, it defaults to the dev branch. That is fine if you are using the latest packages and runtime from thech dev feed, or if you compile everything yourself. Otherwise, you will have to sync to the commit corresponding to those bits. When we have a major release (Beta1, Beta2, etc.) we tag the particular commit that was used to produce the bits. Using the git tag command, you can see the available tags:

D:\debug>cd mvc
D:\debug\mvc>git tag
6.0.0-alpha2
6.0.0-alpha3
6.0.0-alpha4
6.0.0-beta1
6.0.0-beta2

As the tag name suggests, the Beta2 bits correspond to the 6.0.0-beta2 tag. Sync to that tag using the git checkout <tagname> command:

D:\debug\mvc>git checkout 6.0.0-beta2
Note: checking out '6.0.0-beta2'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 2a57f93... Updating Razor to not use K.Roslyn

Now that we have the sources for the packages used by the application, we can configure the application to use them.

Using the local source code instead of the official binaries

In ASP.NET 5 the unit of deployment is the NuGet package. Also, ASP.NET 5 uses Roslyn under the hood and it is able to compile source code on the fly, without requiring the user to provide binaries compiled a priori.

When you want to debug into the source of another library, you specify where the source code for the package containing that library is. If the runtime finds a valid project, it will use it instead of the actual package coming from NuGet or MyGet. An ASP.NET 5 solution, has a global.json file in the root folder. Inside this file, you can specify where the runtime should look for source code. By default it only looks at the src and test folders belonging to the solution.

To use the MVC code downloaded earlier, you have to add the path to MVC’s src folder in global.json. That’s it, now you can debug MVC! Just run the run the application. Remember to revert the changes to global.json, especially absolute paths, before checking in to source control.

The content of the global.json file:

{
  "sources": [
    "src",
    "test",
    "d:/debug/mvc/src"
  ]
}

The runtime decides which package to load using a naive algorithm. When a NuGet dependency (a package) is loaded:

  1. If any of the source code locations specified in global.json contains a folder with the same name as the package (e.g. Microsoft.AspNet.Mvc) and that folder contains a file named project.json, it will use that folder and the source files inside it.
  2. Otherwise, the compiled binary from the packages folder is loaded.

After you add the path to MVC’s source code, you will see that Visual Studio automatically adds the MVC projects to your solution. Also, if you look at your project’s references node, you will notice that Microsoft.AspNet.Mvc has a different icon and it shows that it was loaded from a different location:

If you start debugging and look at the loaded modules, you will notice that Microsoft.AspNet.Mvc is no longer loaded from the packages folder and that symbols are now available:

Behind the scene, MVC was compiled from sources when the application started and the resulted binaries were used instead.

Now, it is time to debug. Add a break point anywhere in the MVC code and it should be hit when the code is executed:

If you are not yet excited about this amazing new feature, let me add a bonus capability. If you change the MVC code in one of the projects added to the solution and restart the application, it will use the modified MVC. Go ahead, try it! If you fix an issue or improve the framework, you can even send a pull request (see the contributing guidelines for more information).

Troubleshooting

We know that sometimes things don’t work as smooth as described here. Below are the most common mistakes that we have seen:

  1. You are using development packages with old bits.Look at the project References node and make sure that all packages have the same version if using released bits.
  2. You are using an older/newer runtime. Using the kvm command line tool (installed separately from the Home repository), you can see which version of the runtime you are using. kvm list will show which version is currently active (the one marker with *). You can select a different runtime version than the active one, for a particular project, from the Project Properties page in Visual Studio.
    D:\debug\mvc>kvm list
    
    Active Version     Runtime Architecture Location                        Alias
    ------ -------     ------- ------------ --------                        -----
           1.0.0-beta2 CLR     amd64        C:\Users\victorhu\.kre\packages
      *    1.0.0-beta2 CLR     x86          C:\Users\victorhu\.kre\packages default
           1.0.0-beta2 CoreCLR amd64        C:\Users\victorhu\.kre\packages
           1.0.0-beta2 CoreCLR x86          C:\Users\victorhu\.kre\packages
    
  3. Global.json is not actually pointing to the correct sources. Make sure the path in global.json is pointing to a cloned repository. Also, notice that it is easiest to use forward slashes (/) because they work on all platforms. If you use backslashes (\) you have to instead use double backslashes (\\) as directory separator, and it will work only on Windows.

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 5, please provide feedback in GitHub or the ASP.NET 5 forum. If you ask a question in Stack Overflow, use the asp.net-5 tag.

ASP.NET MVC 5.2.3, Web Pages 3.2.3 and Web API 5.2.3 Release

$
0
0

While the MVC team is working hard on MVC 6 as part of the ASP.NET 5 effort, we also keep working on the 5.x packages. Today we are releasing ASP.NET MVC 5.2.3, Web Pages 5.2.3 and Web API 5.2.3.

This release addresses 13 issues. Here is the full list.

Highlight of issues fixed

Web API Issues

2092 Significant performance improvement in the default overload for System.Net.HttpFormatting.ReadAsAsync by caching the default JSON formatter. This can result in improvements of 100s of milliseconds on the second call to ReadAsAsync (or similarly to the write method).

2103 Batch's inner request's Url not being decoded in WebHost scenarios.

2101 Error parsing MIME multipart when using irregular mime types

MVC Issues

2155 Remote attribute does not work boolean fields and Html.CheckBoxFor

2081 Performance improvement in OutputCacheAttribute for child action

2136 Attribute routing does not set ControllerContext.IsChild correctly

2172, 2048– Unobtrusive validation fixes

MVC and Web Pages Issues

2085 Performance improvement in rendering Razor views

2119 Performance improvement in rendering attributes in Razor

Shout Out

We want to convey a big thank you to Nick Craver and Marc Gravell, who reported two of the performance issues we resolved in this release and provided a pretty cool Pull Request to fix one of them.

Issue 2085 in detail

Issue 2085 was about the fact the MVC copied ViewData for partial views, and templated helpers. In a reasonably large page with a reasonable amount of data in the ViewBag this proves out to be rather costly. We are now using a copy on write strategy instead. We took this improvement over to MVC 6 as well.

The Test

We built a test site, that put about 50 items in the ViewBag. For each of these items we rendered a partial view. This is similar to having 50 templated helpers (such as DisplayFor and EditorFor) used on a page.

We ran two types of tests:

1. Load the site with a constant stream of requests at the rate of 100 requests/second, and compare memory utilization and garbage collection characteristics for MVC 5.2.2 and MVC 5.2.3.

2. Load the site with maximum amount of requests and compare the requests/second rate between MVC 5.2.2 and MVC 5.2.3.

Results

Test 1

The interesting data in this scenario as the reduction of time spent in GC and reduction in overall allocations. Note that Gen2 garbage collection count went down from 57 to 1! And the time in GC was sliced almost three fold.

Area

5.2.2

5.2.3

Delta %

Total request (count)

2,911

2,869

 

Trace duration (seconds)

30

30

 

Request/second

97.03

95.63

 

GC CPU Samples (msec)

12,139.00

6,682.00

45%

Total allocations (MB)

    18,049.79

12,602.08

30%

Total GC Pause (msec)

1,103.20

663.00

40%

Gen0 GC (count)

76

107

-41%

Gen1 GC (count)

317

106

67%

Gen2 GC (count)

57

1

98%

CPU / request (msec/req)

4.17

2.33

44%

% CPU Time spent on GC

6.40%

2.30%

64%

Test 2

In this scenario the number of requests/sec went up 70%, and less time was spent in GC.

Area

5.2.2

5.2.3

Delta %

Total request (count)

5,246

8,895

 

Trace duration (seconds)

30

30

 

Request/second

174.87

296.50

70%

GC CPU Samples (msec)

39,615

34,704

12.40%

Allocations/Request (MB/Request)

6.382

4.739 

34.66%

Total GC Pause (msec)

2,974.60

3,215.70

-8.11%

Gen0 GC (count)

76

99

-30.26%

Gen1 GC (count)

317

368

-16.09%

Gen2 GC (count)

57

45

21.05%

CPU / request (msec/req)

87.42

155.63

-78.03%

% CPU time spent on GC

8.60%

7.80%

9.30%

 

We hope you enjoy these performance and functionality improvements!

Improve performance by optimizing queries for ASP.NET Identity and other Membership Providers

$
0
0

If your application is using ASP.NET Identity or other membership systems such as SQL, Universal or Simple membership, then you might be running into the following issue.

If you are using ASP.NET Identity 2.x, the query for getting profile values (among other things) uses the UPPER() function on Username - this causes any indexes on username to be ignored.

The workaround is to add a computed column with the call to UPPER(Username) and a database index over it. This is extremely effective in improving the performance and it does not require any changes to the application or updating ASP.NET Identity Framework.

Here are sample SQL commands that you would need to run on the database (table and column names may be different based on your app):

SQL Query for ASP.NET Identity 2.1

ALTER TABLE dbo.AspNetUsers
ADD NormalizedName  AS UPPER(UserName);

CREATE NONCLUSTERED INDEX
[IX_NormalizedName] ON [dbo].[AspNetUsers] ([NormalizedName] ASC);

If you are using ASP.NET Universal Providers, the query for getting profile values (among other things) uses the LOWER() function on Username – so you have to do the following.

SQL Query for ASP.NET Universal Provider

ALTER TABLE dbo.Users
ADD NormalizedName  AS LOWER(Username);

CREATE NONCLUSTERED INDEX
[IX_NormalizedName] ON [dbo].[Users] ([NormalizedName] ASC);

Note:

Although we did it only for Username, the same principle should apply to other columns where you are doing lots of lookups on.

You can use LOWER() or UPPER() based on what queries are being executed.

You can follow the same steps for SQL Membership and Simple Membership as well.

Customers have seen significant improvements in performance with this workaround so we would recommend you to implement this in your application.

Introducing the Visual Studio 2015 Extension for ASP.NET Project Templates

$
0
0

In Visual Studio 2013, there were a handful of templates that supported developing ASP.NET projects with various frameworks and data structures.  Some of those project templates from the Visual Studio 2012 era have been removed from the Visual Studio 2015 install and added to the Visual Studio Extension gallery as the ASP.NET Project Templates extension for Visual Studio 2015.

This was primarily done for the following reasons:

  • Reduce the number of templates that we ship in the box, thereby reducing the installer size.
  • Update templates more frequently. For example, Facebook makes changes to their application development APIs that were incompatible with the MVC Facebook support.  To maintain support, we updated the template outside of a Visual Studio release.

What templates are included?

  • ASP.NET Dynamic Data Entities Project (.NET 4 and above)
  • ASP.NET Dynamic Data Linq Project (.NET 4)
  • ASP.NET MVC Facebook Project (.NET 4.5 and above)
  • ASP.NET Web Forms Project (.NET 4 only)
    • Note: This template was using Universal Providers. Starting Visual Studio 2013, all templates including Web Forms were updated to use ASP.NET Identity and you can create these templates in VS 2015

What about other templates from VS 2013?

All the other templates from VS 2013 are still part of VS 2015.

You can create ASP.NET Web Forms, MVC 5, Web API 2, SPA, Azure Mobile Service projects, using the One ASP.NET dialog. This is the same as Visual Studio 2013.

How to install & create project?

  • Install the ASP.NET Project Templates extension from the online gallery or by going to the Extensions dialog (Tools – Extensions & Updates) in Visual Studio and searching for “ASP.NET Project Templates”.

vsdialog

  • Once you install the extension, the project templates will show up in the File - New Project - Web node as shown below.

List of templates

You can now create a project as you normally would and use the template.

Summary

Web sites and technologies are evolving quickly. We want to be able to deliver to you project templates that use new technologies and techniques on a more timely basis, and to do this we have enabled the ASP.NET Project Template extension.  If you are looking to work with Facebook apps, Dynamic Data, or Web Forms with the Universal Providers, try out the extension and let us know what you think.

Open sourcing and releasing ASP.NET Identity 2.2.0

$
0
0

We are releasing the final version of ASP.NET Identity 2.2. The main focus in this release was to fix bugs and address performance issues.

Open source

We have also made the source code publicly available on aspnetidentity.codeplex.com and will be taking contributions to the project. Check out the project home page for more details.

Note: This is the source code for ASP.NET Identity 2.2. ASP.NET Identity 3.0 is part of ASP.NET 5 and the source code is on GitHub.

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.2.0 

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

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

What’s in this release?

This query has the list of all issues fixed in this release. The main issues fixed are as follows.

1991 Additional IdentityDbContext constructor

2278 ASP.net Identity ChangePassword is inefficient on the database

Samples/ Documentation

Migrating from ASP.NET Identity 2.1.0

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

Give feedback and get support

What’s next?

Apart from working on Identity 2, we are also working on the next version of Identity (Identity 3.0 which is part of ASP.NET 5).

ASP.NET 5 Updates and other improvements for Web Developers in Visual Studio 2015 CTP 6

$
0
0

It's time for another Visual Studio 2015 CTP, and with the CTP 6 release in February 2015 you should find a number of improvements that every web developer will enjoy. In this article we'll review the new features and improvements in ASP.NET 5 and the Visual Studio editor improvements delivered in CTP 6. For a complete list of the ASP.NET 5 runtime improvements check out the release notes on GitHub at https://github.com/aspnet/Home/releases/tag/v1.0.0-beta3.  You can download the new Visual Studio CTP 6 from VisualStudio.com

New Project Templates

We've organized the New ASP.NET Project dialog a bit. Now, when you want to start a new ASP.NET 5 project, you start by selecting 'File - New Project - Web - ASP.NET Web Application' and the below set of project templates are displayed.

Notice that we have added a grouping for the ASP.NET 4.6 templates that you're probably already familiar with, and the new ASP.NET 5 preview templates. We hope this makes it easier to discern which templates are new in this version and which templates are those you've been working with previously.

The Starter Web template has been updated with information about how to get started building ASP.NET applications that can run on Windows, Linux, and OSX. The home page now shows a bootstrap carousel with information about this and a whole lot more:

The new Web API template is introduced in this release, and it omits all of the extra HTML and razor markup that MVC provides so that you can focus on simply writing a solid API. Start here if you want to build an API with static content, or even as a starting point for your next single-page-application.

Task Runner Explorer

For JavaScript developers and automation of tasks, the task runner explorer has received a design update. We've moved the toolbar from the top to the left side and introduced some new buttons.

The new buttons allow you to refresh the contents of the current file, toggle the force flag when running a task, and toggle the verbose flag for a task. In the sample image, we've enabled verbose reporting for executing the grunt-bower task in a default ASP.NET project.

System References are back

You can now easily add references to system assemblies using the Add References dialog, which will make the appropriate modifications to your project.json file:

We are also hard at work to enable support for adding references to user assemblies for a future preview release. 

ASP.NET Project properties page improvements

Up until now, all changes to the behavior of a project went through manual updates to the content of the project.json file. There were a few items that could be updated using the Visual Studio user interface, but they were the minority. With this update, we have added configuration options to the project properties window that will allow you to configure the application and the debug time experience.

In the debug properties window we can now define multiple debug profiles that you want to be able to run your web project under. Each profile lets you specify an executable or a command in your project.json file that you could execute. There are separate arguments, environment variables, options to launch a browser, and the ability to pin a specific K run-time to be used with your debug profile.

Grunt, Bower, npm and Gulp

There are some new updates in the editor for parsing and managing grunt, gulp, bower, and npm configuration files. We are now providing better intellisense support for these file formats as well as enforcing JSON schemas for those tools. With the addition of byte-order-mark processing in these files, you should have no problems transporting them between Windows, Linux, and OSX operating systems.

If you're like me, you hated having to re-run grunt or gulp tasks each time you changed npm or bower configurations. The project.json file had automatic restore built in for NuGet, so why can't we have it for bower and npm? Yes... yes you can now have it for bower.json and package.json too. Each time you save these files, we will restore new packages immediately in the background for you.

We know that developers enjoy working with the solution explorer. We've made it easier to update and uninstall bower and npm packages in that panel with a pair of new context menu options:

We placed these options where it made sense for developers who have been using Visual Studio for a long time, and are used to being able to remove references from their projects with some mouse gestures in their solution explorer.

Command-line tool updates

The K Package Manager (KPM) tool has been update to rename some of the existing subcommands and to add a couple of new ones:

Old NameNew NameDescription
packbundleBundle application for deployment
build packBuild NuGet packages for the project in a given directory
-buildBuild assemblies for the project
-packagesManage local and remote packages folders
-listPrint the dependencies of a given project

The pack subcommand now matches the pack subcommand for nuget.exe to help avoid confusion. The build subcommand now produces just the raw assemblies without putting them into a package.

The packages and list subcommands are new. You can use the packages subcommand to sync a packages folder with a remote source. The new list subcommand will show you all of the packages your project depends on and which components are bringing in the dependency.

Custom Powershell tasks when publishing a Website

Have you had tasks that you want to be executed during your web site publication process? We've added a checkbox in the publish website wizard that will generate a Powershell script that you can customize and use to publish your website:

With that box checked, an script is generated with the name YOUR-PUBLISH-PROFILE-publish.ps1 in the Properties/PublishProfiles folder of your project. You are then welcome to customize this script to your needs, and Visual Studio will use that script when publishing using that profile.

Identity Updates

CTP 6 introduces various improvements and new features in the way in which we help you to handle authentication in your ASP.NET projects. Look for a more detailed update in the next days, but just to whet your
appetite:

  • We now have OpenID Connect and OAuth2 bearer token middleware components you can use with ASP.NET 5. We will publish new samples soon. No templates support (yet).
  • The ASP.NET 4.6 templates have been updated: the authentication logic they generate is now based on the OWIN middleware and OpenId Connect, instead of Windows Identity Foundation.
  • The “Change Authentication” dialog takes better advantage of the built in identity management features in Visual Studio 2015. Furthermore, it enables you to add delegated permissions to your app
  • The authentication logic generated via the ASP.NET 4.6 templates is now the same as the one generated by the “Configure Azure AD Authentication…” dialog, allowing you to modify your authentication settings at any time of a project lifetime

New HTTP client-role API

This CTP includes the latest implementation of the new System.Net.Http.WinHttpHandler API that was first introduced in ASP.NET 5 CTP 2. This implementation is intended to be faster and more efficient in terms of memory utilization than the existing .NET 4.5.2 framework version.

Developers can leverage this implementation via the familiar System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler APIs (in ASP.NET 5, both of these APIs are built on top of this new implementation) or through the newly designed System.Net.Http.WinHttpHandler API. This new API provides more granular control (than HttpClientHandler) over individual aspects of HTTP such as:

  • Automatic decompression
  • Handling HTTP Redirects
  • SSL server and client certificate authentication
  • Managing HTTP cookies
  • HTTP proxy settings
  • Setting HTTP send and receive timeouts


We encourage you to try out the new API and compare the performance of the new implementation against your existing .NET HTTP implementation. We look forward to hearing your feedback.

Coming Soon:
The following parts of the WinHttpHandler API that are yet to be implemented –

  1. Pre-Authentication on an HTTP connection
  2. Use of a user-specified CookieContainer object for managing HTTP cookies (current implementation uses an internal cookie store)
  3. Performance measurements and enhancements

The team is actively working on these and will make them available in an upcoming release.

Summary

Keep an eye on our Web Development and Tools blog this week as we have a number of articles planned that take a deeper dive on each of these topics. Do you like what you see? Are these improvements going to help you as a Web developer? You can open issues and track our progress on GitHub, or just write back to us in the comments below... we read all of them, and perhaps your feature suggestions will make it into the next release of Visual Studio! Thanks!

Identity Updates for Web Developers in Visual Studio 2015 CTP6

$
0
0

As anticipated in Monday’s announcement, the CTP release of Visual Studio 2015 brings lots of interesting news to identityland – both in the IDE and in the form of libraries we released on NuGet at the same time.

The features are still in preview (some of them, very much so Smile) but at this point you should be able to start getting a taste of what the product will look like in its final form.

In this post I am going to highlight the most interesting identity features you might want to experiment with.

New ASP.NET 4.6 Project Templates and Tools

(for the ones of you not keeping track, ASP.NET 4.6 == ASP.NET vCurrent)

Big news in this area!
The first thing you’ll notice is that the look & feel of the “Change Authentication” changed.

image

“Organizational Accounts” is now gone, substituted by the new moniker “Work and School Accounts”. In their infinite wisdom, our designers decided to change the label into something easy for people to relate to. As a poor English-as-a-second-language speaker, I can only agree Smile

If you pick the option and hit OK, things get even more interesting.

image

Major rearranging! Let’s examine the new layout, top to bottom.

The first dropdown remains the same as its VS2013 ancestor. It gives you the usual options for using Azure Active Directory from a Single Organization (for Line of Business apps), multiple organizations (for SaaS/multitenant apps) and on-premises (for direct ADFS connections).

But hey, what is that domain dropdown? What’s in there?

image

You’ll remember from the first VS2015 preview (and this silly video) that VS2015 introduced the ability of associating your MSA (formerly Live ID) and Azure AD accounts to Visual Studio, so that VS can now access the services your accounts can access on your behalf – across multiple features, and without bugging you all the time with credential prompts.
The domain dropdown is a manifestation of that. It lists all the default domains associated to all the Azure AD tenants your users belong to: basically, those are all the directories that you can use for securing new ASP.NET projects. You just select the directory you want, hit OK and VS will automatically provision your app in that directory! Neat, right?
A couple more details worth highlighting:

  • If you don’t see the domain you want in the list, just select the dropdown and start typing the domain you want. Once you hit OK the tool will verify with VS if by any chance that domain is associated to one of the Azure AD tenants for which you already have cached tokens. If that’s the case, it will just use the associated token and create the new project without prompting you. If that’s a completely new, unknown domain, you’ll get the usual ADAL prompt: once you enter the necessary credentials and consent, the cached token collection will grow by one member – and your app will be provisioned in the new directory. WARNING: in this CTP, this doesn’t work especially well. If it fails, you might want to add the user in advance to VS, via top right corner <username>->Account Settings.
  • In this CTP the dropdown is quite unstable. For example: if you have a federated tenant with lots of registered custom domains, the dropdown will show all of them… but in fact, they will all be different ways of choosing the same directory tenant. On occasions it might not show other test directories in the same subscription as the federated tenant.
    That is not very usable, and downright confusing at times (the domains are listed in random order and usually the one preselected in the dropdown is not the one you’d choose). I want to make sure to clarify that this is a BUG in CTP6, which we will hopefully address soon.

Going down, you’ll notice that we now have one single permission, Read Directory Data. The directory permisisons in this release are radically different from the ones in VS2013. Whereas the old model assigned permissions directly to the application, forcing you to be an administrator in the target directory, in the new system we use delegated permissions. That means that as long as the permission you choose does not require admin access, and your admin did not explicitly disallow the feature, you can now use VS for creating Azure AD protected apps even if you are not an admin! For that reason, we limited the set of permissions in the tool to the only one that can be set for (single org) web apps by non admins. If you want to change permissions, you can always go to the portal and change them there.

What’s left? let’s pop out the More Options area.

image

Wait a minute, what is “client id” doing there, instead of “app id URI” or realm? You guessed that right! From this CTP on, the ASP.NET templates for Azure AD generate OpenId Connect config code instead of WS-Federation. And of course, they use OWIN middleware for that.

What about ADFS? Well, if we want to talk with the ADFS setups in market today, we have to stick with WS-Federation. However, we updated the on-premises template to use the OWIN middleware for WS-Federation to talk with ADFS.

You already guessed, but let me spell it out: from this CTP on, we no longer have any template using Windows Identity Foundation. We’re now fully on OWIN.

New Connected Services Tool

Remember the Configure Azure AD Authentication dialog form the first VS2015 preview? It’s been updated to align with the new templates and domain dropdown. If I launch it against the project just created (solution explorer->right click->Configure Azure AD Authentication) I land on the following:

image

As you can see, the dialog precisely picked up all the settings that were generated by the file->new ASP.NET template, and I can now modify those to my heart’s content – the tool understands the project template structure and will do the changes I ask for, whereas in the earlier preview it would have thrown its metaphorical arms up and refused to touch a project with existing identity settings.

Isn’t it awesome to have different VS features all working together, presenting compatible options and augmenting each others’ functionalities? I’ll tell you a little secret: it doesn’t happen on its own! Smile The 2nd law of software thermodynamics wants features to show radically different UX and options, produce different artifacts, duplicate tasks and data, and so on. But we aren’t letting that happen! Every Thursday morning representatives from ASP.NET, VS IDE, Identity, Connected Services tools and Office tools teams gather around the same table, ensuring that everything identity related in VS2015 interlocks nicely. We try our best! Smile

New OpenId Connect and OAuth2 Middleware for .NET Core & ASP.NET 5!

Last but not least. We finally have OpenId Connect and OAuth2 bearer middleware that you can use in ASP.NET 5 projects.
We don’t have templates supporting those at this point, but we have the NuGets out there and two brand new samples that use as a starting point for your Web Apps and Web API based on vNext:

  • WebApp-OpenIdConnect-AspNet5, the classic OpenId Connect sign in and sign out – this time based on the ASP.NET 5 flashy templates
  • NativeClient-AspNet5, the entry level sample showing how to expose a Web API to be consumed by a native client. Note: the native client is still classic .NET 4.5, it’s only the web API project that is on ASP.NET 5.

There isn’t much news for what concerns the identity middlewares in themselves; the main notable new feature is the alignment we made between notification pipelines between OpenId Connect and OAuth2 bearer. That should make it easier for you to write portable logic for pipeline-bound operations, such as claims augmentation, custom request validation, and the like.

The most evident news is more about the way in which the projects in ASP.NET 5 are organized. Say goodbye to web.config! Have lots of moving parts that support client side development!Shove everything in one single Startup.cs! All of those are things happening around the identity logic; in fact, the init code we use remains pretty much the same – as a quick glance to startup.cs will confirm.

app.UseCookieAuthentication(options => { }); 

app.UseOpenIdConnectAuthentication(options =>
{
options.ClientId = Configuration.Get("AzureAd:ClientId");
options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
});

The only difference is that now you have to repeat “options” every time you want to set a property.

There is a bug to call out in this release – the ClaimsPrincipal.Current is not correctly set hence the samples contain a small workaround to set it right. That will be fixed in the next release.

Get your hands dirty

Lots of new features in this release! Although not everything is super stable at this point, I hope you’ll have the patience to play with the new identity features in VS2015 CTP6 and let us know what you like, what you don’t like and what’s still missing. Looking forward for your feedback!


Updates to ASP.NET 5 yeoman generators for beta 3

$
0
0

Hi everyone, the blog post below is written by Shayne Boyer, who is a community member that has been working on the ASP.NET 5 yeoman generators. I hope you enjoy it. - Sayed

With the most recent version of Visual Studio 2015 CTP, CTP 6 this past Monday, there were some great improvements not only in the IDE but also ASP.NET 5. See the article here from Jeff Fritz, or Introducing ASP.NET 5 on Scott Guthrie’s blog, for even more. We have updated the ASP.NET 5 yeoman generators to have the latest content based on ASP.NET 5 beta 3. For more info on getting started with the generators see the two previous blog posts here; Yeoman generators for ASP.NET 5 and Adding New Items to Your ASP.NET 5 Project with Yeoman Subgenerators. In this post we will cover the updates to the generators which are now available.

Prerequisites

KRE Version

This version of the generators are based on beta 3. You can use other version of the KRE but you may need to make changes to the content to build and run. To use beta 3 execute the command below:

kvm install 1.0.0-beta3 -p : installs and sets version to beta 3

By adding –p here next time the command prompt is opened beta 3 will be used.

Installing generator-aspnet

If you are getting the latest version, just run:

npm install -g generator-aspnet

If this is your initial installation you’ll need a few other things, see First Install below.

Now that you have installed the generators let’s move on to discuss the content of the generators.

New Project Templates

Visual Studio CTP 6 has reorganized the templates for ASP.NET 5 and now has 3 templates to choose from for a Web Application.

project_templates_vs2015[1]

These new templates have been added to the generator for project scaffolding. There were existing Web, MVC, and Empty project samples in the generator; these have been replaced by the new templates and the Web API project has also been added.

Preview Starter Web

This is a great starter template; it’s responsive, has a bunch of links to resources on getting started, a nice carousel from bootstrap, how to use static content and more.

$yo aspnet

    _-----_
   |       |    .--------------------------.
   |--(o)--|    |      Welcome to the      |
  `---------´   |   marvellous ASP.NET 5   |
   ( _´U`_ )    |        generator!        |
   /___A___\    '--------------------------'
    |  ~  |     
  __'.___.'__   ´   `  |° ´ Y ` 

? What type of application do you want to create? 
 Empty Application 
 Console Application 
❯ Web Application 
 Web API Application 
 Nancy ASP.NET Application 
 Class Library 

? What type of application do you want to create? Web Application
? What's the name of your ASP.NET application? (WebApplication) HelloWorldCTP6
  create HelloWorldCTP6/Startup.cs
  create HelloWorldCTP6/project.json
  create HelloWorldCTP6/package.json
  create HelloWorldCTP6/bower.json
  create HelloWorldCTP6/config.json
  create HelloWorldCTP6/gruntfile.js
  create HelloWorldCTP6/Models/AccountViewModels.cs
  create HelloWorldCTP6/Models/IdentityModels.cs
  create HelloWorldCTP6/Controllers/AccountController.cs
  create HelloWorldCTP6/Controllers/HomeController.cs
  ...
  create HelloWorldCTP6/Views/Home/Contact.cshtml
  create HelloWorldCTP6/Views/Home/About.cshtml
  create HelloWorldCTP6/Views/Home/Index.cshtml
  create HelloWorldCTP6/Views/Account/Login.cshtml
  create HelloWorldCTP6/Views/Account/Manage.cshtml
  create HelloWorldCTP6/Views/Account/Register.cshtml
  create HelloWorldCTP6/Views/Account/_ChangePasswordPartial.cshtml
  create HelloWorldCTP6/Views/Shared/Error.cshtml
  create HelloWorldCTP6/Views/Shared/_Layout.cshtml
  create HelloWorldCTP6/Views/Shared/_LoginPartial.cshtml
  create HelloWorldCTP6/Views/_ViewStart.cshtml
  create HelloWorldCTP6/wwwroot/_references.js
  .
  .
  .

Your project is now created, you can use the following commands to get going
   kpm restore
   kpm build
   k run for console projects
   k kestrel or k web for web projects
The next commands you need to run are

$ kpm restore

This command restores all of the nuget packages and bower packages that are referenced in the project.

Next run

$ kpm build

to compile the application, then

$ k kestrel

to start the server, and browse to http://localhost:5004

web_template_running

As a note, for OSX/Linux/Unix based systems, Entity Framework functionality was commented out of the template but all of the files and code is included. When EF 7 is complete for cross platform (xplat) local development the generator templates will be updated. You do have the option of using Azure SQL if you intended or need to develop on non Windows platforms in the meantime.

Preview Empty Web

The Empty project is the same with a simple addition by comparison to the template in Visual Studio. The UseStaticFiles() and UseWelcomePage() functionality has been added by default in order give you some out of the box presentation.

empty_template_welcome_page

Preview Web API

An out of the gate starter project template, one that was missing from the original ASP.NET 5 project types. This project template will give you the following greeting on the default page, and links to the built in values controller. http://localhost:5004/api/values.

webapi_default_screen

Other Improvements

Previously the templates were hosted online, meaning the generator was reliant on an internet connection or subsequent repository in order to work.  This was a change in a recent version as well. Now all templates and content run locally. Yes you can even work on a plane, without having to spend $15.

The previous sample projects had hard coded namespaces such as “TestWeb” or “Application”, the new CTP 6 projects in the generator will now have your applicationName as the namespace.

All of the CTP 6 templates have been modified to add the Kestrel nuget package to support xplat development as well as the associated commands in the project.json file.

The Nancy Web API project has also been updated to point to the beta3 ASP.NET assemblies.

First Install

Node, npm, Yeoman

Everything the generator is using is based in one way or another on node.js, not to mention a majority of the tooling you’ll be using in the near future will be as well. Grunt, gulp, etc. So if you aren’t already using node, now is the time to get it.

OSX

Homebrew is the most efficient way of installing node, if you are not already using it, you can obtain it with the following command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

John Papa has a great post on installing npm and node on OSX without sudo requirement here - http://www.johnpapa.net/how-to-use-npm-global-without-sudo-on-osx/

Windows

Chocolately is the best way to obtain node.js for Windows. Install node via

choco install nodejs

Yeoman

Yeoman is the base generator package the ASP.NET generator is built on. You can install it from the command line or terminal with:

npm install -g yo

Finally you can install the ASP.NET generator

npm install -g generator-aspnet

What Missing?

Get involved, project is hosted on GitHub at omnisharp/generator-aspnet. There is a current issue here - https://github.com/OmniSharp/generator-aspnet/issues/66 , please comment; let us know what you need in a generator.

Shayne Boyer
@spboyer on twitter
http://www.tattoocoder.com

Welcome Back! - The AJAX Control Toolkit March 2015 Update

$
0
0

Welcome Back! - The AJAX Control Toolkit March 2015 Update

Its been 15 months since a significant update was released for the AJAX Control Toolkit on CodePlex. In the time since then, our friends at DevExpress have stepped up and offered to lead this open source project. In just a few short months, they have implemented a number of modern and strategic changes to the toolkit to help make it a valuable part of your ASP.NET Web Forms arsenal. This release is branded as version 15.1 and is available NOW from http://devexpress.com/ms-act

DevExpress has written a great post highlighting the updates they've made to the toolkit on their blog at community.devexpress.com In this post, I'm going to show you how to use the updated control toolkit to build a responsive movie ratings page with a simple bar graph.

Your Toolbox is Ready and Waiting

When you start a new web project with the controls installed, you will find your toolbox in ASPX pages loaded with the controls in a new AJAX Control Toolkit 15.1 section:

 

On a new webform, get started by adding a standard asp:ScriptManager and the references to start using the bootstrap framework:

<head runat="server">
<title></title>
<link href="Content/bootstrap.css" rel="stylesheet" />
</head> 
<body> 
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<h2>My Movies</h2>
</form>

<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/bootstrap.js"></script>
</body> 

Add a GridView with a Rating Control

Next, I'm going to add a GridView to the page, but I also want it to have a responsive behavior. It should size appropriately for the browser window it is presented in:

<div class="row">
<div class="col-md-6">
<asp:GridView runat="server" ID="grid" CssClass="table" UseAccessibleHeader="true">
</asp:GridView>
</div>
<div class="col-md-6">
<!-- Graph goes here -->
</div>
</div> 

The div declared with the row class will allow two columns to float next to each other. The first column will contain the GridView, and the second will contain the bar graph. These two controls are placed in identical divs with the bootstrap class "col-sm-6". This class indicates that the column has a width appropriate for a medium device (like a tablet in portrait orientation) and each div is allocated to 6 of 12 'virtual columns' wide.

The GridView is assigned the CssClass 'table' to ensure that it behaves responsively within the bootstrap framework. Combined with the UseAccessibleHeader attribute, the content that is output by the GridView control will look and feel responsive with an appropriately decorated header row.

I'll use model binding features to bind my grid to a collection of Movie objects in a method called grid_GetData:

<asp:GridView runat="server" ID="grid" CssClass="table" 
 UseAccessibleHeader="true" ItemType="WebApplication11.Models.Movie" 
 AutoGenerateColumns="false" SelectMethod="grid_GetData"> 

The rating control can be added in a TemplateField and use the bootstrap glyphicon classes to paint ratings stars in my table:

<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<cc1:Rating ID="myRating" runat="server" Wrap="false" 
 StarCssClass="glyphicon glyphicon-star-empty" 
 FilledStarCssClass="glyphicon glyphicon-star" 
 EmptyStarCssClass="glyphicon glyphicon-star-empty" 
 WaitingStarCssClass="glyphicon glyphicon-star" 
 MaxRating="5" CurrentRating="<%# Item.Rating %>" 
 Tag="<%# Item.ID %>" OnChanged="myRating_Changed">
</cc1:Rating>
</ItemTemplate>
</asp:TemplateField> 

Adding a BarGraph

The bar graph is a simple control to add to this page, with a set of markup that needs to declare the size and title on the graph:

<cc1:BarChart runat="server" ID="bars" 
 ChartHeight="250" ChartWidth="350" 
 BorderStyle="None" ChartTitle="Highest Rated Movies">
</cc1:BarChart> 

Next, I wrote some C# in the code-behind to configure the data series and bind to this control:

private static readonly List<Models.Movie> _Movies = new List<Models.Movie>() { 
 new Models.Movie {ID=1, Name="Iron Man", Rating=4},
 new Models.Movie {ID=2, Name="Thor", Rating=3},
 new Models.Movie {ID=3, Name="Captain America: The First Avenger"},
 new Models.Movie {ID=4, Name="The Avengers", Rating=5}
}; 

private void FormatChart() { 
 var myData=_Movies.Where(m => m.Rating>0).OrderByDescending(m => m.Rating)
 .Select(m => new {x=m.Name, y=m.Rating}).Take(5); 
 bars.Series.Add(new AjaxControlToolkit.BarChartSeries { 
 Data = myData.Select(m => Convert.ToDecimal(m.y)).ToArray() 
 }); 
 bars.CategoriesAxis = string.Join(",", myData.Select(m => m.x).ToArray());
} 

That's all I needed to get started with a responsive grid and graph on a page with the updated AJAX Control Toolkit. The results look decent for writing no additional styling or images and using just the bootstrap framework:

Summary

DevExpress has more plans for the toolkit, and we'll share them in the weeks ahead. Recharge your ASP.NET AJAX Control Toolkit by downloading the update from DevExpress now: http://devexpress.com/ms-act

Customize external web tools in Visual Studio 2015

$
0
0

Visual Studio 2015 ships with multiple open source command line tools that are used in modern web development workflows. Those tools are:

  • Node.exe
  • grunt-cli
  • Bower
  • npm
  • Git

All of these tools are shipped as part of Visual Studio but are not installed in the same way as you would install them manually. They are all located in the Visual Studio install directory and are used by some of the new features such as the Task Runner Explorer and the new ASP.NET 5 project system.

If you manually install any of these tools, then there will likely be a difference in the versions between what Visual Studio is using and what you are using from the command line. For instance, the version of Node.exe shipped in Visual Studio 2015 CTP 6 is 0.10.31, but the latest official release of Node.js is version 0.12.

The good news is that you can tell Visual Studio to use the same version that you have manually installed. Here’s how you can do that in Visual Studio CTP 6.

Go to Tools –> Options –> Projects and Solutions –> External Web Tools.

External Web Tools default

This dialog let’s you add and modify file paths to where Visual Studio will look for the various tools. By default, this is the order of which it will look to find the tools. Notice how $(PATH) is below the internal path $(DevEnvDir)\Extensions\Microsoft\Web Tools\External. To use the global PATH environment variable before the internal path, you can just use the arrows at the top-right to change the order.

This is what it looks like when the global PATH is searched before the internal one and therefore will make Visual Studio use your own versions of the tools.

External Web Tools custom

This ensures that you decide which version of these tools are being used and that you don’t have to rely on Visual Studio updates to upgrade Node.exe, grunt-cli etc.

You are in control.

Introducing Azure API Apps

$
0
0

As part of the Azure SDK 2.5.1 release, a new feature called Azure API Apps were included.  This new feature raises the capabilities of ASP.NET Web API, extending it with Swagger metadata while providing a simple to manage interface in the Azure Portal.  Extend your API with authentication and no code changes, or generate an SDK for your API with a few clicks.  A full definition of API Apps and their capabilities is available in the online Azure documentation. Video coverage of the API Apps announcement with Scott Guthrie is available online:

 

Let’s take a quick look at some concepts, with links to more information.

  • API Apps live in an App Gateway.  This gateway manages add-on functionality such as authentication and update policies for the API.  A gateway resides on a single host.

 

  • Gateways are contained within a standard Azure Resource Group.
  • API Apps can use connectors to access SaaS (software as a service) platforms such as Office 365 and Salesforce.
  • When you create an Azure API App in Visual Studio, you can review the Swagger metadata for your app by navigating a web browser to the default web location of /swagger/docs/v1 in your compiled and running project.

Given the following ASP.NET API Controllers:

The following swagger format is output:

We have a complete tutorial online demonstrating how to get started defining your first API, publishing the API so that others can re-deploy it, and finally deploy the API so that you can consume it.

There is a lot of coverage of the introduction of our new Web App platform, you can learn more at the following links:

If you have an active Azure subscription, navigate over to the Azure Portal and try the new API Apps.  If you are new to Azure and don't yet have a subscription, you can try Azure App Service for free with no credit card and no commitment needed.

ASP.NET Identity 2.2.1

$
0
0

We are releasing ASP.NET Identity 2.2.1. The main focus in this release was to fix issues reported in 2.2.0 release.

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.2.1

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

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

What’s in this release?

The following issues from CodePlex were fixed in this release:

Samples

Documentation

Migrating from ASP.NET Identity 2.2.0

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

Give feedback and get support

Open source

The source code for ASP.NET Identity 2.x and earlier is available on aspnetidentity.codeplex.com.

ASP.NET Identity 3.0 is part of the ASP.NET 5 organization on GitHub.

What’s next?

Apart from working on Identity 2, we are also working on the next version of Identity (Identity 3.0 which is part of ASP.NET 5).

Making It Better: ASP.NET with Visual Basic 14

$
0
0

BASIC is part of the DNA of Microsoft, and we have continued to evolve the language for most of the 40 years of the company’s existence.  In the next evolution of the language, Visual Basic 14, there are a number of great features that are being added and we want to make sure that you know we are fully supporting them with ASP.NET in Visual Studio 2015.  Let’s take a look at a few samples of how using Visual Basic with ASP.NET 4.6 makes developers more productive and their code more readable.

 

String Interpolation Makes Web Forms Strings Feel like Razor Syntax

String formatting with Visual Basic is usually a mess.  How many times can you connect strings with ampersand (&) marks and underscores when you span rows?  If you assemble and format your strings by hand, you know what a mess this is.  You already have some nice syntax in razor like the following:

 

<a href="https://twitter.com/@ViewBag.ScreenName/status/@Item.StatusID">

 

If we wanted to do something similar in web forms for this anchor we could end up with a concatenated mess:

 

<a href="https://twitter.com/<%: screenName %>/status/<%#: Item.StatusID %>">

 

Perhaps we got a little more creative and tried to use a String.Format method call:

 

<a href="<%#: String.Format("https://twitter.com/{0}/status/{1}", screenName, Item.StatusID) %>">

 

Yuck… That makes my eyes hurt to read that, with looking back and forth across the string to understand what values are formatted and placed into the output I feel like I’m watching a tennis match.  We know we can do better to make this more readable. With the new string interpolation feature, the string can be decorated with a dollar symbol and then formatted with even simpler template text with a format like the following:

 

<a href="<%#: $"https://twitter.com/{screenName}/status/{Item.StatusID}" %>">

 

Now our string looks more readable, just like the razor syntax without having to scan back and forth across the code.  Values inside of curly braces in our text are interpreted as code values to be inserted at that point in the string, just like our previous String.Format text format but without the annoying back and forth reading for us humans.  This feature isn’t limited to just ASP.NET use, as you can use it in all of the .NET frameworks that support Visual Basic 14.

 

Use the New NameOf Operator in MVC to Validate Arguments

Magic strings are the practice of having string constants in our code that control behavior of our application.  An example of this is when we throw the ArgumentNullException when verifying input parameters:

 

 Public Function TwitterStatus(screenName As String) As ActionResult

If (String.IsNullOrEmpty(screenName)) Then

Throw New ArgumentNullException("screenName")

End If

 

That sample has a code smell, or a deep-seeded problem… if the parameter name changes and an error scenario is triggered, our code will break with this ugliness:

 

As someone who reads stack traces and debugger output, this helpful bit of information that the previous developer attempted to provide for me no longer makes any sense.

The new NameOf operator will take a variable and return a string value for the name of that variable.  Take a look at how our code changes when we use the NameOf operator:

 

 Public Function TwitterStatus(screenName As String) As ActionResult

If (String.IsNullOrEmpty(screenName)) Then

Throw New ArgumentNullException(NameOf(screenName))

End If

 

With that change, we can protect our MVC and WebAPI action methods from inadvertent changes.  Remember, the new refactoring capabilities in Visual Studio (or another refactoring tool that you may be using) will not capture references to the parameter in strings.   If you do use the automatic refactor it will not replace the parameter name in the previous string example, however it will capture this reference to the parameter name. Additionally, our thrown error looks like the following:

 

Now that error statement makes more sense for the next developer who will be maintaining your code.

 

Asynchronous Model Binding in Web Forms

Asynchronous operations have been available with the Task Parallel Library since .NET 4 in 2011.  It’s been around for a long time, and Web Forms just has not had a chance to really feel that love in the more complex interactions that they host. Let’s face it, Web Forms is the event-driven model that could have significant problems if an event is not finished an asynchronous operation when the next event is about to start.  It’s a complex model, but in the latest update to ASP.NET 4.6, we have opened the web forms model to allow Asynchronous Model Binding operations with the Task Parallel library.  Let’s take a look at how easy it is to migrate an existing set of controls to model binds asynchronously.

In this sample, I’m going to load the tweets for both the Visual Studio and ASP.NET twitter accounts into two columns on a web page.  I’ll use the ASP.NET ListView control to output a simple list of the 5 most recent tweets with a syntax and formatting like this:

 

<asp:ListView runat="server" ID="vsTweetList"

SelectMethod="vsTweetList_GetData" ItemType="LinqToTwitter.Status">

<ItemTemplate>

<p>

<%#: $"At: {Item.CreatedAt.ToString("T")} on {Item.CreatedAt.ToString("d")}" %>

<br />

<%#: Item.Text %>

</p>

</ItemTemplate>

<ItemSeparatorTemplate><hr /></ItemSeparatorTemplate>

</asp:ListView>

 

I’m using Model Binding with this control by declaring a SelectMethod on the control.  This method will be called when the control is ready to bind data for presentation, typically after the Page_Load event.  Model Binding for Web Forms is available starting with ASP.NET 4.5, and the syntax is not changed for 4.6 

The ItemType argument on the ListView provides strongly-typed databinding capabilities.  This allows me to avoid the magic-string problem with databinding syntax like Eval(“Status”) If Status was misspelled or did not appear in my data object, I wouldn’t see an error until the page was requested.  By using the ItemType, all of the references to Item in this control are strongly-typed and I get editor intellisense assistance.

Notice I used the new string interpolation feature from Visual Basic in the date format.  While not entirely necessary, it just felt cool to be able to write that as a complete sentence.

The code-behind to fetch the tweets for this presentation would normally look something like this:

 

 Public Function vsTweetList_GetData() As IEnumerable(Of Status)

Return GetTweetsFor("VisualStudio")

End Function

 

That would normally work really well, fetching the data and loading it into my resultant HTML very quickly.  In this case, I want to load two sets of tweets.  That means two requests to Twitter to load data and blocking page processing while those two requests are fulfilled by the Twitter APIs.

We can make these requests asynchronous by changing the syntax of the specified SelectMethod to return a Task.  We also need to mark the @Page directive with an async=”true” attribute.  It seems too simple, but the web forms framework was updated to allow this type of simple update to “just let the magic happen”

 

 Public Async Function vsTweetList_GetDataAsync() _

As Threading.Tasks.Task(Of IEnumerable(Of Status))

Return Await GetTweetsForAsync("VisualStudio")

End Function

 

Seriously, that’s all that you need to do in order to allow your requests to fire asynchronously.  Just add the async keyword, return a task, and await the asynchronous method call.  Now, both of my requests to the Twitter API will fire at the same time, the ASP.NET runtime will manage the threads that call the API and ensure that they are all processed before returning the page to the requesting user.

 

Roslyn Support for Visual Basic Compilation

Graph of comparison between compiler versionsWith the introduction of the new Roslyn compiler,  you now have a turbo-charged ASP.NET compiler experience.  In the tests in our lab, we have measured an almost 50% speed increase for Visual Basic developers at compile time.  However, we didn’t stop there.

Since May 2014, there has been a NuGet package available called “CodeDOM Providers for .NET Compiler Platform (Roslyn)” and wow was that hard to find.  Only 600 downloads of this package have been recorded at the time of this article’s writing, and that’s a real shame.  This package activates the Roslyn compiler for ASPX page parsing and compiling.  Do you remember waiting for the compiler to re-interpret your ASPX pages each time you change HTML formatting?  This package cuts that time significantly, but is in pre-release mode and only works for C#-based ASPX files.  With the coming release of Visual Studio 2015, we are going to release a 1.0 version of this package and add Visual Basic support.

 

ASP.NET 5 – C# Support And Also Visual Basic

We’ve talked about ASP.NET 5 as a major update of the ASP.NET framework with Roslyn and cross-platform support in mind since our initial public discussions.  It is not a short path, and we focused initially on completing support for C#.  In the months since our initial announcements, we have heard from many of you, telling us how much you like Visual Basic and that they want to see support for it in ASP.NET 5. 

We are excited today to announce that ASP.NET 5 will have full support with Visual Basic (both tooling and runtime – including cross platform runtime support).  As always, we will continue this development of ASP.NET 5 in the open, and you can track our progress or even contribute on GitHub at http://github.com/aspnet/home.

 

Summary

Visual Basic, ASP.NET and even Classic ASP before that have had a long history together.  We’re committed to that partnership, and we will continue to evolve the Visual Basic story with ASP.NET.

You can learn more about the new features in Visual Basic 14 from Lucian Wischik and from Kathleen Dollard in a pair of snack-sized five-minute videos.

New ASP.NET Features and Fixes in Visual Studio 2015 RC

$
0
0

Today Scott Hanselman announced the Release Candidate of Visual Studio 2015, Team Foundation Server 2015 and Visual Studio 2013 Update 5. We hope that all //build attendees are enjoying the show, and we are following up on the news of the Visual Studio 2015 Release Candidate to show you some of the cool new features delivered in this version for web developers. With the Visual Studio 2015 release candidate we are delivering updates for ASP.NET 4.6 and our next generation ASP.NET 5 framework.  You can read more about ASP.NET 5 online at http://www.asp.net/vnext and review the new open source documentation for ASP.NET 5 at http://docs.asp.net Let’s take a look at the new features delivered in the Visual Studio 2015 release candidate for ASP.NET 4.6 and the ASP.NET 5 beta4 preview:

The Big Rename

If you’ve been following the previous releases of Visual Studio 2015 and the nightly builds of ASP.NET, you have no doubt been familiar with the Project K executables: k.exe, klr.exe, kpm.exe, and kvm.exe  In order to drop the Project K codename and move to a more market-friendly name of the ASP.NET tooling, these command-line tools and the K-Runtime were renamed as follows:

  • k and klr are now DNX. DNX stands for .NET Execution Environment.
  • kvm is now dnvm or the .NET Version Manager
  • kpm is migrating some functionality of its functionality to dnu, the .NET Development Utility and some functionality will migrate to be core NuGet functionality
  • The Aspnet50 and aspnetcore50 framework monikers in project.json files are being replaced with dnx451 and dnxcore50.
The ASP.NET 5 Community Standup has a video discussing the rename decision in depth.  That video is from some time ago that refers to nightly builds or "daily bits", those changes have been completed and are in this release.

New Project Templates and Project Types

In the prior versions of Visual Studio 2015, we made project types available for Project K class library and Project K console applications.  These project type names don’t make sense in our new world and we have renamed them appropriately:

Class Library (Package) is a class library project that is configured to allow you to build reference libraries that compile directly into NuGet packages.  Console application is a similar project that allows console applications to be built in the same model as an ASP.NET 5 web application, referencing NuGet packages and configuring multiple frameworks to build against.  Both of these project types allow the developer to configure everything with a project.json file and target the .NET Core framework.

We’ve also simplified and updated the ASP.NET web project templates in this release. There are clear dividing lines between the ASP.NET 4.6 and ASP.NET 5 projects, as well as updated templates for a Single Page Application and Azure Mobile Service:

The ASP.NET 5 templates are updated as well, with additional security and JavaScript features configured to make them an easier starting point for building applications.  You can learn more about how to start a new ASP.NET 5 project online at: http://www.asp.net/vnext/overview/aspnet-vnext/aspnet-5-overview

Add Missing NuGet Packages in ASP.NET 5

Our favorite new feature for ASP.NET 5 developers is the cool new feature to help you add the correct NuGet packages to your project for the types that you are referencing. In the ASP.NET 5 environment, all references are NuGet packages, and how will you know which ones to add when you just want to light-up that XDocument type to work with an XML document?  In an ASP.NET 5 web project or class library project, you can just press CTRL + . (period) to activate a helper in the editor that will offer to add the missing package to your project:

The editor will suggest the package to add and show you the changes that it is going to make to the Using statements at the top of the code file in order to allow your code to function properly.

Performance Updates for ASP.NET 5

We focused a significant amount of time on improving the performance of the Visual Studio developer experience. In this release, you should see a noticeable speed increase when opening existing solutions with ASP.NET 5 projects as well as launching the application. There are a number of other less important performance tweaks under the hood for ASP.NET 5 projects as well.

Editor Improvements to Support TagHelpers

TagHelpers for ASP.NET MVC were introduced in an earlier preview, but in this release they really come into their own.  TagHelpers provide a simple tag experience in the razor editor that allow you to execute code on the server and inject content in the output.  Scott Hanselman and Jeff Fritz have posts that introduce and demonstrate how to start writing your first TagHelper.  The ASP.NET Community standup discussed TagHelpers in March 2015.

We have added editor support so that you can easily see where your .NET code will take over rendering your HTML.  With bold tag names and intellisense support for attributes, coding HTML with these complex server-side interactions has become easier than ever.

Add Reference to Project

We’ve re-introduced the ability to add references to an ASP.NET 5 project from standard class library projects. In the image above, the ClassLibrary1 project is a standard class library, while the TagHelperSample.Helpers project is an ASP.NET 5 specific class library. Both library types are supported interchangeably now.

Cleaned Up Solution Explorer with Automatic File Nesting

With ASP.NET 5, we’ve promoted the fact that ASP.NET developers should start to use more standard web practices for acquiring, minifying, and otherwise processing your static resources before they are served to your web application’s visitors.

To help make the display of minified resources easier to review in your solution explorer, any files with an extension of min.css or min.js will be nested automatically under the un-processed version of that file. We hope that you find this to be a useful addition to the solution explorer.

Local IIS Express Custom Configuration

If you were finding that you were constantly updating your applicationHost.config file on your machine each time you started a new project, then this feature will be a welcome change. With the new ASP.NET tooling, your custom IIS web server configurations are stored in the solution’s .vs folder in an applicationHost.config file. This should help isolate your web server configurations for each of your projects without conflicting references to a single configuration file.

Security Updates for ASP.NET

There are a number of security-focused updates in this release for both ASP.NET 4.6 and ASP.NET 5:

  • ASP.NET 4.6
  • ASP.NET 5
    • The individual web site authorization template option now allows developers to configure social logins, account confirmation, and two-factor authentication.
    • Templates are using Gulp.
    • SSL can be configured from web project property pages.
    • The ASP.NET authorization library now allows for authorization using policies.
    • Web Projects can now be configured to use Windows authentication.

Custom Launch Settings are saved as Project Properties

If you want to lock in the version of the framework that your project for compilation and debugging, those settings are now saved with your project in the new launchSettings.json file in your project properties folder. This means that all of your team members will have the same debugging configuration when they synchronize source code.

Additionally, we have simplified the format of this configuration file to make it easier to read and work with:

 

ASP.NET 4.6 Improvements

We have a number of updates for ASP.NET 4.6 which includes Web Forms, MVC 5 and Web API 2. These include support for .NET Compiler Platform (Roslyn), hosting changes in IIS to support HTTP/2 and more. Read this post for more details.

Summary

We are working on evolving the ASP.NET environment and tooling. This might be a release candidate build for Visual Studio, but we are looking at the big picture for ASP.NET. We will continue to develop at the same pace in the open at http://github.com/aspnet/home. We are building and releasing our libraries and updates for Visual Studio with the updates delivered on NuGet and the Visual Studio Extension Gallery. Keep an eye on our blog to hear about our next set of features.

 

Updates for ASP.NET 4.6 – Web Forms/ MVC 5/ Web API 2

$
0
0

We released Visual Studio 2015 RC which included ASP.NET 5 Preview. Along with ASP.NET 5 Preview we have also been working on improving ASP.NET 4.6 which includes Web Forms, MVC 5 and Web API 2. This post highlights updates in this area.

What is ASP.NET 4.6?

ASP.NET 4.6 is an umbrella term used to describe updates existing Frameworks such as ASP.NET Web Forms/ MVC 5/ Web API 2 etc. You can build Web Apps using these Frameworks on the standard, desktop-enabled .NET Framework model.

Improvements in ASP.NET 4.6 for Web Forms/ MVC 5/ Web API 2.

Apart from working on ASP.NET 5, we are also working on updating Frameworks in ASP.NET 4.6. You can expect changes around supporting platform updates. These includes updates in .NET for .NET Compiler Platform (Roslyn) and hosting changes in IIS to support HTTP/2. The following lists the updates for ASP.NET 4.6

Authentication Updates

The ASP.NET 4.6 templates now use Open Id Connect middleware to authenticate with Azure AD. This makes the programming model to authenticate with Azure AD much easier.

There is a New Connected Services Tool which allows you to Configure AD Authentication on existing projects. For more details read this post.

If you select the “Individual User Accounts” option, then the ASP.NET 4.6 templates show how to use two-factor authentication and social logins. The template uses the latest version of ASP.NET Identity.

clip_image002

Updates to MVC 5.2.3/ Web API 5.2.3

The latest version of the MVC, Web API and Web Pages have lots of fixes around improving performance. Read this post for more details.

Enabling the .NET Compiler Platform (“Roslyn”) in ASP.NET applications

You can use the new language features of C# and VB in any ASP.NET 4.6 project. The Web Forms templates in VS 2015 have the Microsoft.CodeDom.Providers.DotNetCompilerPlatform package pre-installed. Read this post for more details on the providers.

The following screen shows how you can use string interpolation from C# 6 in your Web Forms pages.

clip_image004

In this Preview, following are some known issues which will be resolved for RTM.

- The providers will be added to all templates such as MVC 5/ Web API 2 etc. You can download this NuGet package to use the new languages features in your views.

- When you open Web Forms pages, you will see errors in the “Error List” windows as shown above. However, this does not prevent the project from running successfully.

 

Async Model Binding for Web Forms

In .NET Framework 4.5, Model Binding support was added to Web Forms. In .NET Framework 4.6, we are adding support for Async Model Binding which allow you write Asynchronous Model Binding actions. The following code snippet shows a Web Forms page using Async Model Binding actions.

Add support for HTTP/2

In Windows 10 and .NET Framework 4.6, we have added support for HTTP/2. The main goal for HTTP/2 is to improve performance, latency, and network usage by using a single connection from browsers to a Web site. See this video to learn more.

Updated Ajax Control Toolkit

The Ajax Control Toolkit is a very popular toolkit used by many Web Forms developers. The Toolkit has many fixes to improve quality and new features such as modern templates, Web Optimization support and more.

The Toolkit is still free and open sourced and is being maintained by Dev Express. Read http://devexpress.com/ms-act for more details.

Updated Frameworks and controls to support EF 6

We have updated Dynamic Data Framework, Entity Data Source Control and Universal Providers so they work with Entity Framework 6. Read this post for more details.

Entity Framework 6.1.3

Entity Framework 6.1.3 has bug fixes and performance improvements over 6.1. Read this post for more details.

ASP.NET Identity 2.2.1

ASP.NET Identity 2.2.1 has many bug fixes and performance improvements over 2.1. Read this post for more details.

.NET Improvements

Read this post from the .NET team about improvement to .NET Framework 4.6 and .NET Languages - C#, VB

Updated C# & VB templates with latest packages

The ASP.NET 4.6 templates carry the latest packages for MVC, Web API, Entity Framework, Identity etc.

Support for Azure API Apps

You can build Azure API apps. As part of the Azure SDK 2.5.1 release, a new feature called Azure API Apps were included.  This new feature raises the capabilities of ASP.NET Web API 2, extending it with Swagger metadata while providing a simple to manage interface in the Azure Portal.  Extend your API with authentication and no code changes, or generate an SDK for your API with a few clicks.  A full definition of API Apps and their capabilities is available in the online Azure documentation.

Summary

As we work on ASP.NET 5, we encourage you to look at the updates happening in ASP.NET 4.6 and .NET.

Application Insights for ASP.NET 5 – you’re in control

$
0
0

ASP.NET 5 apps can now be monitored for performance and usage with Visual Studio Application Insights. The composability of components in ASP.NET 5 makes it very easy to integrate telemetry modules into your app design in a flexible way. With the feedback you get about the performance and effectiveness of your app in the wild, you can make informed choices about the direction of the design in each development lifecycle.

application-insights-in-action

ASP.NET 5 is a lean framework for building web and cloud applications. Dependency injection is one of the biggest architectural improvements over previous versions, allowing components to be much more independent, composable, and easily isolated for testing.

This composability has made it easy for us to give you, the app developer, much more control over how you put together the different components of the SDK, compared to the Application Insights SDKs for other platforms.

In the Application Insights team, we believe that good telemetry data collection is critical part of your application. When you put a new feature into the app, you need to know how well it works for the users, and whether it causes any performance problems. You’ll use that data to help prioritize and plan future work. So the telemetry should be designed as part of each user story, and then tested, tuned and deployed along with the app.

From this point of view, it’s clear that telemetry is a tool for developers. It isn’t just a runtime add-on that IT pros use for load management. There is a useful role for that kind of telemetry, but Application Insights is primarily concentrated on developers. We’ve designed it primarily as a development tool, with the runtime add-on as a secondary capability.

We’re delighted with ASP.NET 5, because it fits very well with that philosophy. It’s very easy for us to give you a range of parts that you can select and put together under your control.

Let’s see how that works in practice. Setting up Application Insights has four easy steps.

Step 1. Create an Application Insights resource in the Azure Portal. This is where your telemetry is analyzed and displayed.

new-resource

Get the instrumentation key of the new resource.

get-instrumentation-key

Step 2. Add the SDK NuGet package to your project.

In the dependencies section of project.json, add:

"Microsoft.ApplicationInsights.AspNet": "0.32.0-beta4"

In config.json, tell the SDK about your Azure resource:

"ApplicationInsights": {
        "InstrumentationKey": "af2bd99b-5e71-4465-b03a-24c0f377f93e"
}

Or if you’d prefer the configuration to be dynamic, you can add this code to the application’s Startup class:

configuration.AddApplicationInsightsSettings(
        instrumentationKey: "af2bd99b-5e71-4465-b03a-24c0f377f93e");

In Startup.cs, in ConfigureServices, add:

Services.AddApplicationInsightsTelemetry(Configuration);

Unlike the setup for other Application Insights SDKs, adding the SDK doesn’t automatically configure a range of modules to collect different kinds of telemetry. Instead we’re going to let you choose the modules you want.

You can override any default services you want to replace. For instance, you may choose to implement your own telemetry channel to perform sampling or filtering. Just register it in the same method ConfigureServices, and dependency injection will make use it instead of the standard telemetry channel.

Step 3. Enable the telemetry you choose. You can both write your own telemetry into your app, and use the standard middleware components to report basic metrics like number of requests per second or detailed information about a failed request. Middleware is configured in the Configure method of Startup.cs, and it forms a pipeline:

app.UseApplicationInsightsRequestTelemetry();
//Error handling middleware goes here…
app.UseApplicationInsightsExceptionTelemetry();

Request tracking should always be the first item in the pipeline to give you the most accurate timing of the request. Typically exception reporting goes after any error handling middleware and before other middleware. Typical error handling middleware will handle exceptions and thus earlier middleware in the pipeline will never see it. Thus the Application Insights exception reporting middleware should go after the error handling middleware components unless you don’t want to report some exceptions to Application Insights. Again, you are in control of your telemetry and of course you can write your own middleware if you prefer.

Step 4. Enable client-side reporting of usage and browser performance. From your Application Insights resource, you can get a snippet of code that you insert in each web page – typically just by inserting it in a layout page such as _Layout.cshtml. Using dependency injection you can obtain TelemetryConfiguration class that contains your Instrumentation Key. First, inject the telemetry configuration into the layout page by adding this code to the top of the layout page.

@inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration     
        TelemetryConfiguration 
 

And then use the HTML helper method to inject the Application Insights JavaScript snippet just before closing </head> tag and any other scripts:

@Html.ApplicationInsightsJavaScript(TelemetryConfiguration) 

javascript-snippet

And you’re all set! You’ll be able to see application telemetry while developing the application, while testing it, and when it’s deployed to production. Now you know how it behaves with real users.

As you can see, the Application Insights SDK for ASP.NET 5 application is flexible and easy to configure.

This SDK is an open source project with design discussions, source code and documentation available on GitHub. Get started monitoring your ASP.NET 5 application with Application Insights now, get visibility into the performance and reliability of your application in production and speed up your engineering. We are happy to hear your ideas and feedback. Just file an issue and tell us what you think.

Cool ASP.NET Web Forms Features in 2015 – Async Model Binding

$
0
0

This is the first in a twice weekly series of blog posts that we’re going to share from the Microsoft Web Development blog to showcase some of the really cool and mature features available in ASP.NET Web Forms for developers to use in their projects.  Web Forms is the development model that was deployed first with ASP.NET in 2001, and has been improved in every ASP.NET release since.  Throughout this series of posts, we will build a sample application to track our travel information.  Each update will provide a link to the source code so that you can follow along. 

In this first post, we’re going to look at the model binding feature in web forms and see how it has been improved to provide for asynchronous operations in the new ASP.NET 4.6 framework in Visual Studio 2015.

 

In the beginning

Many long-time ASP.NET developers are familiar with the various ways that you can deliver data to user interface components in web forms.  We call that databinding to a control, and there are two primary techniques you can use:

  • Declarative data-binding with data controls
  • Code-behind, or “manual” data-binding on the server

Declarative data-binding is where all of our database code is placed into a SqlDataSource object on the ASPX page and a grid or some other user interface control references the id of the SqlDataSource to know how to work with a data resource.  Let’s start our first code sample with a simple grid bound to a table of trip information:

The advantage of this technique is that all of the code for the user interface, server-side operations, and database commands are all in one file.  The disadvantage with this approach is that when any of your database resources changes or matures, you need to touch all of your ASPX files to update and maintain those objects.  This is particularly a problem as a database evolves over time.

A manual code-behind method would connect data access to controls through a series of events that are appropriate to each control.  The advantage of this approach is that custom code can be written to centralize data access using a repository class strategy.  The disadvantage of this technique is that a lot more code needs to be written to connect these classes and I need to ensure that the data content of the grid is loaded in the correct event during the page lifecycle.  I could put the contents of my grid into ViewState, but that would bloat the size of the page, a major faux pas in today’s web.

 

Along came Model Binding

With the release of ASP.NET 4.5 in 2012, a simpler and friendlier data binding solution was introduced called Model Binding.  This was an adjustment of a similar feature that was developed for ASP.NET MVC so that the Web Forms framework could experience the productivity gains of this simplified programming model.  The idea with Model Binding is that each data-bound control has four simple methods for each of the CRUD operations:

  • InsertMethod
  • SelectMethod
  • UpdateMethod
  • DeleteMethod

These methods are available to the control as a property or an attribute that can be specified at design-time.  With some editor auto-completion magic, Visual Studio will generate the appropriate signature for these methods in the code-behind of the page you are working on.  Let’s take a look at the GridView control demonstrated in the previous code listings and update it to use model binding for the SelectMethod:

That looks fairly simple, as we moved the code to read the data into the myGrid_GetData method in the code behind.  The advantage here is that all of my data access code is in one method in the code-behind and that method will be called by the page when it is needed.  You can use a repository model with this technique, and really take advantage of that design strategy by implementing the OnCallingDataMethods event handler.  Inside the arguments passed through this event is a property called DataMethodsObject that contains the instance of the repository object that houses the methods you want ASP.NET to call for your control.  Let’s take a look at a page with a FormView control so that we can manage the details of a trip, and add SelectMethod, InsertMethod, and UpdateMethod attributes:

What’s with the [QueryString] markup in the myForm_GetItem method on line 11?  That is a hint that indicates to the ASP.NET page where it can acquire a value to pass in to the SelectMethod if it has not been explicitly called.  In the case of this page, the id is delivered in the querystring parameter “id”.

Next question: where does the id argument come from in the UpdateMethod?  There is no querystring argument on this method, but the id is declared as a DataKeyNames value on the FormView.  This tells ASP.NET that the primary key for the trip object is the id property and to use that in submitting updates.  The argument name on the UpdateMethod is the same name as the name of the property in the DataKeyNames attribute in my ASPX markup.

Last question:  In the InsertMethod and UpdateMethod there is a call to TryUpdateModel.  What is that method call?  This is a helper method that will attempt to pass values that were submitted to the page into the model object that is passed into TryUpdateModel.  This prevents that silly mapping code that you always ended up writing like this:

Too cool! I don’t have to write all of that annoying code and I can now move my data-access methods for this control to a class library or even use dependency injection to pass an interface for a concrete class:

The major disadvantage to this approach is that it runs synchronously within the page lifecycle and you can’t really take advantage of async and await methods to access the datastore.

Until now…

 

Async Model Binding in ASP.NET 4.6

Web Forms has had the ability to run forms asynchronously since ASP.NET 3.5 back in 2008.  However, you needed to construct your own threads and map the callback through an event to be processed by the form before the content was delivered to your visitors.  My mind melted every time I tried to debug a page that I built with this technique.  It worked great, but was real hard to maintain.

With C# 5 and ASP.NET MVC 5, asynchronous programming became a lot easier to follow and build with the async and await keywords and delivering Task objects.  The promise was simple: use these keywords and the host application will release threads while awaiting for background processing.  This makes great sense for use in database interactions, as we do not want to block web server requests while awaiting database processing.

I can adapt the gridview to use asynchronous processing with the database in three simple steps.

Step 1: Add an async=true modified to the @Page directive:

 

<%@ Page Language="C#" Async="true" Title="My Trips" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="TravelDemo.Trips.Default" MasterPageFile="~/Site.Master" %>

 

Step 2: Add an async keyword to my select method and wrap the return object in a Task

 

public async Task<IEnumerable<Models.Trip>> myGrid_GetData()

 

Step 3: Await the appropriate async version of the data access method

 

return await ctx.Trips.OrderBy(t => t.DepartureDateTimeUtc).ToListAsync();

 

 

That’s it for our grid.  The FormView and its data modification methods can be updated similarly in their repository class:

 

Summary

Data access has come a long way with ASP.NET, and with the latest updates we can be extremely productive with high-end multi-threading capabilities with small changes to our existing single-threaded code base.  Unfortunately, with great code power comes great responsibility.  If you make every database call on your application async, that means that the web server will release threads and handle more volume for you while database processing occurs.  Cool!  However, the database will feel the direct force of every query with no processing boundary between the web browser and the query.  Your DBA may see traffic surge, so use these techniques wisely.

The source code branch for this project in Visual Studio 2015 is available on GitHub.  Take a look at the before and AsyncModelBinding branches to understand how the project evolved from the 2001 data access model to the async programming model of today.

ASP.NET 5 Beta5 Now Available

$
0
0

This week we released ASP.NET 5 Beta5 as an in-place update to Visual Studio 2015 RC on http://nuget.org!

The version that shipped with VS2015RC was Beta4 so you’ll definitely want toget this update. ASP.NET 5 Beta5 is loaded with lots of new features, improvements, and bug fixes.

It’s important to remember that there’s the ASP.NET runtime (the bits that run your web apps) and there is the Web Tooling bits for Visual Studio (the bits that give you the HTML and JavaScript editor and the File New Dialog Box). Beta5 is an update to the ASP.NET 5 runtime!

Remember that ASP.NET 5 runs on both the full .NET Framework and also (still a work in progress) .NET Core. It’s .NET Core that will run on Windows, Azure, Linux, and Mac. It’s important to note that ASP.NET runs on both these frameworks, so this is a good time to start installing the betas and trying out your applications with ASP.NET 5.

Here are just some of the highlights from this release:

.NET Execution Environment (DNX)

  • Support for NuGet v3 feeds. Restoring packages using the new NuGet v3 feed is significantly faster - try it out by adding https://api.nuget.org/v3/index.json as a package source.
  • Support for the new dotnet Target Framework Moniker (TFM). You can now use DNX to build portable .NET libraries that work on any .NET flavor that supports your package dependencies using the new dotnet TFM. We will provide more details on using the new dotnet TFM for package authoring in a future post.
  • Specify language and release notes link in project.json. These nuspec properties can now be specified in your project.json file.
  • Removed JSON.NET version pinning. This is an important change that we are introducing as it no longer requires that your application use the same version of JSON.NET that is shipped with the DNX version that you are working with.  As JSON.NET evolves, you can choose to download and install new releases without being required to upgrade the DNX version you are using.
  • New IRuntimeEnvironment service. Use the new IRuntimeEnvironment service to get runtime details, like OS, CLR, and bitness.

ASP.NET 5

  • HttpContext.Connection. Added connection information to HttpContext via the new Connection property.
  • New localization abstractions and middleware. You can see the new abstractions in action in this localization sample.
  • Consistent way to terminate ASP.NET hosting. Previously ASP.NET hosting would terminate on any key press. We now consistently terminate on Ctrl-C.

MVC 6

  • C# 6 support in Razor. You can learn more about the new features available in C# 6 at MSDN blogs.
  • Simplified MVC options and added top level settings. There are now app-level settings for configuring various settings for HTML helpers
  • New JSON helper for serializing JSON in views. This helper allows you to serialize your .NET objects to JSON in Razor views very easily with syntax like the following:

@Json.Serialize(Model)

  • Attribute routing token replacement in route names. In addition to using route tokens in route templates you can now use them in route names, like this:
[Route("Products/[action]", Name = "[actions]Products")]
public class ProductsController
{
    public void Add() { }
    public void Buy() { }
}
  • New ImageTagHelper. The new ImageTagHelper allows you to automatically append image filenames with a cache-buster version number so that you can aggressively cache images with your application, like this:

<img asp-file-version="true" src="~/images/my_cool_image.png" />

  • Tag helper support for binding dictionary properties. You can now bind server side attributes to dictionary properties on your tag helpers. For example, the AnchorTagHelper binds route values for link generation using attributes that follow the asp-route-* pattern, like this:

<a asp-action="Edit" asp-route-id="@index">Edit</a>

  • Support conditionally binding tag helpers based on presence of server-side attributes. You can now specify that tag helper should only be bound to a tag based on the presence of server-side attributes using the Attributes property on TargetElementAttribute.

Be sure to read the Beta5 release notes to find all the details on what’s new as well as known issues. There will be more Betas after this one as we march towards a final release. The final release of ASP.NET 5 will happen AFTER Visual Studio 2015 is released. We’ll announce the schedule very soon.

As I said previously, this ASP.NET 5 runtime update is compatible with Visual Studio 2015 RC. You can open, build and run ASP.NET 5 apps using the Beta5 runtime packages and Visual Studio 2015 RC.

To update to ASP.NET 5 Beta5 use the following steps:

  • Install the .NET Version Manager (DNVM) if you don’t already have it (it comes preinstalled with Visual Studio 2015 RC, or you can get the latest version)
  • From a command prompt set the DNX_FEED environment variable to https://www.nuget.org/api/v2
  • Run “dnvm upgrade”
  • In your app update your global.json to point to eta5 version of the .NET Execution Environment (DNX)
  • Also your project.json to point to the beta5 ackage versions
  • Run “dnu restore”
  • Run “dnu build” and migrate your code to beta5 s needed

There have been quite a few API changes in this release as part of a broad API review. In the process we refactored many of our packages to reduce dependencies and to improve the layering. To help you update your Beta4 code you can find a list of the most impactful changes on our Announcements repo along with details for each change. You can also find docs and samples for ASP.NET 5 at http://docs.asp.net.

We hope you enjoy this release! If you find any issues or have suggestions for improvement please let us know through our public issues trackers on GitHub. Thanks for trying out ASP.NET 5!

Please join us every Tuesday for the ASP.NET Community Standup. The schedule and previous episodes are at http://www.asp.net/vnext.

 

ASP.NET Community Standup - June 30, 2015

$
0
0

This is the first in a series of blog post that will cover the topics discussed in the ASP.NET Community Standup.  The community standup is a short video with some of the leaders of the ASP.NET development teams to discuss the accomplishments of the team on the new ASP.NET 5 framework over the previous week.  Within 30 minutes, Scott Hanselman, Damian Edwards, Jon Galloway and an occasional guest or two discuss new features and ask for feedback on important decisions being made by the ASP.NET development teams.

Each week the standup is hosted live on Google Hangouts and the team publishes the recorded video of their discussion to YouTube for later reference.  This week's meeting is below:

This week's discussion covered the following points:

  • Scott is installing a new Windows 10 build that is publicly available and a new beta5 build of ASP.NET 5
  • Damian recommends that updating ASP.NET 5 from one beta version to another can break significantly.  It is fixable, but the beta builds still contains APIs that may change significantly.
  • The announcement of the ASP.NET 5 beta 5 release is available earlier on this blog. 
  • ASP.NET 4.6 will be a complete release with VIsual Studio 2015 on July 20.  Only the ASP.NET 5 tools and runtimes will be shipped in beta form. 
  • Damian explained that the configuration option during the Visual Studio setup for 'Web Tools' are the WTE or Web Tooling Extension. The ASP.NET team would like to be able to ship this in the future out-of-band, similar to how updates are delivered in the extension gallery or in the NuGet gallery.  Damian promised more planning on this feature delivery option.
  • Damian clarified for Scott that the version of WTE can be found in the 'About Visual Studio' menu option. The ASP.NET and Web Tools are listed on this dialog with the version number clearly defined.
  • The team discussed the option of a weekly WTE feed for those that want to help test features.  The team promised to discuss this further and report back to the standup.
  • Damian has the following schedule tentatively defined for ASP.NET 5:
    • Beta 6 - end of July 2015
    • Beta 7 - end of August 2015
    • Beta 8 - end of September 2015
    • Release Candidate - late fall 2015 - Damian warns that this could be completely inaccurate as it is 6 months into the future.
  • A Release Candidate (RC) contains a Go-Live license that is production-ready with Microsoft Support available
  • Current versions of ASP.NET 5 source code are available under the Apache license and you are welcome to use without any support provided
  • Jon recommends watching the ASP.NET Announcement repository for completed changes to the framework. 
  • Damian reinforced that the goal of ASP.NET 5 is to deliver a framework that provides a very capable production environment on Mac, Linux, and Windows
  • During the community link discussion, Damian commented about the ASP.NET tool acquisition strategy is typically different for the less polished frameworks on Mac and Linux. We are planning to ensure that the ASP.NET delivery strategy will allow developers to choose if they would like an installer or would like to 'install by hand'

Community Links

Q & A

Scott questions if we should expect the average developer should be ready to update ASP.NET frameworks using the command-line and handle changes.  Damian clarified that there is no one-click upgrade story in short term, and these changes will be announced on this blog.

A viewer named Jesse asked for a clarification of the 'Go Live' license.  Damian clarified that this is a legal agreement with Microsoft called an End-User License Agreement that dictates that the framework should not be used in a production environment.  You are welcome to download the code from GitHub and use it under the terms of the Apache license.  Paid support is only provided by Microsoft on products with a Go Live license.

Damian admitted some fears of Australian flora and fauna, but is not afraid of Mac OSX.  He is still learning to use Mac OSX more efficiently, and Scott has some recommendations for him.

 

Viewing all 7144 articles
Browse latest View live