European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

HostForLIFE.eu Proudly Launches ASP.NET Core 1.0 RC2 Hosting

clock June 4, 2016 00:57 by author Peter

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET Core 1.0 RC2 hosting in their entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET Core 1.0 RC2 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

A key change that occurred between RC1 and RC2 is the introduction of the .NET command-line interface.  This tool replaces the dnvm, dnx, and dnu utilities with a single tool that handles the responsibilities of these tools. In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different. As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their ASP.NET Core 1.0 RC2 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET Core 1.0 RC2 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 1.0 RC2 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET Core 1.0 RC2 Hosting can be viewed here http://hostforlife.eu



HostForLIFE.eu supports ASP.NET State Server Service for session :: Moving Session Out-of-Process with StateServer

clock June 2, 2016 20:47 by author Peter

Recently suddenly met a problem with the ASP.NET SessionState. It isn’t a fault of the SessionState itself, but likely a problem with my configuration or uses. Essentially the state was being reset too often. Although I had a timeout value of 1440 minutes, users were getting kicked out after 10-15 minutes. I eventually found out that (for some reason) the IIS worker process was being reset (although it wasn’t configured to self-reset), probably due to an unrecoverable  error in a number of our legacy-based code. And since our SessionState was set to InProc, all of the session data was stored in-the-process and was thus lost whenever it died.

I started researching the alternatives and discovered the proper way to configure the StateServer that comes with ASP.NET to move your sessions out-of-process. This way, you'll literally reset IIS (or if the StateServer is on another machine, reboot your IIS server machine) while not losing session. This seemed like a very appealing situation, and one that many people online endorse as best practice. Another benefit of moving the SessionState out-of-process is that you set yourself up nicely for eventually moving to multiple web servers, or even running simultaneous multiple instances of your application pools on the same machine to spice up performance.

Let’s start from the top. The SessionState is a collection of data that is persisted across multiple web requests to ASP.NET. This can be authentication information, a shopping cart, a theme, or whatnot – essentially any information that you want the server to remember for the next time the user “does something” on your site. This can also be accomplished on the page level with ViewState, but that sends more data back and forth between the client and your server.

If you’re using the cookie method of “tagging” your SessionState (which you should, because cookieless is vulnerable to session hijacking), you’ll have a tiny little harmless cookie called ASP.NET_SessionId which contains a unique session ID that looks something like “okeiohntcofecw55svocxwiz”. This ID is sent to the web server to let the server know which session to retrieve.

If the SessionState is running InProc, all ASP.NET has to do is look at the memory it has of that session information and retrieve or set the values required. However, if that process gets reset (due to an IIS reset, power outage, reboot, failed process, etc) then it no longer has a record of that session information, so that SessionId is no longer valid and the user is “kicked off”.

Additionally, if you increase the number of worker processes per application pool, thinking you’ll be getting better performance on a multiprocessor server, you’ll find that the users continually get kicked off, because each process doesn’t know about the session state of the other so they continually reset the session on each other. This is the same problem you’ll encounter if you try to move to two load-balanced web servers.

The StateServer Solution
Included with .NET is a Windows service called the ASP.NET State Service. This is disabled by default, so if you’re reading this far you may not know about it. This service runs as an additional process so that if the IIS worker process gets reset, the state service is still running with all the session information.

You can even run this State Service on another Windows Server machine. This way, you can have one machine managing your session state, while you can have one or more web servers handling requests. An example situation might look something like this:

(I was trying to find a shape to use for the StateServer to differentiate it from the others… and I chose the “eCommerce Server” shape. As in cash = cache… get it?)

Even though that might be what a more advanced operation might look like, you will likely (such as in development or for a small-load web server) run the StateServer on the same machine as IIS.

Keep in mind that the SessionState is still being stored in memory with the StateServer solution… there’s no persisting of the state to disk. So if the StateServer process gets restarted or rebooted, so does your session information.

The SQL Server Solution
Another solution supported natively by ASP.NET is to use SQL Server to persist state information to disk. This way, even the server handling your state can be rebooted without losing session. This may be the preferred way of doing things for very high-end operations or situations where you need to maintain that information for security or contractual purposes. However, I will not be discussing that here, because I haven’t tried it myself. There’s many resources to learn about this on the web, such as this article from Microsoft.

Enabling StateServer
To enable the ASP.NET State Service, all you have to do is configure the service on both your development and production machines.
Click Start / Run or type Win + R.

  1.     Type in services.msc and press Enter or click OK.
  2.     Locate the ASP.NET State Service in the Services (local) list.
  3.     Right click on it and choose Properties.
  4.     Change the Startup Type to Automatic so that it starts on boot.
  5.     Click the Start button to get it started now.
  6.     Click OK to close the dialog.

Now, if you pull up Task Manager, you’ll notice a nice little aspnet_state.exe process running in addition to the IIS worker process (w3wp.exe). This process is the new StateServer that will maintain all your state data. But in order to use it, we must enable your ASP.NET web site to use the out-of-process StateServer.
Modifying your Web.Config

For the site that you’d like to have use the out-of-process StateServer, first open your web.config file for that site.

Locate (or add) a sessionState element in the system.web section of the config file, like this:

Note the cookieless=”UseCookies” and mode=”StateServer” attributes. These are required to use the StateServer in a cookie’d fashion.

The timeout attribute is the time, in minutes, that you want the session to remain valid.

Also note that this example above is for the StateServer running on the same machine as IIS. With no connection string specified, it looks for a StateServer running on the local machine. If you need to move the StateServer onto another machine, you must match up your MachineKeys and set a StateServer connection string for IIS to connect to. Google is your friend.

Now, your site should be using the StateServer for all of its session data. You may (or may not, but it might be a good idea) need to restart IIS for this to be optimally configured.

Non-Serializable Session Data
The only caveat in this post, and it’s a big one, is that you will receive an error if you try to store non-Serializable data into the session now that you have an out-of-process state (i.e. a System.Data.DataView). Serializable classes are those that have the Serializable attribute set and are optimized for serialization (i.e. a System.Data.DataTable).

You will need to review and test your code (or write new code accordingly) to make sure that you are not storing non-Serializable data to your session when using out-of-process state. If you are using custom classes to store session data, review them for serializable members and properties, and then mark them as serializable.

Final Thoughts
I’ve seen developers proclaim online that all ASP.NET devs should design their applications around an out-of-process session model, and now that I’ve discovered it, I am inclined to agree. If you design from the beginning to be compatible with a StateServer or SQL database state server, you can easily make the jump from one web server to two. A few things to think about are the amount of memory available to the state service, latency and the connection between servers if the StateService is running on another machine, and how to minimize state since it’s now being transferred between processes.

HostForLIFE.eu ASP.NET State Server
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 4.5 Hosting - HostForLIFE.eu :: Secure Your Website No Copy Paste

clock June 2, 2016 20:43 by author Anthony

Have you ever worked really hard on graphics for your site only to find later that someone has stolen them as their own. You can help encrypt and protect your site with the following codes. No right click block is 100% effective, but they will help against novices.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .


Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;

On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;

On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:



HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: Fixing ASP.NET 4.5 Register on Web Server

clock May 26, 2016 20:55 by author Anthony

 

NET 4.5 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5. When making an ASP.NET website throughout IIS 7.5 in Visual Studio 2008/2010, you can find the following issue:

“ASP.NET 4.5 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5 in order for your site to run correctly, Press F1 for more details”

This error usually occurs if you have installed IIS 7.x ‘after’ installing .NET. In order to resolve the error, do the following:

Step 1: Open Control Panel > Programs > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application development Feature

Check the box 'ASP.NET' . Also in the Web Management Tools, remember to select IIS 6 Management Compatibility and IIS Metabase as shown below.

Note: Make sure that you are running Visual Studio 2010 as Administrator.

Now run the site from Visual Studio 2010 using Ctrl + F5.

Step 2: If you further get the error “Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list” or Managed handler is used; however, ASP.NET is not installed or is not installed completely then do a Visual Studio 2010 repair.

Start > Programs > Accessories > Run. Type this command depending on the version of VS 2010 installed.

Silent Repair for 32-bit

%windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart


Silent Repair for 64-bit

%windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

That’s it. Restart IIS and the errors should be fixed.

Step 3: If the errors are not yet fixed, there could be an issue in the Application Pool. Follow these steps

1. Open IIS Manager (Run > Inetmgr) . Expand the server node and then click Application Pools

2. Now select the application pool that contains the application that you want to change. Go to Actions > View Applications.

3. Select the Application pool to change > In Action Pane, click on ‘Change Application Pool’

4. In the ‘Select Application Pool’ dialog box, select the application pool associated with .NET 4.0 from the Application pool list and then click OK.

 

 


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How To Make DropDown List with ASP.NET Core WEB API and AngularJS 2 ?

clock May 22, 2016 05:48 by author Anthony

In this post, we take it to next level and implement it with ASP.NET Core Web API and AngularJS 2. But starting/configuring AngularJS 2 with ASP.NET Core is not straight forward and it requires some manual configurations to be done. If you are not sure how to do it, I recommend you to read this helpful post to find out post how to start with AngularJS 2 in ASP.NET Core with TypeScript using Visual Studio 2015.

Cascading DropDown List with ASP.NET Core WEB API and AngularJS 2

I believe now you have an idea about starting with AngularJS 2. I also followed same steps to configure this demo project as mentioned. So now let’s move to next part. Please note, I selected the “Web application template” while creating the project but removed all the unnecessary code.

Add Models classes in Models folder

First, add Country and State model classes in Models folder. Following is the code for Country.cs. This class has 2 properties and a method which returns a list of countries. For demo, I used static data but you can also get the same list from database.

public class Country
{
    public int id { get; set; }
    public string name { get; set; }

    public Country(int CountryID, string CountryName)
    {
        id = CountryID;
        name = CountryName;
    }

    public static List<Country> GetAllCountries()
    {
        List<Country> lstCountries = new List<Country>();
        lstCountries.Add(new Country(1, "USA"));
        lstCountries.Add(new Country(2, "India"));
        lstCountries.Add(new Country(3, "Australia"));
        lstCountries.Add(new Country(4, "Canada"));
        return lstCountries ;
    }
}

And following is the code for State.cs. This class has 3 properties and a method which returns a list of states. Nothing fancy, self-explanatory code.

public class State
{
    public int id { get; set; }
    public int countryid { get; set; }
    public string name { get; set; }

    public State(int StateID, int CountryID, string StateName)
    {
        id = StateID;
        countryid = CountryID;
        name = StateName;
    }
    public static List<State> GetAllStates()
    {
        List<State>  lstState = new List<State>();
        lstState.Add(new State(1, 1, "Arizona"));
        lstState.Add(new State(2, 1, "Alaska"));
        lstState.Add(new State(3, 1, "Florida"));
        lstState.Add(new State(4, 1, "Hawaii"));
        lstState.Add(new State(5, 2, "Gujarat"));
        lstState.Add(new State(6, 2, "Goa"));
        lstState.Add(new State(7, 2, "Punjab"));
        lstState.Add(new State(8, 3, "Queensland"));
        lstState.Add(new State(9, 3, "South Australia"));
        lstState.Add(new State(10, 3, "Tasmania"));
        lstState.Add(new State(11, 4, "Alberta"));
        lstState.Add(new State(12, 4, "Ontario"));
        lstState.Add(new State(13, 4, "Quebec"));
        lstState.Add(new State(14, 4, "Saskatchewan"));
        return lstState;
    }
}


Add action methods in controller
Next step is to make our WEB API ready. For your information, ASP.NET Core comes with Unified Programming Model for MVC and Web API. So open HomeController.cs and add following 2 action methods.

[HttpGet]
[Route("api/Home/GetCountries")]
public IEnumerable<Country> GetCountries()
{
    return Country.GetAllCountries();
}

[HttpGet]
[Route("api/Home/GetState/{countryid?}")]
public IEnumerable<State> GetState(int countryid = 1)
{
    List<State> lstState = State.GetAllStates();
    return lstState.Where(item => item.countryid == countryid);
}
GetCountries() method makes call to Country.GetAllCountries(); and returns the list. Where the second method GetState() accepts countryid as parameters and based on the its value, filters the state list and return the same.

Note countryid parameter is optional for GetState() action method. And also a default value is supplied to it. Why? Well, this actually allows you to pass countryid in querystring. And while calling REST APIs via AngularJS, the arguments/parameters are appended to URL as part of querystring. And that’s why we must allow our API to support querystring. So following URL,

http://localhost:53483/api/Home/GetState/1
is similar to
http://localhost:53483/api/Home/GetState?countryid=1

AngularJS 2 application structure
Create a folder named “app” in wwwroot folder. If you have already created while configuring AngularJS 2 then ignore this step. Now within this folder, following files needs to added.

I already explained about this application structure and about code here. But let me just summarize here again.

country.ts: This file has a simple class called Country with 2 properties id and name.
state.ts: This file has a simple class called States with 3 properties id, countryid and name.
countrylistcomponent.ts: This file contains code for defining a component and template used to render HTML. The Component adds the metadata to the class. And it also makes call to Angular 2 Service, which in turn calls WEB API.
CountryTemplate.html: This file has HTML code to render select dropdown list.
dataservice.ts: This is an Angular 2 service which makes WEB API calls to get list of countries and states.
main.ts: This file contains code to bootstrap angularjs 2 in our application.
country.cs

export class Country {
    constructor(public id: number, public name: string) { }
}
state.cs

export class State {
    constructor(public id: number,
                public countryid: number,
                public name: string) { }
}
dataservice.ts

import { Injectable } from 'angular2/core';
import {Http, URLSearchParams} from "angular2/http";
import 'rxjs/Rx';
import { Country } from './country';
import { State } from './state';


@Injectable()
export class DataService {
    constructor(public http: Http) {
        this.http = http;
    }
    getCountries() {
        return this.http.get("/api/Home/GetCountries")
            .map((responseData) => responseData.json());
    }

    getStates(countryid: string) {
        var params = new URLSearchParams();
        params.set('countryid', countryid);
        return this.http.get("/api/Home/GetState", { search: params })
            .map((responseData) => responseData.json());
    }
}

As you know AngularJS 2 is modular. And as here in this service, we need to make use of HTTP service. So we need to import it. Similarly URLSearchParams, which is used to pass arguments to WEB API method. Therefore,
import {Http, URLSearchParams} from "angular2/http";

And the other import statement import 'rxjs/Rx';, imports ReactiveX library. The Http service in Angular 1 returns a promise where Angular 2 returns an Observable object. And The Observable classes in Angular 2 are provided by the ReactiveX library.

Here, first we inject $http service in class constructor. And we use http.get() to run our HTTP request. And this returns an Observable object. Since it’s an observable object, we can use map() to convert the response into JSON response.

countrylistcomponent.ts

import { Component } from 'angular2/core';
import { DataService } from './dataservice';
import { Country } from './country';
import { State } from './state';

@Component({
    selector: 'my-country-list',
    templateUrl: 'app/CountryTemplate.html',
    providers: [DataService]
})
export class CountryListComponent {
    selectedCountry: Country = new Country(0, 'India');
    countries: Country[];
    states: State[];

    constructor(private _dataService: DataService) {
        this._dataService.getCountries().subscribe(data => { this.countries = data });
    }

    onSelect(countryid) {
        if (countryid == 0)
            this.states = null;
        else
            this._dataService.getStates(countryid).subscribe(data => { this.states = data });
    }
}
This file is modified to use the service to get countries and states list.

First, import the Service and then within @Component directive, set providers: [DataService].
And inject the service in CountryListComponent constructor. And in constructor, call getCountries() method to get list of countries from the service. Since the service returns Observable object, we can use .subscribe() method to get the output in variable.
Also defined onSelect method which will be called onChange event of country dropdown list. This method calls service to get the list of states based on selected countryid and then using subscribe get the list in states variable.
main.ts

import { bootstrap } from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from "angular2/http";
import { CountryListComponent } from './countrylistcomponent';

bootstrap(CountryListComponent, [HTTP_PROVIDERS]);
This file has code to bootstrap AngularJS 2 in our application. Along with that, it also bootstrap application root/parent component. Angular’s http module exposes HTTP_PROVIDERS, which has all the providers that we need, to code http action in our service. Therefore add the http providers to the bootstrap, by importing the HTTP_PROVIDERS from angular2/http.

CountryTemplate.html

<div class="row">
    <div class="col-md-5" style="text-align:right;">
        <label>Country:</label>
    </div>
    <div class="col-md-7" style="text-align:left;">
        <select [(ngModel)]="selectedCountry.id" (change)="onSelect($event.target.value)" style="width:150px;">
            <option value="0">--Select--</option>
            <option *ngFor="let country of countries" value={{country.id}}>{{country.name}}</option>
        </select>
    </div>
</div>
<br />
<div class="row">
    <div class="col-md-5" style="text-align:right;">
        <label>State:</label>
    </div>
    <div class="col-md-7" style="text-align:left;">
        <select style="width:150px;">
            <option value="0">--Select--</option>
            <option *ngFor="let state of states " value={{state.id}}>{{state.name}}</option>
        </select>
    </div>
</div>
And finally the HTML template. This file name is used while specifying metadata for CountryListComponent class.
There are 2 dropdowns list one for country and other for state and also change event defined on country dropdown list. Angular 2 has different way of defining event. Take the HTML event and wrap it with parentheses. $event.target.value will give the selected country id.

I also want to bring in your attention a change made in AngularJS 2 version “2.0.0-beta.17” with respect to *ngFor. Previously we were using,

*ngFor="#state of states"
but in this version, it is changed a bit. Instead of “#”, use “let”

*ngFor="let state of states"
And finally since we are using Angular 2 Http service in our application, we need to include the script in the layout. So, open the _Layout.cshtml file located at Views/Shared/ and add the following code right after the script element that loads Angular 2 core.

<environment names="Development">
  <script src="~/lib/npmlibs/angular2/http.dev.js"></script>
</environment>
<environment names="Staging,Production">
  <script src="~/lib/npmlibs/angular2/http.min.js"></script>
</environment>
Wait!!! We still need to show what we have done till now on UI. So open Views/Home/Index.cshtml and add angular component tag <my-country-list></my-country-list> to HTML file. And we also need to load the application and all its modules. So place following script section to the end of the file.

@section Scripts {
    <script>
        System.config({
            packages: {
                'app': { defaultExtension: 'js' },
                'lib': { defaultExtension: 'js' },
            },
        });

        System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
}

 

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How To Inject Codes in HTTP Pipeline?

clock May 12, 2016 21:49 by author Anthony

In this tutorial, I will explain about how to inject little codes in HTTP Pipeline in ASP.NET Core. “Middleware is defined in the OWIN specification as pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose. Middleware consists of application components are incorporated into the ASP.NET HTTP pipeline.” The text is in the ASP.NET Core documentation, and as can be seen, with middleware we can insert a component that is incorporated in ASP.NET HTTP pipeline, that is, we can develop a code with a purpose to manipulate the requests and responses.

A characteristic of middleware is that normally there will a chain of middleware whereby order of configuration, one is called after the end of other and the current middleware can on any moment cancel invoking the next middleware, thus all chains of middleware will be canceled.

middlwares

Do you have doubts about what is middlewares? We can compare middleware with the old http modules that today don’t exist in the new ASP.NET. I have already seen somebody comparing middlewares with a hamburger, because the middle is middleware and the ends are the application and the server. How much more middleware, bigger is the hamburger.

To get more clarity about the subject, I am going to show some middlewares that already are utilized by default in application templates to ASP.NET Core, and after I am going to create a custom middleware.

Below I show the startup class, note that there are some comments that indicate where there is a middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink(); //Middleware
                app.UseDeveloperExceptionPage(); //Middleware
                app.UseDatabaseErrorPage(); //Middleware
            }
            else
            {
                app.UseExceptionHandler("/Home/Error"); //Middleware

                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); //Middleware

            app.UseApplicationInsightsExceptionTelemetry(); //Middleware

            app.UseStaticFiles(); //Middleware

            app.UseIdentity(); //Middleware

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            }); //Middleware
        }

Did you see the middlewares utilized in code? Here, each middleware has a responsibility and the gain that we have is we can choose only the ones needed for our project, different from old version of ASP.NET that by default many features were added even when they were not necessary. A very good phrase says: “Pay only by what you use”, in other words, how many fewer middleware you use, the less heavy will be the HTPP pipeline.

Other thing to observe that in code above, all the middlewares start with a “Use”, this is a pattern done by team ASP.NET.

Now I am going to create a own middleware and my goal will be creating one that shows the total time of application to take care of a request. Below following the code.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace MiddlewareArticle.Middleware
{
    public class ResponseTime
    {
        RequestDelegate _next;

        public ResponseTime(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var sw = new Stopwatch();
            sw.Start();

            await _next(context);

            var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");

            if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
            {
                var body = context.Response.Body;
               
                using (var streamWriter = new StreamWriter(body))
                {
                    var textHtml = string.Format(
                        "<footer><div id='process'>Response Time {0} milliseconds.</div>",
                        sw.ElapsedMilliseconds);
                    streamWriter.Write(textHtml);
                }
            }
        }
    }
}


As can be seen, making a middleware is not difficult, it needs a constructor to receive the next middleware and an “Invoke” method that receives the context of HTTP. The goal of showing the total time of application gets in method Invoke. Before calling the next middleware, it is started the time and after of calling the next middleware, when all the middlewares already were executed, I execute the code to show in the HTML the total time.

Remember, I know that all middleware were executed because our middleware must be configured before of all others, thus the code will wait all executions and after the instruction “await _next(context);” we can write our code.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseMiddleware<ResponseTime>(); //Our Middleware
           
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
           
            //...
            //Continue with others codes

The code above is only to show the set up of our middleware in the Configure method of the Startup class. To that this works, it is needed using the instruction “app.UseMiddleware();”, where the UseMiddleware method is used to call custom middlewares.

Conclusion


The ASP.NET Core has changed, not the code that we know, but your core and by this, the way of manipulating a request and a response was changed to middleware. Now it’s lighter and easier to stay between an application and a server. However, take care, it is not because it got better that you must now only use that to develop.

 

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 5 Hosting - HostForLIFE.eu :: Json Files Configuration

clock April 29, 2016 23:12 by author Anthony

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use standard JavaScript functions to convert JSON data into native JavaScript objects.

Much Like XML Because

  • Both JSON and XML is "self describing" (human readable)
  • Both JSON and XML is hierarchical (values within values)
  • Both JSON and XML can be parsed and used by lots of programming languages
  • Both JSON and XML can be fetched with an XMLHttpRequest

Much Unlike XML Because

  • JSON doesn't use end tag
  • JSON is shorter
  • JSON is quicker to read and write
  • JSON can use arrays

The biggest difference is:

XML has to be parsed with an XML parser, JSON can be parsed by a standard JavaScript function.

Visual Studio 2015 with ASP.NET 5 is a sweet surprise for developers. ASP.NET 5 has various JSON files to play with. These files handles global settings for solution, project specific settings, client side packages and node modules packages. In the post, we will take a close look at every JSON file and its code.

Solution Explorer in ASPNET 5 RC1


As seen from the above image, there are mainly 6 configuration json files.

  • Global.json
  • appsetting.json
  • Project.json
  • launchsetting.json
  • bower.json
  • package.json
  • hosting.json: Though this file is not present in solution explorer till RC 1 release but you can add it manually.


Global.json

As the name suggests, the settings defined in the file should work for the solution as whole. The settings defined in global.json implies to all the projects in the solution. If you open the file, by default you will see the following code.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The projects property defines the locations of your solution’s source code. VS 2015, specifies two location for projects in the solution src and test. While the src contains the actual application and test project contains any test (if you have selected option of creating test project while creating the solution for first time].

The team has also made a very interesting and useful change. If you recollect, when you build your application, then all your .dll are placed in bin directory in the same path, where your project is. And we have to handle bin folder very carefully while check-in the code in source control and at the time of deployment. But good news is that it is moved to another location. So you don’t have to worry now. The build artifact is now placed in “Artifact” folder (at the same location), which makes life easy while excluding things from source control.

Artifact folder

And the second property sdk specifies the version of the DNX (.Net Execution Environment) that Visual Studio will use when opening the solution. Specifying the version has an advantage as while working on multiple projects, you can target different versions of ASP.NET 5.

appsettings.json

appsettings.json file is used to define application related settings like connection string, logging settings, or any other custom key which we used to define in web.config file.

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-FirstApp-0ed2f710-6535-4c4e-b080-c26601fbb414;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}


Project.json

This file is used to define project settings and server side dependencies. It largely replaces the web.config file from previous versions of ASP.NET. Read “What is Project.json in ASP.NET 5 (vNext)”. Few things have changed in ASP.NET 5 RC1 release for project.json file.

launchSetting.json

This json file holds project specific settings associated with each profile Visual Studio is configured to use to launch the application, including any environment variables that should be used. You can define framework for your project for compliation and debugging for specific profiles.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:2137/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "Hosting:Environment": "Development"
      },
      "sdkVersion": "dnx-clr-win-x86.1.0.0-rc1-update1"
    },
    "kestrel": {
      "commandName": "kestrel",
      "sdkVersion": "dnx-clr-win-x86.1.0.0-rc1-update1"
    }
  }
}


ASP.NET 5 ships with support for 3 different servers:

  • Microsoft.AspNet.Server.IIS
  • Microsoft.AspNet.Server.WebListener (WebListener)
  • Microsoft.AspNet.Server.Kestrel (Kestrel)

So by default, there will be 3 different profiles. However, it also depends on the commands section of project.json. You can change settings for each profile via right click on the Project and then select properties. Read detailed post about launchsetting.json in ASP.NET 5

change launchsetting.json settings

Bower.json

Bower is a package manager for the web. Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else – it just installs the right versions of the packages you need and their dependencies. With ASP.NET 5 web projects jQuery and bootstrap packages are already installed and bower, gulp and NPM are already in place.
Client-side packages are listed in the bower.json file. As mentioned earlier, bootstrap, jQuery and jQuery validation are pre-configured with ASP.NET 5 project templates.

{
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.5",
    "jquery": "2.1.4",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.4"
  }
}


Visual Studio watches the bower.json file for changes. Upon saving, the bower install command is executed. There is another file named “ .bowerrc” which defines the location at which bower package needs to be installed. Open it, and notice that the directory property is set to “wwwroot/lib”.

Package.json

npm is another package manager like bower. But npm is used for installing Node js modules where bower is used for managing front end components like html, css, js, etc. As mentioned earlier, the ASP.NET 5 project template pre-configures NPM, Gulp and bower. Gulp is JavaScript task runner which is used to automate various tasks like minification and bundling of js and css, checking errors in js etc… Since Gulp is a node.js module so npm is used. So node.js modules are listed in package.json.\

{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

You can see the installed bower and npm modules by expanding src -> dependencies option.

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Handle Error 404?

clock April 22, 2016 23:19 by author Anthony

404 is a frequently-seen status code that tells a Web user that a requested page is "Not found." 404 and other status codes are part of the Web's Hypertext Transfer Protocol ( HTTP ), written in 1992 by the Web's inventor, Tim Berners-Lee. He took many of the status codes from the earlier Internet protocol for transferring files, the File Transfer Protocol ( FTP .)

What to Do If You Get a 404

If the site no longer exists, there's nothing you can do. However, it only takes one mistyped character to result in a 404. See whether the ".htm" should be an ".html" or vice versa. If you're linking from a Web site, you can do a "View source" to make sure it wasn't miscoded. Whether or not it is, you may want to send a note to the Webmaster so that the link can be fixed for the next users.

In this tutorial, I will show you how to handle 404 error in ASP.NET Core 1.0. Prior versions of ASP.NET Core 1.0, have custom errors for error handling. With ASP.NET Core 1.0 and MVC, you can do the error handling via Middlwares. HTTP 404 is a very common error which comes when server can’t find the requested resource. In this post, we will see different ways to handle HTTP 404 error in ASP.NET Core 1.0 and MVC.

How to handle 404 error in ASP.NET Core 1.0


I found 2 ways to handle 404 error. In fact using these solution you can handle any HTTP status code errors. To handle the error, both the solution are using configure() method of Startup.cs class. For those who are not aware about Startup.cs, it is entry point for application itself. You can read this excellent post The Startup.cs File in ASP.NET Core 1.0. to know more about startup.cs. And within the startup.cs file, you will also find static void main() which generally you use with windows/console applications. Read my post Why static void main in ASP.NET 5 startup.cs

Now coming back to our solution 1, within configure method define a custom middleware via app.Use which checks for status code value in response object. And if is 404 then it redirects to Home controller.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
 
    app.UseApplicationInsightsRequestTelemetry();
    app.Use(async (context, next) =>
    {
        await next();
        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/Home";
            await next();
        }
    });
 
    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();
    // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Solution 2

The other solution is to use a built-in middlware StatusCodePagesMiddleware. This middleware can be used to handle the response status code is between 400 and 600. This middleware allows to return a generic error response or allows you to also redirect to another middle. See below all different variations of this middleware.

app.UseStatusCodePages();
 
// app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
// app.UseStatusCodePages("text/plain", "Response, status code: {0}");
// app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
// app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
// app.UseStatusCodePages(builder => builder.UseWelcomePage());
// app.UseStatusCodePagesWithReExecute("/errors/{0}");

Now to handle the 404 error, we shall use app.UseStatusCodePagesWithReExecute which accepts a path where you wish to redirect.

app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");

So we are redirecting here to Home Controller and Errors action method. The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.

public IActionResult Errors(string errCode)
{
    ViewData["ErrorID"] = "The following error " + errCode + " occured";
    return View("~/Views/Shared/Error.cshtml");
}

It adds the status code in ViewData and then returns to Error.cshtml shared view. You can also return to specific error page based on the error code.

public IActionResult Errors(string errCode)
{
  if (errCode == "500" | errCode == "404")
  {
    return View($"~/Views/Home/Error/{errCode}.cshtml");
  }
 
  return View("~/Views/Shared/Error.cshtml");
}

So, if the error code is 500 or 404 then return to Home/Error/500.cshtml or 404.cshtml.

You must have seen on many websites, forums about app.UseErrorPage(); to handle the errors. But this is no longer available with RC1 release of ASP.NET Core 1.0. This was available until beta 5 or 6.


HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Check Record Availability using JOSN and jQuery?

clock April 20, 2016 00:10 by author Peter

In this tutorial, I will show you how to Check Record Availability using JOSN and jQuery. I will check user name available or not a table without refreshing the page using JOSN in ASP.NET. The followind code will explains how to check the user name that end user is entering already exist in database or not if it exist then message will show. In this entire process page is not refreshing.


I am using JOSN and Ajax as in the following example:   

<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>  
    <script type = "text/javascript"> 
    function ShowAvailability() { 
        $.ajax({ 
            type: "POST", 
            url: "CheckUserAvalibleusingJOSN.aspx/CheckUserName", 
            data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: OnSuccess, 
            failure: function (response) { 
                alert(response); 
            } 
        }); 
    } 
     
    function OnSuccess(response) { 
        var mesg = $("#mesg")[0]; 
        switch (response.d) { 
            case "true": 
            mesg.style.color = "green"; 
            mesg.innerHTML = "Available"; 
            break; 
            case "false": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Not Available"; 
            break; 
            case "error": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Error occured"; 
            break; 
        } 
    } 
     
    function OnChange(txt) { 
        $("#mesg")[0].innerHTML = ""; 
        ShowAvailability();//hide this function from here if we want to check avability by using button click 
    } 
    </script> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div > 
            UserName : <asp:TextBox ID="txtUserName" runat="server" onkeyup = "OnChange(this)"></asp:TextBox> 
            <%--<input id="btnCheck" type="button" value="Show Availability" onclick = "ShowAvailability()" />--%> 
            <br /> 
            <span id = "mesg"></span> 
            </div> 
        </form> 
    </body>


Code

    [System.Web.Services.WebMethod] 
    public static string CheckUserName(string userName) 
    { 
        string returnValue = string.Empty; 
        try 
        { 
            string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
            SqlConnection conn = new SqlConnection(consString); 
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
            conn.Open(); 
            returnValue = cmd.ExecuteScalar().ToString(); 
            conn.Close(); 
        } 
        catch 
        { 
            returnValue = "error"; 
        } 
        return returnValue; 
    }


SQL Query

    USE [manish_db] 
    GO 
    /****** Object: StoredProcedure [dbo].[spx_CheckUserAvailability] Script Date: 07/19/2014 02:17:13 ******/ 
    SET ANSI_NULLS ON 
    GO 
    SET QUOTED_IDENTIFIER ON 
    GO 
    ALTER PROCEDURE [dbo].[spx_CheckUserAvailability] 
    @UserName VARCHAR(50) 
    AS 
    BEGIN 
    SET NOCOUNT ON; 
    IF NOT EXISTS 
    (SELECT UserName FROM dbo.UserDetails 
    WHERE UserName = @UserName 
    ) 
    SELECT 'true' 
    ELSE 
    SELECT 'false' 
    END

Note: If we use web services just add webservices and replace the page path with *.asmx file path.

Code

    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class CheckUserAvalible : System.Web.Services.WebService 
    { 
        [WebMethod] 
        public string CheckUserName(string userName) 
        { 
            string returnValue = string.Empty; 
            try 
            { 
                string consString = ConfigurationManager.ConnectionStrings["manish_dbCS"].ConnectionString; 
                SqlConnection conn = new SqlConnection(consString); 
                SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn); 
                cmd.CommandType = CommandType.StoredProcedure; 
                cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
                conn.Open(); 
                returnValue = cmd.ExecuteScalar().ToString(); 
                conn.Close(); 
            } 
            catch 
            { 
                returnValue = "error"; 
            } 
            return returnValue; 
        } 
    }


I Hope it works for you! Happy coding.

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to Make CAPTCHA?

clock April 15, 2016 21:42 by author Anthony

A CAPTCHA (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart") is a type of challenge-response test used in computing to determine whether or not the user is human. The term was coined in 2003 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford.

The technology is used mostly to block spammers and bots that try to automatically harvest email addresses or try to automatically sign up for or make use of Web sites, blogs or forums. CAPTCHA, whose users include Yahoo and Google, blocks automated systems, which can't read the distorted letters in the graphic.

The algorithm for CAPTCHA is public, as the "P" in the name implies. The test was developed in various forms around 1996, but it got its distinctive name in 2000 from researchers at Carnegie Mellon University and IBM. Cracking the algorithm won't make the CAPTCHA vulnerable, since the algorithm is only used for generating the random series of letters and numbers in the image. The system works because humans and computers process strings of characters differently.

One of the problems with CAPTCHA is that sometimes the characters are so distorted that they can't even be recognized by people with good vision, let alone visually handicapped individuals. Depending on local regulations for handicapped access to Web sites, this can also be a compliance issue for some Web-based businesses.

CAPTCHA technology is easy to implement, but requires some knowledge of hypertext preprocessor (PHP) or other Web scripting languages. For more information and links to extensive resources, check the How to use CAPTCHA Web site and The CAPTCHA Project. Both sites also have examples of CAPTCHAs and in-depth tutorials on how to develop and implement CAPTCHA for your Web site.

So, in this article, I will explain how to make basic CAPTCHA.

You can set the height and width of the CAPTCHA image while initializing the CAPTCHA class. The CAPTCHA image generated from the class can be set to the image control directly or it can be save to the local path and then set to the image control. For this example I am saving it to the local path and then set to the image control. And the CAPTCHA image code generated by the class is automatically set to the session variable named CaptchaCode.

Time to get some hand on it

On the page get an image control to display CAPTCHA image, a textbox where user will enter the CAPTCHA text and a button when clicked, we can check and validate if the code entered is correct or not. Plug the DLL in your ASP.NET project and go to the Page_Load event. Here we will generate the image of the height and width we wish to have for out CAPTCHA image and then save the image to the CaptchaImages folder with the random image code generated. The code on the Page_Load event goes like this:
protected void Page_Load(object sender, EventArgs e)
{
        if (!Page.IsPostBack)
        {
            CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 140, 40);
            cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg);
            CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg";
            cImage.Dispose();
        }
        CaptchaCode = Convert.ToString(Session["CaptchaCode"]);
}

Before you can use the above code, declare a public variable which I have used to hold the value of the CAPTCHA code. I named it CaptchaCode. You can name it whatever you like it. We will be using this variable later to check it against the user input. Hit F5 to start and test your application. If everything is in place and you will be able to see the below output.

To check if the user enters the correct CAPTCHA code, we must have an event on button click which will validate the user input and prompt the user if CAPTCHA code is correct or incorrect. The code on the button click is:

protected void btn_Validate(object sender, EventArgs e)
{
        if (CaptchaCode == txt_ccode.Text)
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered Correct CAPTCHA Code!');</script>");
        }
        else
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered INCORRECT CAPTCHA Code!');</script>");
        }
}

The above code will check the CAPTCHA code entered by the user and check against the CAPTCHA code we previously saved in the session variable (CaptchaCode). If the validation is a success, user will get the message notifying him that he enters correct CAPTCHA code or the error message otherwise.

And that's it, we have successfully implement a CAPTCHA in our ASP.NET application. So, here are few things we can do with this CAPTCHA library:

Set image height and width.
Saves the image to the local path.
Automatically sets the generated CAPTCHA code to the application session.

 


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in