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 - ASPHostPortal :: Integrate Stripe .Net Payment Processing Library With your ASP.Net 4.5 C# Application

clock November 11, 2014 06:05 by author Ben

The advantages of Stripe

Accepting payment cards on-line has not been less difficult than it's now. Businesses like Stripe have created it simple for builders like ourselves to include sophisticated payment methods into our internet programs without having to bother with the safety compliance and audits which are typically associated with payment card info storage.

 


Stripe lets you preserve customers’ details securely, create custom made payment structures, and also develop customized payment programs for multiple or one customers.

Stripe.Net

Stripe.Net is definitely an open resource library to the Microsoft .NET Framework that permits straightforward integration into your .NET tasks. Today we are going to only be masking the integration of Stripe.Net into an ASP.NET undertaking, however you can study the documentation and find out more regarding how to use the Stripe.Net library on the Stripe.Net Github repository.

Our Project

For your goal of the tutorial, we are going to be producing a brand new ASP.Net internet application. Should you already have an application that you simply want to combine Stripe.Web with, which is amazing! If not, or for those who have by no means developed an ASP.Net application, follow these initial step to obtain up and running.

Very first, we'd like to create the venture. We will do that by opening up Microsoft Visual Studio, and picking Visual C# > Web > ASP.Net Web Forms Application. Notice that we have been utilizing the .NET 4.5 Framework on the best from the window, really feel totally free to change the framework model in your liking. Push OK.

Referencing the Stripe.Net Library

When you have your software open up in Visual Studio, you’re likely to require to put in the Stripe.Net library to use it is classes and methods inside your program. By reading the Stripe.Net Github page, we have discovered the library is obtainable like a NuGet package in Visual Studio, which is the optimal way to integrate the library, so that is how we’re going to do it. Within your solution explorer locate the References listing and proper click on it. You will see a choice labelled “Manage NuGet Packages…”, click that alternative within the dropdown menu.

You'll be prompted with the Control NuGet Packages window. Navigate down the remaining menu and click on Online. Now you'll be able to kind Stripe.Net to the lookup bar in the top left corner in the window, and (if you are related to the world wide web) you will note the Stripe.Net library seem within the center of the window. Set up the package and you'll notice that it installs the json.NET and Stripe.NET package inside the references listing. The explanation this occurs, would be that the Stripe.Net library relies on the json.NET library, so that you must include it into your references directory to ensure that Stripe.Net to operate.

Authentication

The last step of integration in this process, is verifying your account with Stripe. The designated authentication method that Stripe has provided for us is their developer API Key. This key is unique to each Stripe user and verifies your account so Stripe knows which user account all of your transactions belong to.

We only need to place this API Key into our application once by opening up the Web.config file and placing the following code before the </configuration> tag.

<appSettings>
  <add key="StripeApiKey" value="[your API Key]"/>
</appSettings>

Now you’re all set to use the Stripe.NET library in your application! Just remember to reference the json.NET and Stripe.NET libraries in any files you are using Stripe.NET functionality.

 



ASP.NET 4.5 Hosting - ASPHostPortal :: WebSockets Utilizing .NET 4.5 With the Asynchronous HTTP Handler and System.Web.WebSockets

clock November 7, 2014 07:32 by author Mark

What is WebSockets?

WebSockets is really a new normal way for net apps to have a persistent relationship in between consumer and server. It allows bidirectional (“full-duplex”) communication between an online browser as well as the web server.

Preparing Windows to support WebSockets

To be able to have Windows 8 (or Windows 2012 for instance) assistance for WebSocket, we initial need to add some features towards the Windows operation system. This may be carried out making use of the “Turn Windows features on or off” control panel product. The features we’d like are :
.NET Framework 4.5 Advanced Services → WCF Services → HTTP Activation

and also: Internet Information Services → World Wide Web Services → Application Development Features → WebSocket Protocol

Creating a generic asynchronous HTTP Handler
Let’s start of with creating a new item of type ASP.NET Handler.

Visual Studio generates a class that implements the IHttpHandler interface. We’ll change that to derive from your abstract base course HttpTaskAsyncHandler. Also, as opposed to employing an interface, we’ll override the IsReusable house and ProcessRequest approach. Every thing is run asynchronously, so we seriously depend upon the async/await keywords and phrases as well as the task class. We’ll retailer the incoming WebSocket instance within a personal house, thus permitting us to get in touch with it’s techniques from inside of our class. The code must search such as this:

using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Web;
namespace StockTickerDemo
{
    public abstract class WebSocketAsyncHandler : HttpTaskAsyncHandler
    {
        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private WebSocket Socket { get; set; }
        public override async Task ProcessRequestAsync(HttpContext httpContext)
        {
            await Task.Run(() =>
            {
                if (httpContext.IsWebSocketRequest)
                {
                }
            });
        }
    }
}


Notice that we’re producing a generic class implementation. Though this class will not outline summary methods, it’s going to only find it is usefulness whenever a specialised class derives from it. Therefore the WebSocketAsyncHandler class is marked summary. Also note that the code we apply is wrapped inside a Task occasion.

Defining the WebSocket concept handlers

When the HTTP ask for is in reality a WebSockets ask for, the WebSocket occasion is saved inside the corresponding home. Then we should also examine the State home of that occasion. Dependent on it’s price, we get in touch with the corresponding virtual approach. The following code illustrates this:


if (httpContext.IsWebSocketRequest)
{
    httpContext.AcceptWebSocketRequest(async delegate(AspNetWebSocketContext context)
    {
        this.Socket = context.WebSocket;
        while ( this.Socket != null || this.Socket.State != WebSocketState.Closed)
        {
            ArraySegment< byte> buffer = new ArraySegment< byte>( new byte[1024]);
            WebSocketReceiveResult receiveResult = await this.Socket.ReceiveAsync(buffer, CancellationToken.None);
            try
            {
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Text:
                        string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
                        this.OnMessageReceived(message);
                        break;
                    case WebSocketMessageType.Binary:
                        this.OnMessageReceived(buffer.Array);
                        break;
                    case WebSocketMessageType.Close:
                        this.OnClosing( true, receiveResult.CloseStatusDescription);
                        break;
                }
                switch ( this.Socket.State)
                {
                    case WebSocketState.Connecting:
                        this.OnConnecting();
                        break;
                    case WebSocketState.Open:
                        this.OnOpen();
                        break;
                    case WebSocketState.CloseSent:
                        this.OnClosing( false, string.Empty);
                        break;
                    case WebSocketState.CloseReceived:
                        this.OnClosing( true, string.Empty);
                        break;
                    case WebSocketState.Closed:
                        this.OnClosed();
                        break;
                }
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }
        }
    });
}


 And of course the virtual methods:


protected virtual void OnConnecting()
{
}
protected virtual void OnOpen()
{
}
protected virtual void OnMessageReceived(string message)
{
}
protected virtual void OnMessageReceived(byte[] bytes)
{
}
protected virtual void OnClosing(bool isClientRequest, string message)
{
}
protected virtual void OnClosed()
{
}
protected virtual void OnError(Exception ex)
{
}


This is all the code we need to allows us to respond to messages from the client. Now we need to implement the code to send messages to the client. WebSockets allow us to send/receive binary or text messages (asynchronously!). This implementation is as such:


protected async Task SendMessageAsync(byte[] message)
{
    await this.SendMessageAsync(message, WebSocketMessageType.Binary);
}
protected async Task SendMessageAsync(string message)
{
    await this.SendMessageAsync( Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text);
}
private async Task SendMessageAsync(byte[] message, WebSocketMessageType messageType)
{
    await this.Socket.SendAsync(
        new ArraySegment(message),
        messageType,
        true,
        CancellationToken.None);
}


This generic class can be used in any ASP.NET project to implement your own custom WebSockets handler. All you need to do i s derive your class from it and implement the virtual methods.
Deriving a specialized class and implementing the specifics.
Now that we have written the generic class. we can implement the specifics.


namespace StockTickerDemo
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Threading.Tasks;
        public class StockTickerWebSocketAsyncHandler : WebSocketAsyncHandler
    {
        private static double[] FacebookQuotes
        {
            get
            {
                return new double[] { 28.38, 28.45, 27.53, 29.11, 29.23 };
            }
        }
        private static double[] GoogleQuotes
        {
            get
            {
                return new double[] { 758, 760, 764, 765, 769 };
            }
        }
        private double[] ActiveQuote { get; set; }
        protected override void OnMessageReceived( string message)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            Task task;
            if ( string.Equals(message, "STOP" ))
            {
                IndexTicker .DefaultInstance.Update -= this .IndexTicker_Update;
                this.ActiveQuote = null;
                task = this.SendMessageAsync( "Stopped" );
            }
            else
            {
                if ( this.ActiveQuote == null)
                {
                    IndexTicker .DefaultInstance.Update += this .IndexTicker_Update;
                }
                if ( string.Equals(message, "FB" ))
                {
                    this.ActiveQuote = FacebookQuotes;
                }
                else
                {
                    this.ActiveQuote = GoogleQuotes;
                }
                task = this.SendMessageAsync( "Started" );
            }
        }
        protected override void OnError( Exception ex)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            var task = this.SendMessageAsync( string.Format( "Something exceptional happened: {0}", ex.Message));
        }
        private void IndexTicker_Update( object sender, IndexTickerEventArgs e)
        {
            // Assignment prevents warning "Because this call is not awaited...Consider applying the 'await' operator
            // This is intentional => fire and forget
            var task = this .SendMessageAsync(this .ActiveQuote[e.QuoteIndex].ToString());
        }
    }


The IndexTicket is a single instance of a class that implements a basic Timer and fire’s an event every 5 seconds. Each time giving a random number between 0 and 4. This number corresponds to n index of the array with quote values. This timer is started and stopped in the Global.asax handlers for the web application. This simulates the stock quote ticker. All that the HTTP Handler does at start/stop is assign a event handler to the timer or remove it. When it handles the timer event it send a text message back to the browser client.

Registering the handler

Now that the handler code is ready, we should tell IIS to use this handler. This is done by registering the handler in the web.config:


<configuration>
  <system.webServer>
    <handlers>
      <add name="StockTickerWebSocketAsyncHandler" verb="*" path="StockTicker"
               type="StockTickerDemo.StockTickerWebSocketAsyncHandler, StockTickerDemo"
               resourceType="Unspecified" />
    </handlers>
  </system.webServer>
</configuration>


The web socket service is reachable through ws://<domain>/<site:ports>/StockTicker. The type attribute tells IIS where it can find the handler.
This concludes the server-side part of the demo.

The client HTML page.

Almost done. Now all we have to do is implement the client-side JavaScript and HTML. The HTML page is simple and straight forward. It has a script reference to jQuery and to the JavaScript files, which we will create further on in this article.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Stock Ticker using Web Sockets!</title>
    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/StockTicker.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <input id="stockQuoteFB" type="radio" name="stockQuote" checked="checked"/><label for="stockQuoteFB">Facebook</label>
        <input id="stockQuoteGOOG" type="radio" name="stockQuote" /><label for="stockQuoteGOOG">Google</label>
    </div>
    <div>
        <button id="startButton" value="Start">Start</button>&nbsp;
        <button id="stopButton" value="Stop" disabled="disabled">Stop</button>
    </div>
    <div id="stockQuoteInfo">
    </div>
</body>
</html>


Returned message texts will appear within the stockQuoteInfo div element.

JavaScript

In the JavaScript file we first create a client instance of a WebSocket class and hook up the event handlers so we can we process the messages send from the server :
var stockTickerService;
$(document).ready(function () {
    stockTickerService = new WebSocket( "ws://localhost:55555/StockTicker" );
    stockTickerService.onopen = function () {
        $( "#stockQuoteInfo").append("Connection opened
" );
    }
    stockTickerService.onmessage = function (message) {
        $( "#stockQuoteInfo").append(message.data + "
" );
    }
    stockTickerService.onclose = function () {
        $( "#stockQuoteInfo").append("Connection closed" + "
" );
    }
    stockTickerService.onerror = function (error) {
        $( "#stockQuoteInfo").append(error.data + "
" );
    }


 In the WebSocket constructor we pass the “ws:” url to the WebSocket service as it’s registered in the web.config. Also, we have a little custom JavaScript object to easily communicate the stock quote identifiers:
var NASDAQ = {
    'FACEBOOK' : 'FB',
    'GOOGLE': 'GOOG'
}

Now we only have to wire up the button click handlers to start and stop receiving messages. That is also done in the $(document).ready function:
$("#startButton").click( function () {
    if( $("#stockQuoteFB")[0].checked){
        stockTickerService.send(NASDAQ.FACEBOOK);
    } else {
        stockTickerService.send(NASDAQ.GOOGLE);
    }
    setUIState(true);
});
$("#stopButton").click( function () {
    stockTickerService.send( "STOP");
    setUIState(false);
});

 Now we can run our little web application. Pressing Start will initiate sending the stock numbers to the client:

Pressing the Stop button will send a message to the server, which causes the HTTP Handler to unhook the event. As a result the web server will stop sending messages to the client.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to enable Multicore JIT in an .NET 4.5 application

clock November 6, 2014 11:20 by author Mark

Multicore Just-in-Time (JIT)

In the .NET framework 4.5, Microsoft has introduced an enhancement of the pervious JIT compiler by making it a Multicore JIT compiler, that runs on the two cores and supports parallelism in the compilation process in order to improve the launch performance during application startup.

From the developer point of view the Multicore JIT is a very cool runtime feature in .NET Framework 4.5 to improve their productivity and speed up the overall performance of an application. Now the developer can benefit from multicore processors to speed up the application compilation process.

The Multicore JIT compiler works in parallel with two cores. Because of the two cores, Multicore JIT can make your application start the process faster at startup. Multicore JIT provides significant improvements to Web based applications as well as Desktop Windows Presentation Foundation (WPF) applications.

Now let's start, how does Multicore JIT work?

Working of Multicore JIT

Nowadays, every PC has at least two cores, so the JIT compiler is built to make the investment worthwhile. Using the Multicore JIT, methods are compiled on two CPUs so that the application is able to reach the end of its startup execution quickly.

The compilation process is done in two cores that run in parallel executing the Multicore JIT compiler. The more effective Multicore JIT will reduce the startup time of an .NET application.

Multicore JIT uses the two modes of operation.

Recording mode: It is the first mode, when JIT compiles the entire program and creates a JIT profile using a profile optimization class and saves the profile that was executed to a given folder to disk.

Playback mode: This mode is used when the application is launched subsequently. Playback mode is used to load the profile that was saved during the Recording mode from the disk using the background JIT thread in order to support the main thread.

 

The feature works by the JIT compiling the methods likely to be executed based on profiles created during previous compilations, that will runs on a separate processor core taking care of the JIT Compilation while the main execution thread runs on a different core.

In the ideal case, the second core quickly gets ahead of the mainline execution of the application, so whenever a method is required it is already compiled. As a result, the main thread doesn't need to do as much compilation, and your application launches faster.

In order to know which methods to compile, the feature generates profile data in the Recording mode that keeps track of the methods that are executed. Then the next time the application runs the call will look for that profile and when it finds it then it plays back; that means it starts compiling all the methods that was saved for that profile.

Note: MultiCore JIT requires a multicore machine to take advantage of its algorithms otherwise the CLR will ignore it on single core machines.

How to enable Multicore JIT in an .NET 4.5 application.

You can use this feature of the runtime to significantly improve the startup times of both client applications and Web sites in .NET framework 4.5
Since ASP.NET applications run in a hosted environment, this feature is turned on for these applications automatically. Therefore JIT compiling using multiple cores is enabled by default in ASP.NET 4.5 and Silverlight 5.

But, if you want to disable this feature

in your ASP.NET 4.5 applications then write the following code in the web.config file.

<system.web>
  <compilation profileGuidedOptimizations="None" />
</system.web>

But in a Windows based application, you will need to enable Multicore JIT feature explicitly.

Let's see how.

It is simple to use Multicore JIT, there is a class in the .NET Framework named "System.Runtime.ProfileOptimization" that you can use to start profiling at the entry point of your application.

Optimization Profilers

The ProfileOptimization is a new type introduced in .Net 4.5 to improve the startup performance of application domains in applications that require the just-in-time (JIT) compiler by performing background compilation of methods that are likely to be executed, based on profiles created during previous compilations.

See the MSDN documentation for more information.

http://msdn.microsoft.com/en-IN/library/system.runtime.profileoptimization.aspx

The two methods that you can call at the entry point of your application.
SetProfileRoot: This method is used to specify the root path, where to save the JIT profile compiled information for optimization.

StartProfile: This method is used to start Multcore just in-time compilation.

You must write the following code in your application constructor in order to enable Multicore JIT.

public App()
{

 ProfileOptimization.SetProfileRoot(@"C:\MyAppFolder");
 ProfileOptimization.StartProfile("Startup.Profile");

}

Now that's all to enable the Multicore feature in your application; the rest of the work will be handled by the CLR automatically.

Conclusion

This is definitely a great feature for improving application launch performance. Applications now startup 50% faster than before. If you are developing an web application, you will no need to do something and if you are developing a Desktop application then you can turn on this amazing feature with only a few lines of code.

 



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