ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 Hosting :: Task Parallel Library Improvements (Parralel Programming)

clock August 28, 2013 06:59 by author Mike

Microsoft has introduced a new set of libraries, diagnostic tools and  runtime in .NET 4.0 to enhance support for parallel computing. The main objective of these features is to simplify parallel development, i.e., writing parallel code in a natural idiom without having to work directly with threads. Microsoft has been working on ways to improve the performance of parallel applications in .NET 4.5, specifically those using the Task Parallel Library. Here is a preview of what you can expect to see:



Task, Task<TResult>
At the core of .NET’s parallel programming APIs is the Task object. With such an important class Microsoft took great pains to ensure it is as small as possible. Most of the properties for Task are stored not in the class itself, but rather a secondary object called ContingentProperties. This secondary object is created on an as-needed basis, thus reducing the memory footprint for the most common scenarios.

When .NET 4.0 was released the most common scenario was fork-join style programming such as seen with Parallel.ForEach and Parallel LINQ. With .NET 4.5 and the introduction of async, continuation style programming takes the forefront. Microsoft is so confident that this will be the predominate style that they are moving ContinuationObject into Task and the other fields into ContingentProperties. The end result is faster continuations and a smaller Task object.

The net result was a 49 to 55% reduction in the time it takes to create a Task<Int32> and a 52% reduction in size.


Task.WaitAll, Task.WaitAny
Imagine waiting for 100,000 tasks at the same time. On an x64 machine that would introduce 12,000,000 bytes of overhead above and beyond the size of the tasks themselves. With .NET 4.5 that overhead has dropped to a mere 64 bytes. WaitAny likewise dropped from 23,200,000 bytes of overhead to 152 bytes.

This dramatic change came about due to a change in how kernel synchronization primitives are used. In previous versions one primitive was needed per task. This has been reduced to one per wait operation, regardless of the number of tasks involved.

ConcurrentDictionary

In .NET only reference types and small value types can be assigned atomically. Larger value types such as Guid require are not read and written atomically. To work around this in .NET 4.0, the node objects used by the ConcurrentDictionary are recreated each time the value associated with a key is changed. In .NET 4.5 new nodes are only created if the values cannot be atomically written.To Improve Performance, Reduce Memory Allocations.

One way to reduce memory usage is to avoid using closures. Rather than capturing a local variable inside an anonymous function, one can pass in that information to the Task’s constructor as its “state object”. Starting with .NET 4.5, Task.ContinueWith will also support state objects.

Another technique to reduce memory usage is to cache common used tasks. For example, consider a function that accepts an array and returns a Task<int>. Since the result for the empty array case will always be the same, it would make sense to cache the Task representing the empty array.

The next tip is to avoid unnecessarily “inflating” tasks. A task is inflated when something triggers the creation of its ContingentProperties object. The most common causes for this are:

  • The Task is created with a CancellationToken
  • The Task is created from a non-default ExecutionContext
  • The Task is participating in “structured parallelism” as a parent Task
  • The Task ends in the Faulted state
  • The Task is waited on via ((IAsyncResult)Task).AsyncWaitHandle.Wait()

It should be noted that task inflation isn’t necessarily a bad thing. Rather, it is something to be aware of so that one doesn’t do unnecessary things such as pass in a CancellationToken that isn’t ever used.



ASP.NET 4.5 Hosting – ASPHostPortal.com :: Optimize Your Website Performance with ASP.NET 4.5

clock June 28, 2013 06:45 by author Ben

Microsoft ASP.NET is today the most powerful and fastest growing platform for Web development. ASP.NET powers some of world's largest Web sites and most demanding applications. And now, ASP.NET 4.5 can optimization your website performance.

Typical web site contains CSS files, Images and Javascript files along with you HTML elements. CSS files, Images and JS files will take some time to load into the browser though the loading time is in milliseconds but matters. The HTML is not taking much time but other elements are taking time to load in to the browser. The Typical ASP.NET web site might look like as below in Visual Studio. It may contain Scripts  folder, Images Folder, Styles Folder and a Default aspx page.

The first problem that we can see that too many HTTP requests which are going to images, CSS files and to JavaScript files.

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

We can use Bundling and Minifying the files to reduce those requests. In ASP.NET 4.5 you have the built-in features to these. Write one line of code in Global.asax to bring these HTTP Requests down.

The above line enables the minification for CSS and Javascript files, only these two. Minifying means removing whitespaces, comments and everything that browser does not need to understand. We can really compress these files using this technique.

Basically this bundling technique looks at the folder and takes all the files inside and bundles them into one file, no matter how many are in the folder. This all happens at runtime. It only happens at once.

The order of bundling of your files goes as first it takes all Jquery scripts first and then it takes custom scripts alphabetically from your solution explorer.

Instead of doing the references to individual files, You can do this

Styles/CSS is the convention. Folder name / CSS bundles all the css files on that folder. We can do the same foe JavaScript like this

Suppose if you want to bundle the files by taking from different directories in

In above code we are registering our own bundle named mycss and then we are adding file styles.css and a directory styles.

Compress components with gZip. we can enables this on IIS. You tell the server everything that respond to client that text based zip it. You can do this by changing the couple of attribute values in web.config file

In IIS 7.5 it enables for you by default, if you running on windows server 2008 then you need to set the attribute values to true.

Encoding the Images to Base64 Images

Above code shows before and after encoding the image.

You may not want to encode all images in your project but if you want the images that you want to embed along with style sheets then you can write some regular expressions as shown below.

We can even transform your response further using coffee script as shown below

You can optimize the images in your folder by using Visual Studio extension tool named Optimize Images and then you can refresh folder and compile.



ASP.NET 4.5 Hosting - Using Bundling and Minification in ASP.NET 4.5

clock April 25, 2013 09:12 by author andy_yo

Is it Important?
Minimising the number of requests the page has to perform can have a considerable effect on your site’s performance. IE6 and IE7 both limit the number of concurrent requests to 2, IE8 can handle up to 6. There is a lot you can to improve the initial load speed speed – one of which is bundling all your CSS and JS into two separate files. How much of a difference it could do. Well, as it turns out up to 30seconds on slower connections.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

Bundled and Minified vs. Non-Bundled
This is the standard ASP.NET MVC4 app with all the initial JS libraries and CSS. Over a slower connection, the difference can be up to 30seconds. However, even on faster connections, you can save up two seconds just by combining and minifying your scripts.

Image 1 : Non Bundled

Image 2 : Bundled and Minified

Bundling and Minification in ASP.NET 4.5

Luckily for us, the ASP.NET now ships with a new library called System.Web.Optimization. It provides pluggable bundling and minification functionality for your scripts and styles.

It lets you define bundles at application start and pass them to the BundleCollection. Creating a basic new bundle is quite simple. Let’s assume we would like to combine few CSS files

protected void Application_Start()
{
    ... other startup logic
 
    var cssBundle = new StyleBundle("~/Content/themes/base/css")
            .Include("~/Content/themes/base/jquery.ui.core.css",
            "~/Content/themes/base/jquery.ui.resizable.css");   
    BundleTable.Bundles.Add(cssBundle);
}

You can also create bundles for your JavaScript.

protected void Application_Start()
{
    ... other startup logic
 
    var jsValidationBundle = new ScriptBundle("~/bundles/jqueryval")
              .Include("~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
    BundleTable.Bundles.Add(jsValidationBundle);
}

Both StyleBundle and ScriptBundle take url of the bundled file as a constructor argument and use extension method .Include to add files. You can also use wildcard characters such as * in the include array. If you want to add the entire folder, use IncludeDirectory extension.

One thing to note, is what version of the System.Web.Optimization you have. The older version that came with the MVC4 beta used AddFile() syntax to add files to the bundles. However, if you install VS 2012RC you get a newer version of the DLL, which is a bit neater and uses the syntax shown above.

Rendering Helpers

The library also comes with two awesome helpers. When you develop locally, you want to have all the bundling setup, but you don’t want the bundling and minification to happen – it’s much easier to debug. The System.Web.Optimization has two helpers that address exactly that issue.

  <head>

        ... other content
        @Styles.Render("~/Content/themes/base/css", "~/Content/css")
        @Scripts.Render("~/bundles/jqueryval")
  </head>

When you run the debug setting in the compilation element in your web.config as false, the Styles and Scripts helpers will render the bundled files. However, settings debug=”true” will render them unbundled. Pretty cool!

<system.web>

    .....
    <compilation debug="false" targetFramework="4.5" />
    ....
</system.web>

And that’s not everything, the minified files will also have cache busting string attached based on the files in the bundles.

<link href="/Content/themes/base/css?v=UM624qf1uFt8dYtiIV9PCmYhsyeewBIwY4Ob0i8OdW81" rel="stylesheet" type="text/css" />



ASP.NET 4.,5 Hosting - ASPHostPortal.com :: Websockets with ASP.Net 4.5 and Visual Studio 2012

clock April 11, 2013 12:11 by author Ben

Web applications are becoming increasingly sophisticated and it is common to need to communicate with various services. There are a number of options to accomplish this task with probably the most popular being to continually poll a server with XHR requests. Other alternatives exist that delay disconnections. These can be tricky to implement and don’t scale well (sometimes worse than polling as they keep a connection open) so aren’t used as much.

 

HTTP isn’t really an ideal protocol for performing frequent requests as:

  • It’s not optimized for speed
  • It utilizes a lot of bandwidth for every request with various headers etc sent with every request
  • To keep an application up to date many requests must be sent
  • Provides limited cross domain support
  • Firewalls & proxys sometimes buffer streaming/long polling solutions increasing latency
  • Long polling & streaming solutions are not very scalable

WebSockets are a new technology that attempts to resolve some of these limitations by:

  • Sending the minimum amount of data necessary
  • Making more efficient usage of bandwidth
  • Providing cross domain support
  • Still operating over HTTP so it can transverse firewalls and proxies
  • Works with some load balancers (TCP l4)
  • Provides support for binary data (note some JavaScript implementations don’t currently support this)

When would web sockets be a suitable protocol for your application?
You might want to consider using web sockets in the following scenarios:

  • Games
  • Real time data
  • Chat applications
  • News tickers

Websockets pitfalls
Websockets is a relatively new protocol that has already undergone a number of versions as various issues are addressed. This is important as support across browsers varies.
At the time of writing Websockets (in some form) can be used by the following browsers (check caniuse.com for the most up to date info):

  • IE10
  • Chrome 13+
  • Firefox 7
  • Safari 5+
  • Opera 11+

Earlier implementations of websockets had some security issues so your connections may work but are not secure (Firefox disabled support in Firefox 4 & 5 for this reason).
The other issue that you may encounter is that some older proxy servers don’t support the http upgrade system that websockets uses to connect so some clients may be unable to connect.

.NET 4.5 Web Socket Support
.NET 4.5 introduces a number of APIs for working with web sockets. If you find you need more control than the ASP.net API’s offers then look into WCF as that has also been updated. Before we begin there are a couple of requirements for using ASP.net web sockets API:

  • Application must be hosted on IIS 8 (available only with some version of Windows 8 – please note currently IIS Express currently does not work)
  • Web Sockets protocol feature installed (IIS option)
  • .net 4.5
  • A compatible browser on the client (IE10 or Chrome will 18 work fine at time of writing)
  • It would help if your Chinese birth animal was the horse

Hello Web Sockets Example!
Ok I am going to assume that you are already working with some version of Windows 8 that has IIS & ASP.net 4.5 installed. The other thing we are going to need to do is make sure IIS has the Web Sockets Protocol feature installed (this is in the add/remove programs bit):

- First create a new empty ASP.net project called WebSockets
- Add the Nuget package Microsoft.Websockets
- Pull down the latest jQuery library and put it in a scripts directory (I am using 1.7.2) – note jQuery isn’t necessary it just saves a bit of tedious event and manipulation code.

Now add a file called index.htm and enter the following code:

<!doctype html>
<head>
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var name = prompt('what is your name?:');
var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name=' + name;
alert('Connecting to: ' + url);
ws = new WebSocket(url);
ws.onopen = function () {
$('#messages').prepend('Connected <br/>');
$('#cmdSend').click(function () {
ws.send($('#txtMessage').val());
$('#txtMessage').val('');
});
};
ws.onmessage = function (e) {
$('#chatMessages').prepend(e.data + '<br/>');
};
$('#cmdLeave').click(function () {
ws.close();
});
ws.onclose = function () {
$('#chatMessages').prepend('Closed <br/>');
};
ws.onerror = function (e) {
$('#chatMessages').prepend('Oops something went wront <br/>');
};
});
</script>
</head>
<body>
<input id="txtMessage" />
<input id="cmdSend" type="button" value="Send" />
<input id="cmdLeave" type="button" value="Leave" />
<br />
<div id="chatMessages" />
</body>
</html>


We need to create an http handler so add a new generic handler to the project called ws.ashx and enter the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class WSHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new TestWebSocketHandler());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

Finally we need to create something to handle the websocket connection (TestWebSocketHandler that is created in the AcceptWebSocketRequest method).
Create a new class called TestWebSocketHandler and enter the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class TestWebSocketHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["name"];
clients.Add(this);
clients.Broadcast(name + " has connected.");
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0} said: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);


That’s all you need so now compile the project and run it in a compatible browser (IE10 or the latest Chrome will do fine) making sure you are hosting your project from IIS (project properties if you are not).


Once you have run it up you will be prompted to provide a name, then an alert box will indicate the end point of your application (ws://localhost/.. – note the secure https version is wss://).


Now open up a different browser and you should find you can via websockets.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in