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

Announcing the ASP.NET WebHooks Visual Studio Extension Preview

$
0
0

After a few days of work, I’m excited to introduce you to the ASP.NET WebHooks preview support we’ve put together for Visual Studio developers. This tool bootstraps your ASP.NET project with the NuGet packages and configuration code you’ll need so you can add custom processing for incoming WebHook requests from third parties like GitHub, Dropbox, and more. The 7-minute video embedded below demonstrates and end-to-end user experience offered by the WebHooks extension.

Over the past few weeks Henrik has been busy developing framework NuGets that enables WebHook support for ASP.NET, and he’s documented each step of the evolution of ASP.NET WebHooks on this blog. I’d highly encourage you take a look at some of these posts as context for how things work and what you can accomplish with the WebHooks preview:

When I first saw the NuGets I realized we had a great opportunity to streamline things for developers who want to light up WebHook-reception support in their web apps. So let’s jump right in and explain how the WebHook tool can make life better. 

How this WebHook extension simplifies your life

In the video above, you’ll see that the WebHooks wizard streamlines the process of selecting which WebHooks you want to support and for providing secrets that will be used to authenticate incoming requests. In most cases, the single variation in configuring individual incoming WebHooks is that each probably has it’s own secret. In my example scenario, I’ve created a custom SHA1 hash my app expects to be sent when GitHub calls me, and I need to use the Dropbox application secret. So the wizard first finds out which WebHooks I’d like to receive:

image

Then it captures the secrets for each of them individually. For the time being these are persisted into Web.config, but we see other opportunities – persisting them to config.json for vNext projects, persisting them directly into my Azure Web App settings. Crawl, walk, run…

image

Once the information is captured the NuGets are downloaded based on the list of providers I selected, and some code is added to my project that lights up the WebHooks I selected using the configuration extension methods available in each WebHook Receiver NuGet package.

The code for WebHookConfig.cs is shown below, after it was dropped into the App_Code folder of my Visual Studio project. It simply wires up each of the individual receivers according to the convention in place already.

image

For each of the selected receivers, a class is added to the project that inherits from the WebHookHandler class, the base class for all WebHook handler customizations you intend on doing. Each receiver is identified by name, with the name being used in the route wire-up, so each generated handler checks to see if it’s the one who should be handling the incoming requests. The Dropbox generated handler is below. The single change in the GitHub generated handler would be that it’s checking the receiver’s value against the string “GitHub,” and so on. In this way, you can light up multiple incoming WebHook requests, but only process according to the receiver’s context on your own.

image

The video demonstration walks through this in more detail, so I’d encourage spending a few minutes watching it to see the entire experience in action. None of the details are locked – this is a preview – so any feature ideas you have are on the table. Furthermore, the code for the ASP.NET WebHooks extension is open source and on GitHub, so feel free to fork the repository and improve it, submit issues and requests for ideas, and so on.

How can you install the extension

The extension is published into the Visual Studio Extensions Gallery, and can be downloaded in one of three ways. You can either go to the official Visual Studio Extensions Gallery download page here. With my buddy Mads Kristensen’s help, I have wired up a CI build of the extension so that each commit will rebuild and re-publish the extension into the VsixGallery.com extensions gallery. So if you’re amped on keeping up with the nightly builds of the extension as it evolves, you should install it from the VsixGallery page here. Alternatively, you can install the extension directly in Visual Studio using the “Extensions and Updates” dialog, as shown below. Simply search for “WebHooks” and it’ll pop up from either the official Visual Studio Extensions gallery or from the VsixGallery.com feed.

image

Summary and a feedback request

This tooling was written as a sidekick to Henrik’s WebHooks functionality and was inspired by it and my desire to make use of the new Connected Services SDK in Visual Studio to build something interesting and valuable for the community, so I'm interested in hearing some feedback in the comments, and would entertain some feature ideas in the GitHub repository storing the tooling code.

And again, this tool is a preview tool, so it may have some imperfections and bruised corners. If you see any, please submit an issue on the GitHub repository and well try to help. If you want to make some changes and get the code published, let’s discuss – overall the PR-approval process will be pretty quick and painless.


Receive WebHooks from Azure Alerts and Kudu (Azure Web App Deployment)

$
0
0

The Microsoft ASP.NET WebHooks preview is moving forward! We have received two very cool source contributions adding support for Kudu (Azure Web App Deployment) and Bitbucket. There is a sample for Bitbucket, but here we will focus on Kudu as well as Azure Alerts which just announced support for WebHooks.

Kudu provides a ton of functionality for deploying, managing, and inspecting Azure Web Apps (formerly known as Azure Web Sites). The source code for Kudu is available on GitHub along with documentation describing all the cool things it can do. One way you can use Kudu WebHooks is to get notified when an update has been deployed, which is what we will show in this post.

Azure Alerts allow you to monitor a wide variety of your Azure resources including Azure Web Apps, Azure SQL, and more. For each resource you can add an alert rule detailing a condition for when you want to get notified. For an Azure Web App, this may be if the number of HTTP 500 status codes suddenly increases, or the CPU spikes. For your Azure SQL Server, this may be if the number of broken connections spikes, or the total DB size increases dramatically.

Configuring Kudu and Azure Alert Handlers

Let’s first create an empty Web Application with Web API in Visual Studio which we will use for receiving WebHooks from Kudu and Azure Alerts. Set it up for deployment in Azure by checking Host in the cloud:

EmptyProject

Install the Microsoft.AspNet.WebHooks.Receivers.Azure Nuget package. Then the registration happens exactly like in the blog Introducing Microsoft ASP.NET WebHooks Preview by adding these two lines to the WebApiConfig.Register method:

publicstaticclass WebApiConfig
{
publicstaticvoid Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

config.InitializeReceiveKuduWebHooks();
config.InitializeReceiveAzureAlertWebHooks();
}
}

Now add two handlers, one for Kudu and one for Azure Alerts. Add a class called KuduWebHookHandler looking like this:
 
publicclass KuduWebHookHandler : WebHookHandler
{
public KuduWebHookHandler()
{
Receiver = "kudu";
}

publicoverride Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// Convert to POCO type
KuduNotification notification = context.GetDataOrDefault<KuduNotification>();

// Get the notification message
string message = notification.Message;

// Get the notification author
string author = notification.Author;

return Task.FromResult(true);
}
}
 
Similarly, add another class called AzureAlertWebHookHandler for Azure Alerts that look like this:
 
publicclass AzureAlertWebHookHandler : WebHookHandler
{
public AzureAlertWebHookHandler()
{
Receiver = "azurealert";
}

publicoverride Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// Convert to POCO type
AzureAlertNotification notification = context.GetDataOrDefault<AzureAlertNotification>();

// Get the notification status
string status = notification.Status;

// Get the notification name
string name = notification.Context.Name;

// Get the name of the metric that caused the event
string author = notification.Context.Condition.MetricName;

return Task.FromResult(true);
}
}

Finally, add two application settings with two secrets so that we can validate that the WebHook requests indeed come from Kudu and Azure Alerts respectively. As always, use high-entropy values such as a SHA256 hash or similar, which you can get from FreeFormatter Online Tools For Developers. Also, set them through the Azure Portal instead of hard-coding them in the Web.config file.

<appSettings>
<addkey="MS_WebHookReceiverSecret_Kudu"value="32-128 bytes of high entropy data"/>
<addkey="MS_WebHookReceiverSecret_AzureAlert"value="32-128 bytes of high entropy data"/>
</appSettings>

That’s it for the receiver Web App – it is now ready to deploy to Azure. Note the URI of the site as you will use it when setting up the WebHooks.

Configuring Kudu WebHook

To show both Kudu and Azure Alerts WebHooks in action, let’s set up another Azure Web App and then use WebHooks to get information from Kudu and Azure Alerts about new deployments and changes in how the Web App operates. Go to the Azure Portal and create a Web App, it should look something like this:

WebAppConfig

For now, we just leave the site completely empty. To get to the associated Kudu site, go to Tools and then Kudu which will take you to a site looking like this:

KuduHome

Select Tools and then WebHooks and enter a PostDeployment URI of your Kudu WebHook handler:

https://<host>/api/webhooks/incoming/kudu?code=<secret hash from above>

The ‘host’ is the name of the receiver site. For security reasons, the URI has to be an ‘https’ URI and the code is what we use to verify that the request comes from Kudu. If you want to have multiple WebHooks for the same handler then you can use the optional {id} to differentiate, for example:
 
https://<host>/api/webhooks/incoming/kudu/{id}?code=<secret hash from above>

In this case, the corresponding application setting should look like this:
 
<appSettings>
<addkey="MS_WebHookReceiverSecret_Kudu"value="{id}=32-128 bytes of high-entropy data"/>
</appSettings>

Configuring Azure Alert WebHook

Go back to the Azure Portal for your Web App and find the Operations lens, select Alert Rules (you might have to scroll down on the Web App blade to see it), and then Add Alert. The WebHook URI follows the same pattern as the Kudu WebHook but looks like this:
 
https://<host>/api/webhooks/incoming/azurealert?code=<secret hash from above>
 
In this example we set up a trivial alert firing after more than one 200 OK Response within 5 minutes, but you can make it whatever you want.
 
AzureAlert

Trying it Out

We are now ready to try things out. If you want to follow along then attach the debugger to the receiver project, you deployed before.

Remember that we didn’t actually add any content to the first Web App we created? That is the Web App that we want to monitor and have set up WebHooks for. Let’s now add some by doing a deployment so that we can see that the WebHooks trigger. There is a lot of great information in the blog Continuous deployment using GIT in Azure App Service for how to get set up. Here we use a very simple local repository using the following commands:

git init
git remote add azure https://<username>@<host>.scm.azurewebsites.net:443
echo hello! > index.html
git add index.html
git commit -m "First commit!"
git push azure master

Once you push, you should get called in your Kudu handler looking something like this:

KuduWebHook

Try and hit the site a few times and wait for 5 minutes or so. You should now get called in the Azure Alert handler as a result of the alert firing:

AzureAlertWebHook

That’s it – you can now listen for events from both Kudu and Azure Alerts.

Have fun!

Henrik

Announcing Availability of ASP.NET 5 Beta8

$
0
0

ASP.NET 5 beta8 is now available both on NuGet and as a tooling update to Visual Studio 2015! This release greatly expands the supported surface area of .NET Core on OS X and Linux. You can now use networking, cryptography and globalization features cross-platform! This release also includes some nice improvements to ASP.NET 5, DNX and the Web tools. Let’s take a look at how we can get started with ASP.NET 5 beta8.

Installation

You can find instructions in our documentation for installing ASP.NET 5 beta8 on Windows, Mac and Linux.

New Features

Below is a summary of some of the new features in ASP.NET 5 beta8. For a full list of what is new in this release please refer to the beta8 release notes.

Changes to IIS Hosting Model

We’ve made a major update to the IIS hosting model for ASP.NET 5 in beta8. Up to and including beta7, ASP.NET 5 applications running in IIS have been hosted by a component named "Helios", contained in the Microsoft.AspNet.Server.IIS package. This component facilitated the bootstrapping of DNX and CLR using a hook in the existing System.Web hosting model. This hook replaced the runtime after the application had started (from IIS's point of view). This effectively made "Helios" a second DNX host, meaning it contained its own logic pertaining to locating, booting, and loading the runtime. It also meant a second set of logic to enable things like runtime servicing, as well as configuration of certain DNX-level settings.

Having two distinct hosting models for ASP.NET 5 introduced a number of complexities and inconsistencies that were difficult or impossible to resolve. To address this we're discontinuing the "Helios" IIS host. Hosting ASP.NET 5 applications in IIS will now be achieved using the IIS HttpPlatformHandler configured to forward through to the ASP.NET 5 Kestrel server. The HttpPlatformHandler is a native IIS module that needs to be installed by an administrator on the server running IIS (installers: x86, x64). It’s also already included with the beta8 Web tools update for local development on IIS Express. This native IIS module manages the launching of an external application host process (in this case dnx.exe) and the routing of requests from IIS to the hosted process.

Simplifying the model to a single hosting option (but the same scenarios still supported) means less things for developers to code for and test. Additional benefits of the new model include:

  • The IIS AppPool doesn't need to run any managed code (you can literally configure it to not load the CLR at all)
  • The existing ASP.NET Windows component does not need to be installed to run on Windows Servers
  • Existing ASP.NET 4.x modules can run in IIS alongside the HttpPlatformHandler since the ASP.NET 5 process is separate
  • You can set environment variables per process since HttpPlatformHandler supports it. It will make setting things like the ASP.NET 5 environment configuration possible on local IIS servers.
  • Unified error handling for startup errors across all servers
  • Code and behavior unification
    • Support for app.config when running on .NET Framework (full CLR) whether self-hosted or in IIS (no more web.config even for .NET Framework compatibility)
    • Unified servicing story
    • Unified boot-up story (no odd AspNetLoader.dll in the bin folder)

You’ll notice that the ASP.NET 5 project templates in Visual Studio have been updated to include the following web.config file in the wwwroot folder of your application:

<configuration><system.webServer><handlers><add
        name="httpPlatformHandler"
        path="*"
        verb="*"
        modules="httpPlatformHandler"
        resourceType="Unspecified"/></handlers><httpPlatform
      processPath="%DNX_PATH%"
      arguments="%DNX_ARGS%"
      stdoutLogEnabled="false"
      startupTimeLimit="3600"/></system.webServer></configuration>

This web.config file adds the HttpPlatformHandler to your application and configures the handler to forward requests to a DNX process. Visual Studio handles setting up the DNX_PATH environment variable to point to the appropriate DNX version for your application.

When you publish your application the process path in web.config is updated to point to the “web” command defined by your application. You can opt to use a different command instead using the --iis-command option when running dnu publish.

For more details on these changes to the IIS hosting model please see the corresponding announcement.

Localization

ASP.NET 5 now has built-in support for localization. The new localization support provides middleware for specifying the correct culture and UI culture on the thread based on the request and also mechanisms for accessing localized content based on the current culture.

You enable localization in your application by adding the request localization middleware to your request pipeline in your Startup class:

app.UseRequestLocalization(options)

The request localization middleware uses a set of configured IRequestCultureProvider implementations to determine the culture for the request. Built-in providers can determine the culture from the request using the Accept-Language header, a query string value, or from a cookie. You can also build and specify your own IRequestCultureProvider.

Once the request localization middleware determines the current culture it sets it on the thread. The IStringLocalizer service then provides access to localized content based on the current culture. You enable support for these localization services like this:

services.AddLocalization(options => options.ResourcesPath = "resources");

The ResourcePath specifies the path where the localized resources are located relative to the application root. You can use the IStringLocalizerFactory service to create an IStringLocalizer for a specific resource or simply request an IStringLocalizer<T> directly.

The default implementations of these services is based on System.Resources.ResourceManager, which supports accessing localized content in satellite assemblies based on resx files. You can alternatively provide your own implementations for accessing localized content from different sources, like form a database.

You can see a full working sample of these localization features in the Localization repo.

Localization and MVC

MVC builds on the new localization support in ASP.NET 5 to enable localization in controllers and views. MVC introduces a few of additional services for localization built on the core localization services.

To enable the MVC specific localization features, you add the following when configuring the MVC services:

services
    .AddMvc().AddViewLocalization(options => options.ResourcesPath = "Resources");

The IHtmlLocalizer service (with accompanying IHtmlLocalizerFactory) adds support for getting localized HTML strings with property encoded arguments. You can use an IHtmlLocalizer from your controllers like this:

private IHtmlLocalizer<HomeController> SR;

private IHtmlLocalizer<HomeController> SR;

public HomeController(IHtmlLocalizer<HomeController> localizer)
{
    _localizer = localizer;
}

public ActionResult Index()
{
    ViewData.Message = SR["Localize me!"];
    return View();
}

The  IViewLocalizer is an IHtmlLocalizer service that looks for a resource based on the current view name. You can inject an IViewLocalizer into your view using the @inject directive, like this:

@inject IViewLocalizer SR<h1> @SR["Localized header"]</h1>

MVC also provides a LanguageViewLocationExpander that enables the view engine to look for views that are suffixed with a specific culture. For example, you can have index.html and index.en-GB.cshtml. Which view is selected will be based on the current culture.

Error messages from validating data annotations can be localized by adding the following option when setting up the MVC services:

services
    .AddMvc()
    .AddViewLocalization(options => options.ResourcesPath = "Resources").AddDataAnnotationsLocalization();

Any validation error messages from data annotations will then be localized using the available IStringLocalizer service.

DNX Watch command

The dnx-watch command will run your application and then watch all of the project files for changes. When a file is changed the dnx-watch command restarts the application. This enables a rapid development workflow where you edit the code, save, and then refresh your browser to see the changes.

To install the dnx-watch command run the following:

dnu commands install Microsoft.Dnx.Watcher

You can then start the dnx-watch command from the same directory where your project.json is located. Any arguments passed to dnx-watch will get passed along to dnx:

C:\Users\danroth27\Documents\WatchTest\src\WatchTest>dnx-watch web
[DnxWatcher] info: Running dnx with the following arguments: --project "C:\Users\daroth\Documents\WatchTest\src\WatchTest\project.json" web
[DnxWatcher] info: dnx process id: 8348
Hosting environment: Production
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Browse to your application to see the current content:

 

Modify your code and save the file:

public IActionResult About()
{ViewData["Message"] = "Watch this!";

    return View();
}

Refresh the browser to see the changes:

Better view precompilation

We’ve improved precompilation of MVC views in this release to work seamlessly with tag helpers. You can now use view precompilation even when using custom tag helpers in your views.

Specify target frameworks when publishing

When publishing an application, you can now specify the target framework that you want to publish for:

dnu publish –framework dnx451

This will trim the set of packages included in the published app to just the packages required for the specified target framework resulting in a smaller deployment payload.

Clear the HTTP response cache used for package restore

When restoring packages dnu will normally do HTTP response caching for any requests sent. You can now easily clear the HTTP response cache by running:

dnu clear-http-cache

Target .NET 2.0 and .NET 3.5

You can now target .NET 2.0 and .NET 3.5 in your DNX projects. Simply use the net20 and net35 target framework monikers in the frameworks node of your project.json file.

Running scripts before and after building and creating packages

One of the nice features of DNX is that it will handle building for multiple target frameworks (ex net46, dnxcore50, etc.) and multiple build configurations (ex Debug, Release). In project.json you can define command-line scripts that run before and after each build and package creation. Previously these scripts would only run once, but in this release the scripts will run before each build configuration and each target framework.

For example, if you have two build configurations (Debug and Release) and two target frameworks (net46 and dnxcore50) then the prebuild and postbuild scripts will run four times: once for each build configuration and once for each target framework. The prepack and postpack scripts will run twice: once for each build configuration.

In your prebuild and postbuild scripts you can use the %build.Configuration% and %build.TargetFramework% variable to get access to the current build configuration and target framework. The %build.Configuration% variable is also available in your prepack and postpack scripts.

Add additional files to a package

DNX generally handle generating NuGet packages for your projects for you, but sometimes you need to add additional files to the packages. You can now specify additional content files for your NuGet packages in project.json using the new packInclude property:

"packInclude": {
    "destination1/": "source1/**",
    "destination2/": "source2/**",
    "destination2/some_additional_file.txt": "source2a/somefile.txt",
    "destination3/": ["source3/a.txt", "source3/b.txt", "source4/c/**/*.ps1"]
}

The packInclude property specifies a set of destinations in the package and the source files that should be included at those destinations. You can use globing patterns when specifying source files to include or list individual files in an array. The destination can be a specific file name and path or it can be a directory. To specify a directory as the destination you include a trailing slash.

When you build your package all of the specified source files will get included in the package at the specified locations.

Explicitly target dependencies at packages or projects

When DNX resolves dependencies specified in project.json it will resolve dependencies as installed packages or as project references. This gives you the flexibility to swap out package dependencies as source code or vice versa. But sometimes you want to be explicit about the target type for the dependence. For example, you may want to make sure that you don’t accidentally resolve a dependency from a configured NuGet feed that should really just be a project reference.

You can now explicitly specify the target type for a dependency in project.json to ensure that the dependency only comes from a package or a project:

"dependencies": {
    "ClassLibrary1": { "version": "1.0.0-*", "target": "project" },
    "ClassLibrary2": { "version": "1.0.0-*", "target": "package" }
}

The target property for ClassLibrary1 indicates that it’s a project reference, not a package. Similarly, the target property for ClassLibrary2 indicates it’s a package, not a project. If the target property is not specified, then the target can be either a package or a project.

Dnvm uninstall

For those of you who have been keeping up with all the latest DNX release updates you probably have quite a few older versions of DNX hanging out on your machine. You can always go into your user profile and delete the folder for a specific DNX from the ~/.dnx/runtimes folder. But now there is an even easier way. The DNVM tool now supports uninstalling specific versions of DNX. Simply run dnvm uninstall <VersionOrAlias> to uninstall a specific DNX version from your machine and it will delete the corresponding runtime folder for you.

New Visual Studio 2015 Features for ASP.NET 5

Hiding files in Solution Explorer

In this release we have added the ability to hide files from the default view in Solution Explorer. To hide a file, in Solution Explorer you can use the new Hide from Solution Explorer context menu option. In the image below, you can see the context menu for a file that I’m going to hide from Solution Explorer.

After using Hide from Solution Explorer the item will no longer show up in Solution Explorer. This is facilitated by adding a new entry into the .xproj file. For the case above the new entry in the .xproj file is.

<ItemGroup><DnxInvisibleContent Include="myhiddenfile.txt" /></ItemGroup>

After the file is hidden from Solution Explorer you will not see it by default. If you need to interact with hidden files you can use the Show All Files button on Solution Explorer. You can see this being used in the screenshot below.

Info bar when restoring NuGet packages

One piece of feedback from users on the new ASP.NET 5 experience that we have received is that it’s not clear when NuGet packages are being restored. This is because Visual Studio 2015 will automatically restore NuGet packages as needed. For example, when you open a project, if NuGet packages are missing they will be restored. Similarly when you edit project.json to add a new dependency, that will kick off a NuGet restore. There are other times when Visual Studio starts a restore.

To make it more clear when a NuGet package restore operation is in progress we have introduced a new info bar for ASP.NET 5 projects. Now when a NuGet package restore is in progress you’ll see the following info bar in Solution Explorer.

The info bar at the top of Solution Explorer indicates that a restore is in progress and how many projects are participating in that. Directly from the info bar you can open the output of the restore operation with the Output link. You can also click on Settings so that you can configure the behavior of the info bar. In the settings page you can specify when the info bar should show up.

Show dependency errors in project.json and Solution Explorer

In previous releases if there were any issues with dependencies you would have to go to the output window, or Error List, to see errors and warnings about packages. With this release we have integrated showing dependency errors/warnings directly in project.json and Solution Explorer.

In the image below, I’ve modified the BrowserLink dependency to have an invalid version and also added a new entry to a dependency which doesn’t exist, SomeMissingPackage. In the image below you can see that both of those entries in project.json have squiggles indicating an issue.

When you hover over an entry in project.json you’ll see the corresponding error/warning message. For example, see the image below.

Dependency issue are also now indicated in Solution Explorer as well. In the image below you can see the view in Solution Explorer for the sample above.

In the previous image the icon for the BrowserLink and SomeMissinagePackage have a Warning icon. In addition to this, you can see dependency errors and warnings in the Error List.

Update NuGet package view in Solution Explorer

In Solution Explorer we have updated the view under the References node for ASP.NET 5 projects. In previous releases, we used the blue NuGet icon for every NuGet package. We also used a generic icon for a project-to-project reference. In the image below you can see the improved view.

In the image above there are a few changes. The icon for NuGet package references has been updated to one that fits better with the other icons in Solution Explorer.

The icon for a project-to-project icon has been updated so that it’s clear that it’s a project-to-project reference. Project-to-project references will always be shown at the top of the list.

As well as icon updates we also show Framework Assemblies at the bottom of the reference list. This shows the assemblies that are available coming from the framework.

Open source templates

Lastly, our Visual Studio project templates for ASP.NET 5 and DNX are now open source on GitHub! The Templates repo contains the templates used in Visual Studio for ASP.NET 5 and DNX based projects (ASP.NET 4.6 templates are still managed separately). You can now contribute to the template code and provide feedback via the public Templates issue tracker.

Summary

This release includes a variety of new runtime features and tooling enhancements. Please download and try out ASP.NET 5 beta8 today and let us know what you think on GitHub. We hope you enjoy it!

.NET Core and ASP.NET Launches a Beta Bug Bounty Program.

$
0
0

A guest post from Barry Dorrans, the security lead for ASP.NET

Today, with great excitement, we announce an introductory 3 month bug bounty program for .NET Core and ASP.NET, our new open source, cross platform runtime and web stack. The program encompasses the latest beta version, beta 8 and any subsequent beta or release candidates released during the program period.

We recognize that you, our customers, rely on our platforms and development tools to write your own software. The more secure we can make our frameworks the more secure your software can be. We take your trust seriously and this program is part of our investment in improving the security of our frameworks on all platforms. Starting a bounty program during our beta period allows us to address issues quickly and comprehensively. We are able to reward and recognize security researchers for their hard work and for any qualifying security bugs they report to us under the aegis of the program. This is the right thing for our customers and for the security researcher community.

The bounty includes all supported platforms .NET Core and ASP.NET runs on; Windows, Linux and OS X. However with the first eligible release, beta 8, we are excluding the networking stack on Linux and OS X. In later beta and RC releases, once our cross platform networking stack matches the stability and security it has on Windows, we'll include it within the program. When this happens we'll update the bounty terms and conditions and make a blog post on this blog. The ASP.NET web site has instructions on how to install beta 8 on Windows, Linux and OS X. Windows researchers can use Visual Studio 2015, including the free Visual Studio 2015 Community Edition, after following the instructions to update the web tooling. The source for .NET Core can be found on GitHub at https://github.com/dotnet/corefx. The source for ASP.NET v5 can be found on GitHub at https://github.com/aspnet.

We encourage you to read the program terms and FAQs before beginning your research or reporting a vulnerability. We would also like to applaud and issue a hearty and grateful thanks to everyone in the community who has reported issues in .NET and ASP.NET in the past. We look forward to rewarding you in the future as we take .NET and ASP.NET cross platform.

Updates to Microsoft ASP.NET WebHooks Preview

$
0
0

We just released Beta4 of ASP.NET WebHooks Preview with a nice set of new features based on feedback and help from the community! Always let us know what you think – either by raising a issue on GitHub or pinging me on twitter. You can get the update from nuget.org by looking for the packages under Microsoft.AspNet.WebHooks.*. If you haven’t heard about ASP.NET WebHooks then you may want to look at Introducing Microsoft ASP.NET WebHooks Preview.

Here’s what’s new:

Storing WebHook Registrations in SQL

This feature is from a pull request from Ryan Posener -- thanks! It enables storing Custom WebHook Registrations in a SQL server. Before this we could store them in Azure Table Storage, but with support for SQL, developers have much more flexibility in where to store them. Now, when setting up custom WebHooks, you can include the Microsoft.AspNet.WebHooks.Custom.SqlStorage package and wire it up in the WebApiConfig.cs file:

publicstaticclass WebApiConfig
{
publicstaticvoid Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Load basic support for sending WebHooks
config.InitializeCustomWebHooks();

// Use SQL for persisting subscriptions
config.InitializeCustomWebHooksSqlStorage();

// Load Web API controllers for managing subscriptions
config.InitializeCustomWebHooksApis();
}
}

Set the connection string in the Web.config file of your Web Application project, something like this:

<configuration>
...
<connectionStrings>
...
<addname="MS_SqlStoreConnectionString"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
Initial Catalog=WebHooks-20151029053732;Integrated Security=True"

providerName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>

Finally, you need to initialize Entity Framework Code First Migrations to create and initialize the DB. In Visual Studio, open Package Manager Console from the Tools\Nuget Package Manager menu and make sure your Web Application project is the Default Project:
 
NugetConsole

From the Package Manager Console run the following three commands, one after another, for initializing migrations and to initiate the DB:

Enable-Migrations -ContextAssemblyName Microsoft.AspNet.WebHooks.Custom.SqlStorage
Add-Migration WebHookStoreInitialDB
Update-Database

That’s it – you are now ready to store WebHook registrations in your SQL server of choice! For a full example of how to use this, please see our new Custom WebHooks sample projects below.

Custom WebHooks Sample Projects

We added two Custom WebHook sample projects following the path for setting up Custom WebHooks described in the blog Sending WebHooks with ASP.NET WebHooks Preview. The CustomSender project covers the sending part of Custom WebHooks and the CustomReceiver project covers the receiving part. These sample projects (along with the other sample projects) hopefully make it simpler to try things out.

Slack Slash Commands

Slash Commands enable Slack users to interact with external services directly from Slack. Slash commands start with a slash ‘/’ and can be wired up much like Outgoing WebHooks. That is, you can define a Slash Command to trigger an HTTP request with additional data to do something, for example:

/henrik do something!

To set up a Slash Command you just follow the instructions for a Slash Command like this:

SlashCommand

On the ASP.NET WebHooks side, the setup works exactly as for Slack Outbound WebHooks described in the blog Integrating with Slack Using ASP.NET WebHooks Preview. In addition, there now is a Slack sample which you can also use.

Instagram Receiver Improvements

We added some more types making it simpler to use Instagram WebHooks and also added a sample illustrating the new model. Here’s a sample handler looking for both image and videos (if present):

publicoverride async Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// Get the WebHook client
InstagramWebHookClient client = Dependencies.Client;

// Convert the incoming data to a collection of InstagramNotifications
var notifications = context.GetDataOrDefault<InstagramNotificationCollection>();
foreach (var notification in notifications)
{
// Use WebHook client to get detailed information about the posted media
JArray entries = await client.GetRecentGeoMedia(context.Id, notification.ObjectId);
foreach (JToken entry in entries)
{
InstagramPost post = entry.ToObject<InstagramPost>();

// Image information
if (post.Images != null)
{
InstagramMedia thumbnail = post.Images.Thumbnail;
InstagramMedia lowRes = post.Images.LowResolution;
InstagramMedia stdRes = post.Images.StandardResolution;
}

// Video information
if (post.Videos != null)
{
InstagramMedia lowBandwidth = post.Videos.LowBandwidth;
InstagramMedia lowRes = post.Videos.LowResolution;
InstagramMedia stdRes = post.Videos.StandardResolution;
}

// Get direct links and sizes of media
Uri link = post.Link;
}
}
}

Receivers Behind Firewalls

In certain cases, a WebHook receiver may sit behind a firewall or gateway that forwards requests as non-HTTPS requests, i.e. just as plain-text HTTP. In this case, the default WebHook receiver check that requires use of HTTPS will fail preventing the WebHook from being processed. This check can now be suppressed by setting the 'MS_WebHookDisableHttpsCheck' Application Setting to ‘true’. That is, if ‘true’ this will cause regular HTTP requests to go through. Obviously this setting should be used with caution!

WebHookManager Updates

We added a constructor for WebHookManager which enables wiring up the default IWebHookManager implementation with a custom retry policy and the level of concurrency used when sending out event notifications in the form of WebHook requests. Here is an example of initializing Custom WebHooks using Autofac Dependency Injection engine registering WebHookManager with a custom policy:

publicstaticvoid Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Load basic support for sending WebHooks
config.InitializeCustomWebHooks();

// Load Azure Storage or SQL for persisting subscriptions
config.InitializeCustomWebHooksAzureStorage();

// Load Web API controllers for managing subscriptions
config.InitializeCustomWebHooksApis();

// Create custom WebHookManager with custom retry policy
ILogger logger = config.DependencyResolver.GetLogger();
IWebHookStore store = config.DependencyResolver.GetStore();
IWebHookManager manager = new WebHookManager(store, logger, new TimeSpan[] { }, null);


// Register WebHookManager with Autofac
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterInstance(manager).As<IWebHookManager>().SingleInstance();

// Register MVC and Web API controllers with Autofac
Assembly currentAssembly = Assembly.GetExecutingAssembly();
builder.RegisterApiControllers(currentAssembly);
builder.RegisterControllers(currentAssembly);

// Build the Autofac container and set it as the dependency resolver for both MVC and Web API
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}


We also added a new generic JSON WebHook receiver, but we will demonstrate that in a separate blog so stay tuned :)

Have fun and keep the feedback coming!

Henrik

Announcing ASP.NET 5 Release Candidate 1

$
0
0

As scheduled on our ASP.NET 5 roadmap and demonstrated during the Connect() event, we are proud to announce the availability of runtime and tooling for the RC1 release of ASP.NET 5.  The framework and enhanced web development tools are available with Visual Studio 2015 Update 1, or you can install the framework and tools from the new http://get.asp.net site.  There are instructions, downloads, and samples there for you to learn more about the new ASP.NET 5.  The complete release notes for this RC version are also available online.

NOTE: There is currently a known issue with the ASP.NET 5 RC installer. If you run the installer from a folder that contains previous versions of the MSI installers for DNVM (DotNetVersionManager-x64.msi or DotNetVersionManager-x86.msi) or the ASP.NET tools for Visual Studio (WebToolsExtensionsVS14.msi or WebToolsExtensionsVWD14.msi), the installer will fail with an error “0x80091007 - The hash value is not correct”. To work around this issue, run the installer from a folder that does not contain previous versions of the installer files.

Unlike the beta releases of ASP.NET 5, this release candidate does not have significant new framework features but does have a number of programming model changes that you should be aware of if you are migrating from a beta version of ASP.NET 5.  In this post, we’ll review some of the new Visual Studio features and highlight some of the important framework changes.

Visual Studio Updates

Get Started with ASP.NET 5 RC

When you initially download and install the Visual Studio 2015 Update 1, you will not immediately have the ASP.NET 5 RC tools installed and available.  When you start a new Web Project you will be presented with the ‘New ASP.NET Project’ window to choose a web application template, and among the templates is a ‘Get ASP.NET 5 RC’ template.  When you choose that template, we will install the RC version of ASP.NET 5 tools and frameworks.


Before

After

The familiar three ASP.NET 5 templates Empty, Web API, and Web Application are then available after the installation completes.

Bootstrap Snippets

To help direct developers towards building web applications with responsive interfaces that work on any device, we are introducing bootstrap snippets as a recommended extension when you start editing HTML or CSHTML pages in an ASP.NET 5 project.  You will receive a suggestion at the top of the Visual Studio editor that indicates recommended extensions are available.  Once accepted, a window appears that will show you the recommended extensions.

This extension installation needs to be completed only once per Visual Studio install and does not need to be repeated for every project.  The result is a collection of almost 40 HTML snippets that will be added to the Visual Studio toolbox for HTML and CSHTML pages to help create widgets and layouts using the bootstrap CSS framework.

New Bower Package Manager UI

In Visual Studio 2015 there has been a NuGet package manager user interface for managing libraries and content on the server-side.  With ASP.NET 5, we recommend using Bower for delivering and managing client-side features like CSS, JavaScript, and Font libraries but have not had a user-interface for managing these references.  You can access the bower package manager by right-clicking on the ASP.NET project name in the solution explorer and choosing ‘Manage Bower Packages’ in the context menu.

The user interface presented is similar to the new NuGet package manager, however it is populated with Bower packages and searches Bower endpoints.

Not all of the information provided by the NuGet package details is available in Bower package data, but we will do our best to populate as much information about the Bower package as possible on the right panel.  When you install / update / uninstall a package, an appropriate entry for that package and version will be written into the bower.json file and Visual Studio will perform that task.

Incompatible NuGet Packages

In an effort to help with Bower adoption, we have introduced a new feature in the NuGet package manager user interface to show Bower recommendations.  For popular packages we have identified that have client-side contents, this feature will recommend you use Bower in ASP.NET 5 projects and provide a link to the matching Bower package.

 

MVC Scaffolding

With this release, we are updating MVC Scaffolding to work with ASP.NET 5.  Initially only available in projects that have authentication configured, you can again right-click on a folder in your project and choose to ‘Add -> New Scaffolded Item’ to your project.

The familiar configuration windows from previous versions of ASP.NET will appear and allow you to define how you would like your MVC Controller, API Controller, or Razor Views configured.

Solution Explorer Cleanup

With the new interactions between ASP.NET, Gulp, Bower, and npm we knew that the Solution Explorer view was getting a bit crowded.  To help simplify and lead developers to use tools in Visual Studio we moved some items around and hid others from view.  Consider this initial view of a new project in Solution Explorer:

You will notice that the bower.json file is not present, and the Dependencies element is underneath the wwwroot element.  With the new Bower package manager interface, we want to encourage using this more user-friendly technique to install packages.  The package.json file used by npm is hidden by default as well.  You can make these hidden files appear in the window by clicking the ‘Show all items’ button at the top with the toolbar icon that looks like a stack of cards.  While these files are not visible, they are committed to source control.

We have removed the hosting.ini file and instead we are recommending that a hosting.json file be used in its place.  The lack of this file in a project means that the default configuration of the host listening on port 5000 will be used.

The ViewModels that were in older versions of ASP.NET MVC Models folder have been placed into separate files and placed in appropriately named folders under the ViewModels folder in the default project configuration.  This should help make it clearer what and where these objects come from while building an ASP.NET MVC application.

Framework and Runtime Updates

Static Void Main

In order to more closely align with the syntax of an application entry point in other versions of the CLR, a new web application entry point has been introduced in the familiar “static void main” syntax.  Starting with this version of ASP.NET 5 templates, you will find a single line at the bottom of the Startup.cs file:

public static void Main(string[] args) => WebApplication.Run(args);

This directive mapping gives the dnx a clear entry point in your code to start the web application.  Optionally, you could convert this into an explicit method body to perform any other tasks that you want your application to handle before the host starts and initializes the web application with the other methods in the Startup class.  Another option with the Main method is that it can return an integer instead of void if you would like to be able to signal error codes from your application. For more details please see the announcement on GitHub.

Cross-platform SQL Client

With the RC, we are taking another large cross-platform step by introducing a beta version of a cross-platform capable SQL client library.  In the default templates, you will find this library included indirectly by the EntityFramework.MicrosoftSqlServer package.

With this library, you can now have ASP.NET query SQL Servers from Windows, Mac, and Linux.  The only limitation at this release currently is that you must disable multiple active recordsets in the connection string to access the SQL Server.

"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MyCoolWebsite;Trusted_Connection=True;MultipleActiveResultSets=false"

There is a known issue on some platforms where the System.Net.Security package is not properly loaded by DNX.  If you encounter an error where this package is not located for the SqlClient, you can explicitly add the System.Net.Security package to your project.json configuration to work around this issue.

Default webroot folder

In the beta versions of ASP.NET 5, the base folder for the static content of an application was defined with the “webroot” configuration property in the project.json file.  After reviewing how this configuration option was used and to provide a clearer definition of the content of the project.json file, it was decided to move the webroot configuration option to a hosting.json file that lives next to the project.json file.  The ASP.NET 5 hosts will no longer honor this configuration parameter in project.json

However, the ASP.NET hosts are smart if you do not have a hosting.json file with a webroot parameter configured.  If there is a wwwroot folder in the base application folder, it will default that as the webroot of your application.  If there is not a wwwroot folder, it will serve the base application folder as the base of static file contents for your web application.

Strong Named Framework Libraries

We are now adding strong names to the framework libraries that are referenced by ASP.NET.  The complete list of libraries effected are listed on the GitHub strong-naming announcement.  This change helps us on several fronts:

  • There are other projects that need to take a dependency on ASP.NET and require strong naming, and their dependencies must be strong-named.
  • In order to help with applying patches on Windows operating systems using Windows Update, we need to place these libraries in the GAC.  In order for these libraries to reside in the GAC, they must be strong-named.

Introducing the .NET Platform Standard

There are several versions of .NET frameworks available, and the introduction of the .NET Core framework further introduces complications for portable class library authors.  To simplify the targeting of .NET frameworks for developers, we are introducing the .NET Platform Standard.  The short definition of the Platform Standard is that it is a single representation for binary compatible .NET Frameworks in packages and project.json instead of representing them as “portable-a+b+c”.  For various versions of the framework, they can be grouped together as “dotnet5.4” with this version of the tools.  This is a work in progress, with the naming convention for these frameworks changing to 'netstandard1.x' in a future release.  More details on the plans for the .NET Platform standard roadmap are available on the .NET Roadmap.

NuGet and dnu both support this new representation of compatible .NET frameworks, and more details and tools will be made available as this new definition of .NET Framework compatibility evolves through our completion of the ASP.NET 5 RTM.

With this version of ASP.NET 5 templates, the “Class Library (package)” project template will target “dotnet5.4” which has binary compatibility with .NET 4.6, .NET Core 5, and Mono. 

Other Breaking API Changes

There were a number of other API changes after we completed our API review of the entire framework.  We have shared and documented these changes in the Announcements repository on GitHub.  Use this handy query to review the complete list of changes to the framework in the beta8 – RC1 cycle.

Glimpse v2 Beta1 Released for ASP.NET 5

Glimpse v2 is a major evolution of the Glimpse platform for Web diagnostics and it is now available for ASP.NET 5. There’s lots of new bells and whistles, but the team highlights four key improvements in this early beta release: First, there’s a new and improved UI paradigm that puts diagnostics on the stage that they deserve. Next, because Glimpse v2 is based on ASP.NET 5 and the .NET Core, it’s cross platform and runs everywhere ASP.NET can run. Third, Glimpse now not only instruments the server as it has in the past, but it also leverages modern browser diagnostics API’s to provide a complete picture of the performance of a request end-to-end. Lastly, Glimpse now supports a wider range of production environments, including those with multiple web front ends. Be sure to check out the full details of the Glimpse announcement over at their blog.

Go Live!

Starting with the RC1, we are including a “Go Live” license.  This license allows you to deploy an application written with ASP.NET 5 RC1 to a production environment and utilize Microsoft Support.  The duration of this license for the RC1 last until the next release candidate or the completed release of ASP.NET 5 (called an RTM release) that is currently scheduled for Q1 2016.  This license also covers running ASP.NET on Windows, Linux, and OSX.

Run on IIS

When you are ready to publish your ASP.NET 5 web application, you may want to run it on a Windows Server with IIS just as all previous ASP.NET applications were deployed.  In the ASP.NET 5 model, you will need to configure IIS to use the HTTP Platform Handler with the ASP.NET host.  Instructions describing how to configure IIS for use with the new ASP.NET hosting model are available on docs.asp.net.

Support for Azure

ASP.NET 5 was built to be cloud-ready, and we’ve made it easy to publish your new ASP.NET 5 applications to Azure and use CoreCLR libraries for Azure Active Directory, Storage and SQL Database.  With this release we have also released Azure Management libraries for Azure Compute, Network, Storage, App Service, Resource Manager and more which target CoreCLR. To get started with these Preview libraries, click here

You can also use the Visual Studio Publish feature to create a new Azure Web app and publish your application quickly and confidently to Azure.  For more information about the Azure App Service and to get started for free, visit http://tryappservice.azure.com

Summary

The collection of tools, stabilization changes, and framework alignment changes in the RC1 of ASP.NET 5 should make development easier and prepare you for success with the upcoming .NET Platform Standard.  With continued support for OSX and Linux environments in this release, the ASP.NET platform has matured and is now officially supported by Microsoft on all three major operating systems.  Its an exciting time as we prepare to deliver this vision of a new ASP.NET.  There are several ways that you can get involved:

  • Follow our weekly community standup broadcast at live.asp.net for more information from the program managers leading the project.  Ask your questions and listen in to the updates every Tuesday to learn more about the progress of the project.
  • Get the latest ASP.NET tools, samples, and bit from get.asp.net
  • Read and contribute to our open sourced documentation at docs.asp.net  Every article is markdown in Github that you can submit updates to.  Get your name listed as an author of the ASP.NET 5 documentation by submitting an acceptable pull-request!

We have almost completed ASP.NET 5, and have some items to complete with regards to performance goals and the .NET Platform standard.  What are you going to build with the new ASP.NET?

Using ASP.NET WebHooks with IFTTT and Zapier to Monitor Twitter and Google Sheets

$
0
0

With the latest drop of ASP.NET WebHooks we have added a generic JSON WebHook receiver, which can be used to receive WebHooks from services like IFTTT and Zapier. Both IFTTT and Zapier provide a huge number of integrations in areas such as productivity, automotive, blogging, CRM, commerce, project management, IoT, social, mobile, collaboration, and much more. For a full list, check out IFTTT channels and browse Zapier zaps.

A really cool thing about both IFTTT and Zapier is that they enable regular HTTP requests to be output of an integration. That is, you can build integrations that when something happens, a Web request is sent to some specified destination.

Here we’ll show how to leverage this to build two simple integrations – one with IFTTT and one with Zapier – and then use ASP.NET WebHooks to receive the result. For IFTTT we wire it up to Twitter monitoring when a tweet is sent, and for Zapier we wire it up to a Google Sheet monitoring when a row is added. These are of course just examples – the possibilities for integrations are endless!

Configuring Generic WebHook Handler

As usual, let’s first create an empty Web Application with Web API in Visual Studio which we will use for receiving WebHooks from IFTTT and Zapier. Btw, if you just want to look at the code then you can also check out this sample. Otherwise, continue by setting the project up for deployment in Azure by checking Host in the cloud:

EmptyProject

Install the Microsoft.AspNet.WebHooks.Receivers.Generic Nuget package. The registration happens exactly like in the blog Introducing Microsoft ASP.NET WebHooks Preview by addingthis line to the WebApiConfig.Register method:

publicstaticclass WebApiConfig
{
publicstaticvoid Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Initialize Generic JSON WebHook receiver
config.InitializeReceiveGenericJsonWebHooks();
}
}

In this case we want the same receiver to handle both IFTTT and Zapier WebHooks which means that we need two WebHook URIs looking like this (one for IFTTT and one for Zapier):

https://<host>/api/webhooks/incoming/genericjson/i?code=1388a6b0d05eca2237f10e4a4641260b0a08f3a5
https://<host>/api/webhooks/incoming/genericjson/z?code=80ad19e357b01a04fe767067df7cd31b96a844e1

We achieve this by defining the MS_WebHookReceiverSecret_GenericJson application setting as follows:

<appSettings>
<addkey="MS_WebHookReceiverSecret_GenericJson"
value="i=1388a6b0d05eca2237f10e4a4641260b0a08f3a5,z=80ad19e357b01a04fe767067df7cd31b96a844e1"/>
</appSettings>

As stated in the blog Introducing Microsoft ASP.NET WebHooks Preview, the preferred way to do this is to set it in the Azure Portal. The 'code' parameter must be between 32 and 128 characters long and as usual, you should pick values that have high entropy. A good idea is to pick something like a SHA256 hash which you for example can get from FreeFormatter Online Tools For Developers.

Finally, we add a GenericJsonWebHookHandler.cs file containing the following class for processing the incoming WebHooks for both IFTTT and Zapier. Note how we use the ‘Id’ property to differentiate between the two:

publicclass GenericJsonWebHookHandler : WebHookHandler
{
public GenericJsonWebHookHandler()
{
this.Receiver = "genericjson";
}

publicoverride Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
// Get JSON from WebHook
JObject data = context.GetDataOrDefault<JObject>();

if (context.Id == "i")
{
// Received a WebHook from IFTTT!
}
elseif (context.Id == "z")
{
// Received a WebHook from Zapier!
}

return Task.FromResult(true);
}
}

Integrations using IFTTT’s Maker Channel

Setting up a recipe with IFTTT is fairly straight forward, but obviously you need an account with IFTTT. And just to avoid any confusion, to wire up to Twitter you also need a twitter account. Start by going to My Recipes, then IF, then Create a Recipe, and then this to set up the trigger part:

IFTTT-01

Look for the Twitter channel:

IFTTT-02

and select New tweet for you:

IFTTT-03

Wire it up to your twitter account and create the trigger:

IFTTT-04

Now select that for the action part:

IFTTT-05

Search for the Maker channel:

IFTTT-06

and select the Make a web request action:

IFTTT-07

Set URL to the first WebHook URI value from above, set the Method to ‘POST’ and Content Type to ‘application/json’.

IFTTT-08

Also, set the Body to something like this while being careful generating valid JSON – otherwise the WebHook receiver will reject it:

{ "Text": "{{Text}}", "Link": "{{LinkToTweet}}" }
 
Select Create Action and you should see something like this:
 
IFTTT-09

Integrations using Zapier’s WebHook Action

Setting up an integration with Zapier is equally simple, but of course you also need a Zapier account to get going and one for Google Drive to wire up to Google Sheets. Start by going to your dashboard and select Make a new Zap:

Zapier-01

Then for trigger search for Google Sheets as the trigger app:

Zapier-02a

Then pick New Spreadsheet Row as the trigger. Similarly, pick WebHooks by Zapier as the action app and then POST as the action:

Zapier-03

For this tutorial I created a Google Sheet with simple data like this:

GoogleSheet

Now add your Google Sheets account to the trigger part of the Zap in step 2:

Zapier-04

The WebHooks by Zapier action doesn’t require any account setup in step 3 so just continue to step 4:

Zapier-05

Select the particular sheet you want to monitor and pick the particular worksheet:

Zapier-06

Finally, set the URL to the second WebHook URI value from above and set the Payload Type to ’json’:

Zapier-07

In step 6 you can test out the zap but for now just go to step 7, enable the zap and get ready to try it out:

Zapier-08a

Trying it Out

Simply deploy your Web Application Project to Azure and try out the two integrations: To trigger the IFTTT integration, tweet from the account you registered, and for Zapier, add a row to the Google Sheet. For both IFTTT and Zapier there is a delay, at least in the free tier, for some minutes before changes cause a WebHook to fire. However, in both cases you can manually run the integration to cause it to fire.

If you attach the debugger and add a row to the Google Sheet you and then run the zap manually, you should see this show up in the debugger like this:

Zapier-09

Similarly, after you tweet you should see the same breakpoint getting hit but this time for the IFTTT integration.

That’s it – you can now build integrations using IFTTT and Zapier and get the result straight into ASP.NET using ASP.NET WebHooks.

Have fun!

Henrik

.NET Core and ASP.NET Bug Bounty Update

$
0
0

As we've now released RC1 of .NET Core and ASP.NET restrictions on areas for investigation are now lifted. The entire cross platform stack, including networking is now in scope and eligible for bounty submissions.

The ASP.NET web site has instructions on how to install RC1 on Windows, Linux and OS X. Windows researchers can use Visual Studio 2015, including the free Visual Studio 2015 Community Edition, after installing RC1 from https://get.asp.net. The source for .NET Core can be found on GitHub at https://github.com/dotnet/corefx. The source for ASP.NET v5 can be found on GitHub at https://github.com/aspnet.

As before we encourage you to read the program terms and FAQs before beginning your research or reporting a vulnerability.


New feature to enable C# 6 / VB 14

$
0
0

The model to leverage updated versions of C# or VB in web apps has changed over the past few years. In the past to leverage a new version of C# or VB you would get the runtime and build tools by installing the .NET Framework. With Visual Studio 2015 and the latest version of MSBuild this is no longer needed. You can decide which applications leverage C# 6/VB 14 by adding a NuGet package, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, to your web projects. When you add this NuGet package to your web applications then you can start using C# 6/VB 14 in both the code behind as well as Views.

 

In Visual Studio 2015 Update 1 we have included a new feature to simplify this. When you have a solution open which has at least one web project which is targetting .NET 4.5+ and does not have the DotNetCompilerPlatform NuGet package in the Project menu you’ll see a new option, Enable C# 6 / VB 14 appear.

project-menu

 

When you select the Enable C# 6 / VB 14 menu option a dialog will appear showing all web projects which can be updated to support C# 6 / VB 14. In this case the solution that I have opened has two web projects which can be updated to support C# 6. When the dialog appears I can see both projects and can select the ones that I want to be updated for C# 6.

project-selection

In this case I’ll just select WebApplication1 to be updated. After selecting to enable C# 6, the Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package is installed into the project. Now I can use C# 6 in both the code behind files as well as the views.

Because the support to leverage C# 6 / VB 14 is shipped as a part of your project, when you publish there will be some additional files that will get published. If you are not planning to leverage C# 6 / VB 14 then it’s recommended to not install this NuGet package as it will just slow down your deployment speeds.

 

Thanks,
Sayed Ibrahim Hashimi

WCF Connected Service Visual Studio Extension Preview for ASP.NET 5 Projects

$
0
0

Over the years, many Visual Studio developers have enjoyed the productivity that Add Service Reference Dialog Box provided when their projects need to access Windows Communication Foundation (WCF) services. WCF team is excited to introduce you to the support of Add Service Reference functionality for ASP.NET 5 projects via WCF Connected Service extension preview. This tool retrieves metadata from a WCF service in the current solution, locally or on a network and generates a .NET Core compatible source code file for a WCF client proxy that you can use to access the service.

How to install the extension

The WCF Connected Service extension can be installed on Visual Studio 2015 and it has following prerequisite. Please make sure you have prerequisites installed before installing the extension.

The extension is published into the Visual Studio Extensions Gallery and can be downloaded either from the official Visual Studio Extensions Gallery download pageor directly from Visual Studio via the "Extensions and Updates" dialog as shown below by simply searching for "WCF Connected Service".

How to use the extension

The WCF Connected Service extension is applicable to any projects created with project templates under Visual C# -> Web. This includes Console Application (Package), Class Library (Package) and all ASP.NET 5 templates. I will use an ASP.NET 5 Web Application as an example and walk you through to add a reference to a WCF service to the project.

  1. In Solution Explorer, right-click the References of the project and then click Add Connected Service as shown below. The Add Connected Service dialog box appears.

  2. In Add Connected Service dialog box, click Microsoft on the left column, then click WCF Service - Preview in the middle column and finally click Configure button. This will bring up Configure WCF Service Reference dialog box.

  3. You can either click the Discover button to initiate a search for services that are contained in the current solution or enter the URL for a service in the Address box and then click Go to search for the service hosted at the address.

    The services that are found will be displayed in the Services box and you can select the one you want to use. You can also enter the namespace that you want to use for the reference in the Namespace box. Optionally, you can click through the Next button to make further configuration of DataType Options and Client Options.
  4. Click Finish when you done.

This will download metadata from the WCF service, generate a reference.cs file for the WCF client proxy, and add it to the project under Service References folder. The project.json file of the project will also be updated with WCF NuGet packages for your application to run on .NET Core or framework references for your application to run on full .NET Framework as appropriate. With this, you can create client proxy as you normally do and happy coding!

What's next and feedback request

This is a preview of the tool. Some of the advanced features such as Reuse types in Referenced Assemblies, are still not supported in this release. We are working to bring in more features. In the meanwhile, we would love to hear your experience of using this tool, any feedback or issues you may see.

New Year Updates to ASP.NET WebHooks Preview

$
0
0

We just released a new update of ASP.NET WebHooks with a couple of interesting new features on the WebHooks sender side – that is, when you want to send WebHooks to others when some event happens – including:

  1. Sending events to all users registered for a particular event.
  2. Scaling out and load balancing events using persistent queues.

You can get the update from nuget.org by looking for the packages under Microsoft.AspNet.WebHooks.* with ‘preview’ filter enabled. If you haven’t heard about ASP.NET WebHooks then you may want to look at Introducing Microsoft ASP.NET WebHooks Preview. As this blog is about the sending side, the blog Sending WebHooks with ASP.NET WebHooks Preview also provides good background.

Sending Events to All Users

In addition to sending events in the form of WebHooks to individual users, it is now possible to send WebHooks to all users who have registered for a particular event. We now expose the method NotifyAllAsync in the same places where you could use NotifyAsync to send notifications to all active registered WebHooks.

Also, you can use a predicate as a filter if you want to control which users get the WebHook notification. For example, in the below illustration, Receiver 2 and 5 don’t get this particular event due to the predicate.

NotifyAll

Using NotifyAllAsync is very similar to using NotifyAsync and it is available in the same places. Assuming you have a project already set up to support WebHooks as described in the blog entry Sending WebHooks with ASP.NET WebHooks Preview or using this sample, here’s how you can use NotifyAllAsync in an MVC controller:

[Authorize]
publicclass NotifyController : Controller
{
[HttpPost]
public async Task<ActionResult> Submit()
{
// Create an event with action 'event1' and additional data
await this.NotifyAsync("event1", new { P1 = "p1" });

// Send event1 to all users not called 'henrik'
await this.NotifyAllAsync("event1",
new { P1 = "p1" }, (webHook, user) => { return user != "henrik" });

returnnew EmptyResult();
}
}

The model looks exactly the same in a Web API controller:

[Authorize]
publicclass NotifyApiController : ApiController
{
public async Task<IHttpActionResult> Post()
{
// Create an event with 'event2' and additional data
await this.NotifyAsync("event2", new { P1 = "p1" });

// Send event2 to all users not called 'henrik'
await this.NotifyAllAsync("event2",
new { P1 = "p1" }, (webHook, user) => { return user != "henrik" });

return Ok();
}
}

Sending WebHooks: Scaling Out and Load Balancing

We have introduced a new IWebookSender abstraction which allows you to scale-out and load-balance the act of sending out WebHooks. That is, instead of having the Web server directly sending out WebHooks, it is now possible to have an architecture like this allowing you to both persist WebHooks on the sender side and to scale up and out as you want:

ScaleOut

To illustrate this, we provide out of the box support for sending WebHooks via an Azure Storage Queue but you can hook  in any kind of queue. Once you have a project already set up to support WebHooks (like this sample) as described in the blog entry Sending WebHooks with ASP.NET WebHooks Preview, configuring it to support Azure Storage Queues is quite simple:

  1. On the frontend side, you register a special IWebHookSender implementation which simply submits all WebHooks to an Azure Storage Queue.
  2. On the sender side, you use the AzureWebHookDequeueManager class which dequeues messages from the Azure Storage Queue and then sends them out as WebHooks.

To register the queue IWebHookSender implementation (part of the Microsoft.AspNet.WebHooks.Custom.AzureStorage nuget package) on the frontend, simply add this line to the initialization:

publicstaticclass WebApiConfig
{
publicstaticvoid Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Load basic support for sending WebHooks
config.InitializeCustomWebHooks();

// Load Azure Storage (or SQL) for persisting subscriptions
config.InitializeCustomWebHooksAzureStorage();

// Load Azure Queued Sender for enqueueing outgoing WebHooks to an Azure Storage Queue
config.InitializeCustomWebHooksAzureQueueSender();

// Load Web API controllers for managing subscriptions
config.InitializeCustomWebHooksApis();
}
}

To configure the frontend, you need to set the Azure Storage connection string, that it should use, for example:

<connectionStrings>
<addname="MS_AzureStoreConnectionString"connectionString="UseDevelopmentStorage=true;"/>
</connectionStrings>

On the sender side, you now need a process that can dequeue messages from the Azure Storage Queue and send them out to the targeted WebHook recipients. This can be a simple command line program (like this sample):

internalclass Program
{
privateconststring QueueConnectionString = "MS_AzureStoreConnectionString";

publicstaticvoid Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => DequeueAndSendWebHooks(cancellationTokenSource.Token));

Console.WriteLine("Hit ENTER to exit!");
Console.ReadLine();

cancellationTokenSource.Cancel();
}

privatestatic async Task DequeueAndSendWebHooks(CancellationToken cancellationToken)
{
// Create the dequeue manager
string connectionString =
            ConfigurationManager.ConnectionStrings[QueueConnectionString].ConnectionString;
ILogger logger = CommonServices.GetLogger();
AzureWebHookDequeueManager manager = new AzureWebHookDequeueManager(connectionString, logger);

// Start the dequeue manager
await manager.Start(cancellationToken);
}
}

The two highlighted lines are the key ones – the first creates the AzureWebHookDequeueManager using the given connection string pointing to the queue. The second line starts an event loop returning a Task that you can cancel when you are done. The AzureWebHookDequeueManager will periodically poll for new messages in the queue and send them out as WebHooks.

If the WebHook requests either succeed or return HTTP status code 410 Gone, then we consider the message delivered and delete it from the queue. Otherwise we leave it in the queue ensuring that it will get another chance of being sent out after a couple of minutes. After 3 attempts we give up and delete the message from the queue regardless. For more information about Azure Storage Queues, please see the blog How to use Queue storage from .NET.

Like for the sender side, we can provide the Azure Storage connection string in the config file, for example:

<connectionStrings>
<addname="MS_AzureStoreConnectionString"connectionString="UseDevelopmentStorage=true;"/>
</connectionStrings>
 
That’s it – I hope you enjoy these new features in ASP.NET WebHooks!

Happy New Year!

Henrik

Using ASP.Net Module to Debug Async Calls

$
0
0

I had a web application that generously used async/await keywords. The application encountered a slow response possibly due to a pending backend database call. I attached a debugger to the application. There was, however, nothing running in the process (see Figure 1), which was expected due to the calls being async and the waiting threads were no longer active.

It is frustrating seeing no code running when debugging applications using asynchronous methods. What can I do?

Figure 1 “Nothing” is running in the process. The 'Location' column is empty.

Introducing TPLEventListenerModule

Andrew Stasyuk has a good post (https://msdn.microsoft.com/en-us/magazine/JJ891052.aspx) introducing a way to get the call stacks (or causality chains) of async tasks. I figured I could leverage this method in my web application.

In a nutshell, the .NET Framework defines an event source, TplEtwProvider, which fires events that allow you to track Task lifetime. In .NET 4.5 and above, it is possible to subscribe to the event source to get the events. Here is what I do. I create an ASP.Net HttpModule, TPLEventListenerModule, which contains an event listener listening to TPL (Task Parallel Library) events. The listener captures two kinds of TPL event, TaskWaitBegin and TaskWaitEnd. Upon capturing an event, the listener stores the Task’s information -- such as, the Id of the task, the StackTrace where the event happens, the created time of the event, the type of the event, and so on -- in memory. The module ensures the listener initialized during BeginRequest event of requests. And I create an HttpHandler for viewing the stored information. The task information can also be accessed via APIs or be found in a dump of the web application.

The solution of the module is attached to this blog post. Here are some more details about the module.

   1. The module is an ASP.Net HttpModule. To use it I just need to register the module in my web application’s web.config. The section to be added in web.config looks like this, 

  <system.webServer    …     <modules>      <add name="TPLEventListenerModule" type="TaskEventListenerModule.TPLEventListenerModule, TaskEventListenerModule"/>
    </modules>    …  </system.webServer>

   2. The captured event info is stored in the following two ways: 

   Each HttpContext instance has a SingleRequestTaskStore instance that stores the current active Task’s info for the corresponding request.

Figure 2 A SingleRequestTaskStore instance is stored in the HttpContext's Items bag.

   Each HttpContext instance has a DebuggingInfoList containing all events for the corresponding request.  

 

Figure 3 A DebuggingInfoList contains all Task Begin/End events for the corresponding request.

   3. The module puts/removes every request’s HttpContext into/from a ConcurrentItemStore in the request’s BeginRequest/EndRequest event. I can access the stored HttpContext via the CurrentContextViewer. 

Figure 4 The Contexts property contains HttpContexts for all active requests.

   4. I wrote an HttpHandler, ViewAsyncTaskInfoHandler. The handler can give me a view of all active requests and all async Task info if there is any. To enable the handler in my application, in web.config I added a section like this,

  <system.webServer>    …    <handlers>      <add type="TaskEventListenerModule.ViewAsyncTaskInfoHandler, TaskEventListenerModule" name="ViewAsyncTaskInfoHandler"
          resourceType="Unspecified" path="vat.axd" verb="POST,GET,HEAD"></add>
    </handlers>    …  </system.webServer> 

Trying it Out

The attached solution includes  a demo project. The default page has two hyperlinks, “Async Page” and “View Async Tasks”. Start the application and browse the default page, you can try clicking “Async Page” a few times and then click “View Async Tasks”, and “View Async Tasks” page will show you a list of requests running async tasks.

With the TPLEventListenerModule in place, I can now know what async task my request is awaiting even though I do not see any active thread. If you ever have the same problem, get a copy of the module into your project today.

 

Task runners in Visual Studio 2015

$
0
0

trx

There are various kinds of tasks typically used by web developers as part of their workflow. Everything from bundling and minifying JavaScript files, to compiling LESS files into CSS and even running custom batch or PowerShell scripts.

In a sense you can say that tasks are steps that needs to be performed to make the application run that are separate from coding it.

Visual Studio 2015 supports any kind of custom task execution from the new Task Runner Explorer tool window. It ships with built-in support for two very popular web centric task runners – Grunt and Gulp.

The Task Runner Explorer shows a list of available tasks and executing them is as simple as a click of the mouse. You can even bind any task to specific events that occur in Visual Studio such as Build, Clean and Project Open.

Sure you can use the command line to invoke your custom tasks, but with the integration into Visual Studio you can automate a lot more of your workflow.

There are quite a few extensions freely available that adds support for a lot more task frameworks.

NPM Scripts Task Runner

npmThis task runner adds support for npm scripts listed in the scripts section of a package.json file. This allows you to run any executable with any arguments simply by modifying package.json.

You can read more about npm scripts and how to set it up in the npm documentation.

Download | Source code

 

Command Task Runner

commandIs similar to the NPM Script Task Runner in that it can execute any executable, but with the main difference that you don’t need a package.json file. Also, this extension supports inline PowerShell and batch commands.

This make it perfect for any type of project that has custom .cmd or .ps1 files as part of the build process.

Download | Source code

 

WebPack Task Runner

webpackFrom the webpack website: webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

Webpack is getting more and more popular and seems to be resonating very well with React.js developers.

Download | Source code

 

Broccoli Task Runner

broccoliFrom the Broccoli is a build tool that is very popular with developers using the ember.js JavaScript framework, but can be used in any web project.

From their website: A fast, reliable asset pipeline, supporting constant-time rebuilds and compact build definitions. Comparable to the Rails asset pipeline in scope, though it runs on Node and is backend-agnostic.

Download | Source code

 

Brunch Task Runner

brunchBrunch is a builder. Not a generic task runner, but a specialized tool focusing on the production of a small number of deployment-ready files from a large number of heterogeneous development files or trees.

Download | Source code

 

ASP.NET 5 Task Runner

aspnetAllows you to easily execute the scripts in project.json’s scripts section such as prepublish and postbuild. But you can also specify your own custom scripts that this extension can then execute.

This makes it possible to setup a full build process from a single location.

Download | Source code

 

All of these extensions demonstrate just how flexible the Task Runner Explorer in Visual Studio is. If you find your favorite task runner framework to be missing from this list, please let us know in the comments.

Visual Studio keeps showing suggested extensions

$
0
0

In Visual Studio 2015 Update 1 we introduced a mechanism that would analyze a web project and suggest helpful Visual Studio extensions based on what it could find. For instance, if the project was using the Bootstrap CSS framework, it would suggest two very cool extensions specifically for working with Bootstrap.

Based on your project, we have identified extensions you may find helpful
 
It works by showing a yellow bar at the top of the editor when an HTML document is being opened. The idea was to improve the user experience by suggesting extensions from the community that would make you more productive based on your current context.

While some people found these suggestions helpful and installed the extensions, some people weren’t interested and they clicked the Don’t Show Again button. However, a bug had sneaked its way into this feature so that Visual Studio would always show the yellow bar when opening an HTML document.

To work around this issue, you have to set the setting to hide the yellow bar manually. Go to Tools -> Options and set the Identify Helpful Extensions option to False.

Advanced HTML settings

Disabling this feature solves another issue as well. The issue happens when there is a Git merge conflict or with Annotate and Excluded Folder documents. The error message isn’t very informative and looks like this:

An exception has been encountered

The ActivityLog.xml is a bit cryptic but it contains a reference to Microsoft.VisualStudio.Html.Package.Extensions.ExtensionsManager.OnTextViewCreated which is where this issue occurred.

These issues have all been fixed and will be available soon in a future release.

ASP.NET 5 is dead - Introducing ASP.NET Core 1.0 and .NET Core 1.0

$
0
0

This post originally appeared on Scott Hanselman's blog at: http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx

Naming is hard.

There are only two hard things in Computer Science: cache invalidation and naming things. - Phil Karlton

It's very easy to armchair quarterback and say that "they should have named it Foo and it would be easy" but very often there's many players involved in naming things. ASP.NET is a good 'brand' that's been around for 15 years or so. ASP.NET 4.6 is a supported and released product that you can get and use now from http://get.asp.net.

However, naming the new, completely written from scratch ASP.NET framework "ASP.NET 5" was a bad idea for a one major reasons: 5 > 4.6 makes it seem like ASP.NET 5 is bigger, better, and replaces ASP.NET 4.6. Not so.

So we're changing the name.

Reintroducing ASP.NET Core 1.0 and .NET Core 1.0

  • ASP.NET 5 is now ASP.NET Core 1.0.
  • .NET Core 5 is now .NET Core 1.0.
  • Entity Framework 7 is now Entity Framework Core 1.0 or EF Core 1.0 colloquially.

Why 1.0? Because these are new. The whole .NET Core concept is new. The .NET CLI is very new. Not only that, but .NET Core isn't as complete as the full .NET Framework 4.6. We're still exploring server-side graphics libraries. We're still exploring gaps between ASP.NET 4.6 and ASP.NET Core 1.0.

Which to choose?

To be clear, ASP.NET 4.6 is the more mature platform. It's battle-tested and released and available today. ASP.NET Core 1.0 is a 1.0 release that includes Web API and MVC but doesn't yet have SignalR or Web Pages. It doesn't yet support VB or F#. It will have these subsystems some day but not today.

We don't want anyone to think that ASP.NET Core 1.0 is the finish line. It's a new beginning and a fork in the road, but ASP.NET 4.6 continues on, released and fully supported. There's lots of great stuff coming, stay tuned!


Using ASP.Net Module to Debug Async Calls

$
0
0

I had a web application that generously used async/await keywords. The application encountered a slow response possibly due to a pending backend database call. I attached a debugger to the application. There was, however, nothing running in the process (see Figure 1), which was expected due to the calls being async and the waiting threads were no longer active.

It is frustrating seeing no code running when debugging applications using asynchronous methods. What can I do?

Figure 1 “Nothing” is running in the process. The ‘Location’ column is empty.

Introducing TPLEventListenerModule

Andrew Stasyuk has a good post (https://msdn.microsoft.com/en-us/magazine/JJ891052.aspx) introducing a way to get the call stacks (or causality chains) of async tasks. I figured I could leverage this method in my web application.

In a nutshell, the .NET Framework defines an event source, TplEtwProvider, which fires events that allow you to track Task lifetime. In .NET 4.5 and above, it is possible to subscribe to the event source to get the events. Here is what I do. I create an ASP.Net HttpModule, TPLEventListenerModule, which contains an event listener listening to TPL (Task Parallel Library) events. The listener captures two kinds of TPL event, TaskWaitBegin and TaskWaitEnd. Upon capturing an event, the listener stores the Task’s information — such as, the Id of the task, the StackTrace where the event happens, the created time of the event, the type of the event, and so on — in memory. The module ensures the listener initialized during BeginRequest event of requests. And I create an HttpHandler for viewing the stored information. The task information can also be accessed via APIs or be found in a dump of the web application.

The solution of the module is attached to this blog post. Here are some more details about the module.

   1. The module is an ASP.Net HttpModule. To use it I just need to register the module in my web application’s web.config. The section to be added in web.config looks like this, 

  <system.webServer
    … 
    <modules>
      <add name="TPLEventListenerModule" type="TaskEventListenerModule.TPLEventListenerModule, TaskEventListenerModule"/>
    </modules>
    …
  </system.webServer>

   2. The captured event info is stored in the following two ways: 

   Each HttpContext instance has a SingleRequestTaskStore instance that stores the current active Task’s info for the corresponding request.

Figure 2 A SingleRequestTaskStore instance is stored in the HttpContext’s Items bag.

   Each HttpContext instance has a DebuggingInfoList containing all events for the corresponding request.  

 

Figure 3 A DebuggingInfoList contains all Task Begin/End events for the corresponding request.

   3. The module puts/removes every request’s HttpContext into/from a ConcurrentItemStore in the request’s BeginRequest/EndRequest event. I can access the stored HttpContext via the CurrentContextViewer. 

Figure 4 The Contexts property contains HttpContexts for all active requests.

   4. I wrote an HttpHandler, ViewAsyncTaskInfoHandler. The handler can give me a view of all active requests and all async Task info if there is any. To enable the handler in my application, in web.config I added a section like this,

  <system.webServer>
    …
    <handlers>
      <add type="TaskEventListenerModule.ViewAsyncTaskInfoHandler, TaskEventListenerModule" name="ViewAsyncTaskInfoHandler"
           resourceType="Unspecified" path="vat.axd" verb="POST,GET,HEAD"></add>
    </handlers>
    …
  </system.webServer> 

Trying it Out

The attached solution includes  a demo project. The default page has two hyperlinks, “Async Page” and “View Async Tasks”. Start the application and browse the default page, you can try clicking “Async Page” a few times and then click “View Async Tasks”, and “View Async Tasks” page will show you a list of requests running async tasks.

With the TPLEventListenerModule in place, I can now know what async task my request is awaiting even though I do not see any active thread. If you ever have the same problem, get a copy of the module into your project today.

 

TaskEventListenerModule.zip

New Year Updates to ASP.NET WebHooks Preview

$
0
0

We just released a new update of ASP.NET WebHooks with a couple of interesting new features on the WebHooks sender side – that is, when you want to send WebHooks to others when some event happens – including:

  1. Sending events to all users registered for a particular event.
  2. Scaling out and load balancing events using persistent queues.

You can get the update from nuget.org by looking for the packages under Microsoft.AspNet.WebHooks.* with ‘preview’ filter enabled. If you haven’t heard about ASP.NET WebHooks then you may want to look at Introducing Microsoft ASP.NET WebHooks Preview. As this blog is about the sending side, the blog Sending WebHooks with ASP.NET WebHooks Preview also provides good background.

Sending Events to All Users

In addition to sending events in the form of WebHooks to individual users, it is now possible to send WebHooks to all users who have registered for a particular event. We now expose the method NotifyAllAsync in the same places where you could use NotifyAsync to send notifications to all active registered WebHooks.

Also, you can use a predicate as a filter if you want to control which users get the WebHook notification. For example, in the below illustration, Receiver 2 and 5 don’t get this particular event due to the predicate.

NotifyAll

Using NotifyAllAsync is very similar to using NotifyAsync and it is available in the same places. Assuming you have a project already set up to support WebHooks as described in the blog entry Sending WebHooks with ASP.NET WebHooks Preview or using this sample, here’s how you can use NotifyAllAsync in an MVC controller:

[Authorize]
public class NotifyController : Controller
{
[HttpPost]
public async Task<ActionResult> Submit()
{
// Create an event with action 'event1' and additional data
await this.NotifyAsync("event1", new { P1 = "p1" });

// Send event1 to all users not called 'henrik'
await this.NotifyAllAsync("event1",
new { P1 = "p1" }, (webHook, user) => { return user != "henrik" });

return new EmptyResult();
}
}

The model looks exactly the same in a Web API controller:

[Authorize]
public class NotifyApiController : ApiController
{
public async Task<IHttpActionResult> Post()
{
// Create an event with 'event2' and additional data
await this.NotifyAsync("event2", new { P1 = "p1" });

// Send event2 to all users not called 'henrik'
await this.NotifyAllAsync("event2",
new { P1 = "p1" }, (webHook, user) => { return user != "henrik" });

return Ok();
}
}

Sending WebHooks: Scaling Out and Load Balancing

We have introduced a new IWebHookSender abstraction which allows you to scale-out and load-balance the act of sending out WebHooks. That is, instead of having the Web server directly sending out WebHooks, it is now possible to have an architecture like this allowing you to both persist WebHooks on the sender side and to scale up and out as you want:

ScaleOut

To illustrate this, we provide out of the box support for sending WebHooks via an Azure Storage Queue but you can hook  in any kind of queue. Once you have a project already set up to support WebHooks (like this sample) as described in the blog entry Sending WebHooks with ASP.NET WebHooks Preview, configuring it to support Azure Storage Queues is quite simple:

  1. On the frontend side, you register a special IWebHookSender implementation which simply submits all WebHooks to an Azure Storage Queue.
  2. On the sender side, you use the AzureWebHookDequeueManager class which dequeues messages from the Azure Storage Queue and then sends them out as WebHooks.

To register the queue IWebHookSender implementation (part of the Microsoft.AspNet.WebHooks.Custom.AzureStorage nuget package) on the frontend, simply add this line to the initialization:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

// Load basic support for sending WebHooks
config.InitializeCustomWebHooks();

// Load Azure Storage (or SQL) for persisting subscriptions
config.InitializeCustomWebHooksAzureStorage();

// Load Azure Queued Sender for enqueueing outgoing WebHooks to an Azure Storage Queue
config.InitializeCustomWebHooksAzureQueueSender();

// Load Web API controllers for managing subscriptions
config.InitializeCustomWebHooksApis();
}
}

To configure the frontend, you need to set the Azure Storage connection string, that it should use, for example:

<connectionStrings>
<add name="MS_AzureStoreConnectionString" connectionString="UseDevelopmentStorage=true;" />
</connectionStrings>

On the sender side, you now need a process that can dequeue messages from the Azure Storage Queue and send them out to the targeted WebHook recipients. This can be a simple command line program (like this sample):

internal class Program
{
private const string QueueConnectionString = "MS_AzureStoreConnectionString";

public static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => DequeueAndSendWebHooks(cancellationTokenSource.Token));

Console.WriteLine("Hit ENTER to exit!");
Console.ReadLine();

cancellationTokenSource.Cancel();
}

private static async Task DequeueAndSendWebHooks(CancellationToken cancellationToken)
{
// Create the dequeue manager
string connectionString =
            ConfigurationManager.ConnectionStrings[QueueConnectionString].ConnectionString;
ILogger logger = CommonServices.GetLogger();
AzureWebHookDequeueManager manager = new AzureWebHookDequeueManager(connectionString, logger);

// Start the dequeue manager
await manager.Start(cancellationToken);
}
}

The two highlighted lines are the key ones – the first creates the AzureWebHookDequeueManager using the given connection string pointing to the queue. The second line starts an event loop returning a Task that you can cancel when you are done. The AzureWebHookDequeueManager will periodically poll for new messages in the queue and send them out as WebHooks.

If the WebHook requests either succeed or return HTTP status code 410 Gone, then we consider the message delivered and delete it from the queue. Otherwise we leave it in the queue ensuring that it will get another chance of being sent out after a couple of minutes. After 3 attempts we give up and delete the message from the queue regardless. For more information about Azure Storage Queues, please see the blog How to use Queue storage from .NET.

Like for the sender side, we can provide the Azure Storage connection string in the config file, for example:

<connectionStrings>
<add name="MS_AzureStoreConnectionString" connectionString="UseDevelopmentStorage=true;" />
</connectionStrings>
 
That’s it – I hope you enjoy these new features in ASP.NET WebHooks!

Happy New Year!

Henrik

Task runners in Visual Studio 2015

$
0
0

trx

There are various kinds of tasks typically used by web developers as part of their workflow. Everything from bundling and minifying JavaScript files, to compiling LESS files into CSS and even running custom batch or PowerShell scripts.

In a sense you can say that tasks are steps that needs to be performed to make the application run that are separate from coding it.

Visual Studio 2015 supports any kind of custom task execution from the new Task Runner Explorer tool window. It ships with built-in support for two very popular web centric task runners – Grunt and Gulp.

The Task Runner Explorer shows a list of available tasks and executing them is as simple as a click of the mouse. You can even bind any task to specific events that occur in Visual Studio such as Build, Clean and Project Open.

Sure you can use the command line to invoke your custom tasks, but with the integration into Visual Studio you can automate a lot more of your workflow.

There are quite a few extensions freely available that adds support for a lot more task frameworks.

NPM Scripts Task Runner

npmThis task runner adds support for npm scripts listed in the scripts section of a package.json file. This allows you to run any executable with any arguments simply by modifying package.json.

You can read more about npm scripts and how to set it up in the npm documentation.

Download | Source code

 

Command Task Runner

commandIs similar to the NPM Script Task Runner in that it can execute any executable, but with the main difference that you don’t need a package.json file. Also, this extension supports inline PowerShell and batch commands.

This make it perfect for any type of project that has custom .cmd or .ps1 files as part of the build process.

Download | Source code

 

WebPack Task Runner

webpackFrom the webpack website: webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

Webpack is getting more and more popular and seems to be resonating very well with React.js developers.

Download | Source code

 

Broccoli Task Runner

broccoliFrom the Broccoli is a build tool that is very popular with developers using the ember.js JavaScript framework, but can be used in any web project.

From their website: A fast, reliable asset pipeline, supporting constant-time rebuilds and compact build definitions. Comparable to the Rails asset pipeline in scope, though it runs on Node and is backend-agnostic.

Download | Source code

 

Brunch Task Runner

brunchBrunch is a builder. Not a generic task runner, but a specialized tool focusing on the production of a small number of deployment-ready files from a large number of heterogeneous development files or trees.

Download | Source code

 

ASP.NET 5 Task Runner

aspnetAllows you to easily execute the scripts in project.json’s scripts section such as prepublish and postbuild. But you can also specify your own custom scripts that this extension can then execute.

This makes it possible to setup a full build process from a single location.

Download | Source code

 

All of these extensions demonstrate just how flexible the Task Runner Explorer in Visual Studio is. If you find your favorite task runner framework to be missing from this list, please let us know in the comments.

Visual Studio keeps showing suggested extensions

$
0
0

In Visual Studio 2015 Update 1 we introduced a mechanism that would analyze a web project and suggest helpful Visual Studio extensions based on what it could find. For instance, if the project was using the Bootstrap CSS framework, it would suggest two very cool extensions specifically for working with Bootstrap.

Based on your project, we have identified extensions you may find helpful
 
It works by showing a yellow bar at the top of the editor when an HTML document is being opened. The idea was to improve the user experience by suggesting extensions from the community that would make you more productive based on your current context.

While some people found these suggestions helpful and installed the extensions, some people weren’t interested and they clicked the Don’t Show Again button. However, a bug had sneaked its way into this feature so that Visual Studio would always show the yellow bar when opening an HTML document.

To work around this issue, you have to set the setting to hide the yellow bar manually. Go to Tools -> Options and set the Identify Helpful Extensions option to False.

Advanced HTML settings

Disabling this feature solves another issue as well. The issue happens when there is a Git merge conflict or with Annotate and Excluded Folder documents. The error message isn’t very informative and looks like this:

An exception has been encountered

The ActivityLog.xml is a bit cryptic but it contains a reference to Microsoft.VisualStudio.Html.Package.Extensions.ExtensionsManager.OnTextViewCreated which is where this issue occurred.

These issues have all been fixed and will be available soon in a future release.

ASP.NET 5 is dead – Introducing ASP.NET Core 1.0 and .NET Core 1.0

$
0
0

This post originally appeared on Scott Hanselman’s blog at: http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx

Naming is hard.

There are only two hard things in Computer Science: cache invalidation and naming things. – Phil Karlton

It’s very easy to armchair quarterback and say that “they should have named it Foo and it would be easy” but very often there’s many players involved in naming things. ASP.NET is a good ‘brand’ that’s been around for 15 years or so. ASP.NET 4.6 is a supported and released product that you can get and use now from http://get.asp.net.

However, naming the new, completely written from scratch ASP.NET framework “ASP.NET 5″ was a bad idea for a one major reasons: 5 > 4.6 makes it seem like ASP.NET 5 is bigger, better, and replaces ASP.NET 4.6. Not so.

So we’re changing the name.

Reintroducing ASP.NET Core 1.0 and .NET Core 1.0

  • ASP.NET 5 is now ASP.NET Core 1.0.
  • .NET Core 5 is now .NET Core 1.0.
  • Entity Framework 7 is now Entity Framework Core 1.0 or EF Core 1.0 colloquially.

Why 1.0? Because these are new. The whole .NET Core concept is new. The .NET CLI is very new. Not only that, but .NET Core isn’t as complete as the full .NET Framework 4.6. We’re still exploring server-side graphics libraries. We’re still exploring gaps between ASP.NET 4.6 and ASP.NET Core 1.0.

Which to choose?

To be clear, ASP.NET 4.6 is the more mature platform. It’s battle-tested and released and available today. ASP.NET Core 1.0 is a 1.0 release that includes Web API and MVC but doesn’t yet have SignalR or Web Pages. It doesn’t yet support VB or F#. It will have these subsystems some day but not today.

We don’t want anyone to think that ASP.NET Core 1.0 is the finish line. It’s a new beginning and a fork in the road, but ASP.NET 4.6 continues on, released and fully supported. There’s lots of great stuff coming, stay tuned!

Viewing all 7144 articles
Browse latest View live


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