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 :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



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 use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



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.

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: How You Can Develop Asynchronous Device Page in ASP.Net 4.5

clock November 4, 2014 05:15 by author Ben

Within this tutorial we'll make use of the most recent ASP.Net 4.5 methods to come back up with a asynchronous gadget web page via help of Visual Studio Express.

The sample software that we're going to use listed here makes use of new async and awaits key phrases and they're obtainable in .NET 4.5 and Visual Studio 2012. This allows the complier to hold the responsibility of getting care from the complex transformations that are necessary for asynchronous programming. Also the compiler will allow you to write the code using the C#'s synchronous manage movement constructs. Therefore the compiler on its own applies the transformations which can be necessary to deploy call-backs. This is done in order to prevent blocking threads.



ASP.Net asynchronous web pages has to comprise in the Web page directive and Async feature label set to “true”. The code detailed under demonstrates the Page directive with all the value of Async attribute set to accurate for the DeviceAsync.aspx page.

<%@ Page Async="true" Language="C#" AutoEventWireup="true"
    CodeBehind="DeviceAsync.aspx.cs" Inherits="WebAppAsync.DeviceAsync" %>

The below code reflects the Device synchronous Page_Load method as well as the DeviceAsync asynchronous page. In case the browser supports the HTML5 <mark> element, the changes can be seen in DeviceAsync in yellow highlight.

protected void Page_Load(object sender, EventArgs e)
{
   var deviceService = new DeviceService();
   DeviceGridView.DataSource = deviceService.GetDevice();
   DeviceGridView.DataBind();
}

The below displays the asynchronous version:
protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDeviceSvcAsync));
}

private async Task GetDeviceSvcAsync()
{
    var deviceService = new DeviceService();
    DeviceGridView.DataSource = await deviceService.GetDeviceAsync();
    DeviceGridView.DataBind();
}

The beneath lists the changes that were applied to permit DeviceAsync page to be asynchronous.

  • This is a need to to set the Webpage directive Async attribute to "true".
  • The RegisterAsyncTask indicates is deployed to sign up an asynchronous task that includes of the code which can be operated asynchronously.
  • The new GetDeviceSvcAsync approach is labelled with the async key phrase that informs the compiler to make callbacks for parts of the body and in addition to generate a Job of its personal which is returned.
  • Should you recognize, we appened "Async" towards the asynchronous technique title although this is not required however it is the conference while you're writing asynchronous methods.
  • The return sort in the Task defines the perform in progress and offers the callers of the approach having a deal with through which to halt for your completion of the asynchronous operation. The return type in the new GetDeviceSvcAsync method is Activity.
  • Internet support call helps make use of the await keyword.
  • The asynchronous web service API was referred to as GetDeviceAsync.

GetDeviceAsync is another asynchronous method that's known as inside of the GetDeviceSvcAsync method physique. Task<List<Device>> is immediately returned by a GetDeviceAsync that will finally full on the availability of the info. For your purpose that you'd not want to proceed additional just before you have the device data, the code waits for the task making use of the await keyword. 1 might make usage of the await keyword just in techniques annotated with all the async search term.

Until finally we have the completion from the task, the thread is not blocked from the await search term. It indications up the rest of the method as being a callback within the job, and immediately returns. Within the completion in the awaited activity, that callback will likely be invoked thereby resuming the implementation from the method right exactly where it left off.

The below code displays the GetDevice and GetDeviceAsync techniques:

public List<Device> GetDevice()
{
   var uri = Util.getServiceUri("Device");
   using (WebClient webClient = new WebClient())
   {
        return JsonConvert.DeserializeObject<List<Device>>(
            webClient.DownloadString(uri)
        );
    }
}

public async Task<List<Device>> GetDevicesAsync()
{
    var uri = Util.getServiceUri("Devices");
    using (HttpClient httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(uri);
        return (await response.Content.ReadAsAsync<List<Device>>());
    }
}

The asynchronous modifications which were utilized are same as those applied to the DevicesAsync above.

  • Async key phrase was used to annotate the method signature, the return sort was changed to Task<List<Device>>, and Async was appended for the technique title.
  • The asynchronous HttpClient is utilized rather than synchronous WebClient class.
  • The await keyword was used to the HttpClient GetAsync asynchronous method.

The below image displays the asynchronous device see.

The browsers screen of the gadget info is same concerning the check out that's created by the synchronous contact. Here the only difference will be the asynchronous model might be more execute ant below main hefty loads.

Methods that are hooked up with RegisterAsyncTasks will likely be executed instantly after PreRender. 1 may also utilize async void page events directly as may be seen from the under code:

protected void Page_Load(object sender, EventArgs e) {
    await ...;
    // do work
}

The disadvantage for the async occasions is that the programmers now don't have the complete use of the occasions when activities are applied. Example, in case both an .aspx as well as a .Master signifies Page_Load occasions and a minimum of 1 of them is asynchronous, there's no guarantee from the execution.

Getting a developer, it is recommended to apply the above stated procedure to come up with the asynchronous unit web page making use of the newest ASP.Net 4.5 systems.

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: Producing Data-driven Web Apps Utilizing ASP.Net 4.5 Web Forms

clock October 16, 2014 06:30 by author Ben

Data binding is less complicated and more effective in ASP.Net 4.5 Kinds.This publish discuss about making Data-driven software using ASP.Net 4.5 preview. Additionally, it discuss about distinct Info access methods, especially about design entry binding features in Internet Types. You need to install Visual Studio 11 Developer preview to use this function.

Typical ASP.Net developer could use a single from the following Info Access mechanisms for binding the data

  • You could set up your Database Initial - Making a Schema and creating product from it. Listed here model is actually a class which you're going to communicate with your databases from your code.
  • You may setup your Product Initial - Instead of developing the database first, we design the entity model initial eg: making use of entity framework. Style your product first after which generate a schema and code.
  • You could setup your Code First- On this strategy you very first write code to design and style the product and after that produce a schema making use of that code.

Your model designer floor could search like beneath should you stick to the any of above Information Accessibility mechanisms


This post discuss the third strategy Code Very first Information Entry mechanism to connect with the databases. This method makes use of the Product Binding , the phrase barrowed from MVC. In MVC whenever you call an motion method which received some parameters in which you need to move values from question string or from cookie assortment and bind these values into parameters. Design Binding does this in MVC. The concept is comparable Web Types but context is little little bit different.

Step1 Construct courses which represent your model.

Incorporate a folder within your remedy referred to as Model and then add new item class named Issue.



The difficulty class code getting some homes which appear like as below


Consequently the above mentioned code turns into a database desk. You can discover info annotations on every home. You'll be able to specify your validation at a single spot. eg: Required in above properties.

Produce an additional class which represent the database context named IssuesDb.


Now add the connection string in web.config file with same name as your DbContext. Here it is IssuesDb.

Create another class which initializes your database as shown below

public class Dbinitializer : DropCreateDatabaseIfModelChanges<IssuesDb>

    {

      protected override void Seed(IssueDb context)

        {

            context.Issues.Add(new Issue { CreatedBy="xyz",

            CreatedOn = new DateTime(), Title="Issue1"})

            context.Issues.Add(new Issue { CreatedBy="abc",

             CreatedOn = new DateTime(), Title="Issue2"})

            context.Issues.Add(new Issue { CreatedBy="aaa",

           CreatedOn = new DateTime(), Title="Issue3"})       

      

       }

You'll be able to override the tactic See to insert some values into the produced desk.

Step2 Displaying the above specifics in UI. We will set up a Gridview to Model Binding to list the details from database table.


We are not performing anything at all new listed here , Product Binding is merge of concept from Object information resource and MVC Design Binding. Specify your ModelType and SelectMethod to point out the main points.

We will also template fields to gridview and established the binding expression to point out the values but in different way.

The normal way is one thing proven below


The problem with the above expression is we do not know the type of the column. Now you will get an intellisense inside data binding expressions with a name Item.


The GetIssues method code will look like as below


Before running your application, Initialize the database initializer class in Global.asax file Application Start method

DataBase.SetInitializer(new IssueDbInitializer());


It also creates database and tables as you specified in the model class


Step3 Now let us add a filter to this application.

Add a lable, text box and a button to UI.


Now modify GetIssues method as shown below where Model Data binding comes into the picture.


The method having a parameter named createdSince that is a textbox id and we have been telling the strategy it is a handle. You are able to go ahead and take price from parameter and filter the values as demonstrated below


Instead of finding the control and writing the code, Model Binding takes the input from the user and retrieves the values from Dbcontext.

Points to note:

There's no If !(IsPostBack) or button handlers to attain this functionality. Just get in touch with this process by passing the worth from this handle. that is it!. We will dynamically manipulate the query by just using the values in the user.

Step4 Adding a FormView which exhibits all particulars and permits you to insert and edit the issue. The FormView markup seems like as below


The GetIssue method code as below. The idea is enable autogenerated select column in gridview and show the details when you select the particular issue.


You saying to method to get the id value from issuesGrid control and return the issue details. Run the application then you will see the below result


Note that we've not composed any code to re-bind the values from database to grid. Design Binding maintain observe from the values of parameters across the submit backs. It truly retailers these values in viewstate.

The InsertMethod code seems as below


and above code you can see we are validating whether user is logged in or not and based  on that we are using ModelState to add the model error message.

ModelState represents the current state of Model Binding system on your page.

You can pass this error message to Validation Summary on your page by setting ShowModelStateErrors = true.


Another new point to notice is TryUpdateModel method which is an explicit Model Binding. This method tells model to try and bind the data from current request in to this issue variable.

The binding expression in InsertItem template in gridview will look like


Previously we do something like this


Run the application you then will begin to see the under screen


The update method exactly looks like insert method but having an additional parameter named id which is an id of record in the current Model Binding expression.


We have seen the new data-related improvements in ASP.NET 4.5 Web Forms with Model Binders and Data annotations.



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BulkEmail._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">              
                <h2>Send Bulk email using asp.net</h2>
            </hgroup>
            <p>To learn more about ASP.NET
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
       <h3>We suggest the following:</h3>
    <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
    <p>
       <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1" runat="server" Font-Bold="true" ForeColor="Green" Text="Total
Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size="Larger"></asp:Label> </p>
        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
        <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>
    </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:
Web.config

<connectionStrings>   
<add name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      
</connectionStrings>


In the code behind file (Default.aspx.cs) write the code as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
    public partial class _Default : Page
    {
        #region MySqlConnection Connection
        MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Try
            {
                if (!Page.IsPostBack)
                {

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
        /// <summary>
        /// This function is used for show message.
        /// </summary>
        /// <param name="msg"></param>
        void ShowMessage(string msg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
        }       
        #endregion
        #region Bind Data
        /// <summary>
        /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBind_Click(object sender, EventArgs e)
        {
            Try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();

            }
            btnBind.Visible = false;
        }
        #endregion
        #region Bulk email,GridView,gmail
        /// <summary>
        /// this code used to Send Bulk email 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Try
            {
                lbltotalcount.Text = string.Empty;
                foreach (GridViewRow grow in grvCustomers.Rows)
               {
                    string strCustomerID = grow.Cells[0].Text.Trim();
                    string strContactName = grow.Cells[1].Text.Trim();
                    string strAddress = grow.Cells[2].Text.Trim();
                    string strPhone = grow.Cells[3].Text.Trim();
                    string strEmail = grow.Cells[4].Text.Trim();               

                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("##NAME##", strContactName);
                    string to = strEmail;
                    string from = "[email protected]";
                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding = Encoding.UTF8;
                    message.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.NetworkCredential basicCredential = newSystem.Net.NetworkCredential("[email protected]", "Password");
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                    try
                    {
                        client.Send(message);
                        ShowMessage("Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Page Instrumentation in ASP.NET 4.5

clock December 27, 2013 11:03 by author Robert

 

In this article, I showed you how to use Page Instrumentation, a new  feature in ASP.NET 4.5 which might be useful for you during debugging.
ASP.NET 4.5 include a hidden gem called Page Instrumentation, very few people aware of this gem. You can use page instrumentation in ASP.NET 4.5 WebForm and MVC 5 or 4(assuming it targets 4.5). It allows you to inspect/instrument a web form or a mvc view during the rendering process. Page instrumentation are useful in scenarios when you have some performance issues regarding view engine rendering. In this article, I will show you how to use this feature in ASP.NET 4.5.

To start instrumenting a page, you need to inherit PageExecutionListener class.

The BeginContext will be called by a view engine before it renders the output for the specified context. Similarly, EndContext called by a view engine after it renders the output for the specified context. Both of these methods accept PageExecutionContext class as a parameter which have the following members.

All the properties of PageExecutionContext class are self explanatory. Let assume we have the following MVC view(for understanding how many times and when the BeginContext and EndContext will be invoke by the framework).

The Razor View Engine will emit the following C# code


Finally, here is a simple implementation of PageExecutionListener class which calculates the total time each time whenever something is written to the output response.

 



ASP.NET 4.5 Hosting with ASPHostPortal.com :: How to Send E-mail using ASP.NET 4.5

clock December 7, 2013 11:41 by author Mike

If you build a large site then you will be required to provide a facility for the users to contact the relevant department or web master through online form. This is the best way to prevent spam messages as users will not know the real e-mail id. The whole process of sending emails from an ASP.NET form has been simplified with the release of .NET Framework 4.5.

Look at the below figure where I added few Textbox controls.


Figure_1


You need to substitute FROM EMAIL ID, MAIL SERVER NAME, EMAIL ID and PASSWORD on the below code with relevant correct values.

Copy the code given below after providing correct values as mentioned above using Notepad, save it as an .aspx file and upload to your web server. The below code requires access to a shared Windows hosting server with ASP.NET 4.5:

<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
 
<script runat="server">  
 
    Protected Sub btnSubmit_Click1(sender As Object, e As EventArgs)
        Dim mail As New MailMessage()
 
        mail.To.Add(txtEmail.Text)
        mail.From = New MailAddress("FROM EMAIL ID")
        mail.Subject = "Contact Form"
 
        mail.Body = txtName.Text & vbCrLf & txtComments.Text
 
        Dim smtp As New SmtpClient("MAIL SERVER NAME")
        smtp.Credentials = New NetworkCredential("EMAIL ID", "PASSWORD")
 
        smtp.Send(mail)
        lblStatus.Text = "Your data has been submitted successfully"
        txtName.Text = ""
    txtEmail.Text = ""
    txtComments.Text = ""
 
    End Sub
</script>
 
<html>
 
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Contct Form Demo</title>
</head>
 
<body>
    <form id="form1" runat="server">
        Name -
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <br />
        Email -
        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
 
ErrorMessage="Please Enter Valid Email ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)
 
*"></asp:RegularExpressionValidator>
        <br />
        <br />
        Comments -
        <asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="71px" Width="301px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblStatus" runat="server"></asp:Label>
        <br />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click1" />
        <br />
        <br />
    </form>
</body>
</html>

Figure_2

In the above code, I have enabled validation for E-mail ID field. This means that if you forgot to enter e-mail id in correct format you will not be able to submit the form.

Looking for quality ASP.NET 4.5 Hosting? Look no further than ASPHostPortal.com Hosting!



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