ASP.NET 4.5 Hosting BLOG

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

FREE ASP.NET Hosting with ASPHostPortal.com :: How to Fix ASP.NET 4.0 has not been Registered on the Web Server Error

clock May 6, 2015 06:54 by author Dan

When making an ASP.NET website throughout IIS 7 in Visual Studio 2008/2010, you can find the following issue:

“ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 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.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Free ASP.NET Hosting with ASPHostPortal.com :: How to Using Facebook Graph API With ASP.NET MVC

clock April 20, 2015 05:52 by author Mark

This article series covers the use of the Facebook Graph API integration with an ASP.NET MVC web applications to learn how to incorporate Facebook features server-side.In this article series we will learn how to implement custom social media integration into our ASP NET web application using the Facebook SDK.
Here we will see in practical terms how to access and update Facebook data utilizing the Graph API.
Before we proceed let's see the few terms.

  • OAuth 2.0: Open standard for authorization

Provides secure delegate access specifically from Facebook as an OAuth provider. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials.

  • OWIN: Open Web Interface for .NET
  • Defines a standard interface between .NET web servers and web applications.
  • User Access Token: Encodes an App Id + User Id + Permissions
  • AppSecret_Proof: Encrypted Hash of the Access Token using App Secret key

So let's get started learning about Facebook Graph API integration.

Step 1: Open https://developers.facebook.com/ then click on My Apps and then add a new App as shown below.

Step 2: Select website and provide the Display name and namespace as shown below.
Here namespace is an alternative way to identify our application so don't confuse it with namespaces in C#.

Step 3: Click on settings and then click on Add Platform.

Step 4: Select website and we will get a couple of options as shown below.

Step 5: Now Let's create a test app which is best practice.

Summary

In this article we learn how to create a Facebook App. In the next article we will see how to authenticate with ASP.NET MVC applications.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



Free ASP.NET Hosting with ASPHostPortal.com :: State Management in ASP.NET

clock April 15, 2015 05:53 by author Mark

State Management in ASP.NET

  • A new instance of the Web page class is created each time the page is posted to the server.
  • In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip.
  • The Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can be broadly divided into the following two categories:
    • Client-Side State Management Options
    • Server-Side State Management Options

Client-Side State Management

  • Client-based options involve storing information either in the page or on the client computer.
  • Some client-based state management options are:
    • Hidden fields
    • View state
    • Cookies
    • Query strings

Hidden Fields

  • A hidden field is a control similar to a TextBox control.
  • A hidden field does not render in a Web browser. A user cannot type anything into it.
  • Hidden fields can be used to store information that needs to be submitted along with the web page, but should not be displayed on the page.
  • Hidden fields can also be used to pass session information to and from forms, transparently.

To pass the information from one page to another, you can invoke the Server.Transfer method on the Click event of a Button control, as shown in the following example: 

protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("Page2.aspx");
    }

  • The target page can access the passed information by referring to individual controls on the source page, as shown in the following example: 

     String name = Request.Form["TextBox1"];
   String color = Request.Form["HiddenField1"];

View State

  • Each Web page and controls on the page have a property called ViewState.
  • This property is used to automatically save the values of the Web page and each control on the Web page prior to rendering the page.
  • The view state is implemented using a hidden form field called _VIEWSTATE.
  • This hidden form field is automatically created in every Web page.
  • When ASP.NET executes a Web page on the Web server, the values stored in the ViewState property of the page and controls on it are collected and formatted into a single encoded string.
  • The encoded string is:    
    • Assigned to the Value attribute of the hidden form field, _VIEWSTATE.
    • Sent to the client as part of the Web page.       
    • During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore the values in _VIEWSTATE.

Enabling and disabling view state

  • By default, the view state is enabled for a Web page and the controls on the Web page.
  • You can enable or disable view state for a page by setting the EnableViewState property of a Web page, as shown in the following example: 

<%@ Page Language="C#"AutoEventWireup="true"EnableViewState="false"CodeFile="Page1.aspx.cs"Inherits="Page1" %> 

  • You can enable or disable view state for a control by setting its EnableViewState property to false.
  • When view state is disabled for a page, the view state for the controls on the page is automatically disabled.

Cookies

  • Cookies
    • Cookies are: 
    • Used to store small pieces of information related to a user's computer such as its IP address, browser type, operating system, and Web pages last visited.
    • Sent to a client computer along with the page output.      

Types of cookies 

  • Temporary Cookies     
  • Exist in the memory space of a browser.
  • Also known as session cookies.
  • Are useful for storing information required for only a short time.         

Persistent Cookies     

  • Are saved as a text file in the file system of the client computer.
  • Are used when you want to store information for a longer period.
  • Are useful for storing information required for only a short time.      
  • Creating Cookies 

     Response.Cookies["userName"].Value = "Peter";
    Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
    Reading Cookies

  • You can access the value of a cookie using the Request built-in object.   

    if (Request.Cookies["userName"].Value != null)
    {
        Label1.Text = Request.Cookies["userName"].Value;
    }

Query String

  • A query string: 
  • Provides a simple way to pass information from one page to another.
  • Is the part of a URL that appears after the question mark (?) character.    
  • You can pass data from one page to another page in the form of a query string using the Response.Redirect method, as shown in the following example:

Response.Redirect("BooksInfo.aspx?Category=fiction&Publisher=Sams");

Server-Side State Management

There are situations where you need to store the state information on the server side.
Server-side state management enables you to manage application-related and session-related information on the server.
ASP.NET provides the following options to manage state at the server side:

  • Application state
  • Session state
  • Application State

ASP.NET provides application state as a means of storing application-specific information such as objects and variables.
The following describes the information in the application state:

  • Is stored in a key-value pair.
  • Is used to maintain data consistency between server round trips and among pages.     
  • Application state is created the first time a user accesses any URL resource in an application.
  • After an application state is created, the application-specific information is stored in it. 

Storing and Reading information in application state

You can add application-specific information to an application state by creating variables and objects and adding them to the application state.
For example: 

Application ["MyVariable"] = "Hello";
You can read the value of MyVariable using the following code snippet:
stringval = (string) Application["MyVariable"];
  

Removing information from application state

  • You can remove an existing object or variable, such as MyVariable from an application state using the following code snippet:

Application.Remove(["MyVariable"]);

  • You can also remove all the application state variables and objects by using the following code snippet: 

Application.RemoveAll();  

Synchronizing application state

Multiple pages within an ASP.NET web application can simultaneously access the values stored in an application state, that can result in conflicts and deadlocks.
To avoid such situations, the HttpApplicationState class provides two methods, Lock() and Unlock().
These methods allow only one thread at a time to access application state variables and objects.

Session State

  • In ASP.NET, session state is used to store session-specific information for a web application.
  • The scope of session state is limited to the current browser session.
  • Session state is structured as a key-value pair for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
  • Session state is not lost if the user revisits a Web page by using the same browser window.

However, session state can be lost in the following ways: 

  • When the user closes and restarts the browser.
  • When the user accesses the same Web page in a different browser window.
  • When the session times out because of inactivity.
  • When the Session.Abandon() method is called within the Web page code.  
  • Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID string containing American Standard Code for Information Interchange (ASCII) characters.
  • You can store objects and variables in a session state.
  • You can add a variable, MyVariable with the value HELLO in the session state using the following code snippet:  

Session["MyVariable"]="HELLO";     

  • You can retrieve the value of the variable, MyVariable, using the following code snippet:  

String val = (string)Session["MyVariable"];

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASPHostPortal.com Announces Excellent Drupal 7.34 Hosting Solution

clock April 13, 2015 13:01 by author Dan

ASPHostPortal.com was established with the goal to provide high quality hosting services for everyone. They believe that providing high quality services should come at an affordable price. For this reason we have provided exceptional plans, at the lowest and free price, for the best services possible, on their fastest nodes ever. Today, they launch Drupal 7.34 hosting with high speed, full features, and FREE.

Drupal is an open source content management platform powering millions of websites and applications. It’s built, used, and supported by an active and diverse community of people around the world. With Drupal, marketers and web developers can create and manage great web, mobile and social experiences. And they can improve and adapt quickly thanks to ongoing innovation and ideas from the Drupal community.

Drupal now presents their new version (Drupal 7.34). Drupal 7.34 was released in response to the discovery of security vulnerabilities. ASPHostPortal offers a powerful Windows hosting platform which allows for easy to manage websites, FTP, email, and etc. Our hosting is housed in a state of the art data centre which gives a totally secure data protection and Super-Quick Network Access. With a knowledgeable support team available 24 hours a day, 7 days a week, you can rest assured that your Websites and Data are Secure and Available for your management anytime. To learn more about Drupal 7.34 Hosting, please visit http://asphostportal.com/Drupal-Hosting

About ASPHostPortal.com :
ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET Hosting. ASPHostPortal.com has ability to support the latest Microsoft and ASP.NET technology, such as: such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting highly scalable solutions. ASPHostPortal.com strives to supply probably the most technologically advanced hosting solutions available to all consumers the world over. Protection, trustworthiness, and performance are on the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET

clock April 13, 2015 06:19 by author Ben

My previous article discussed about How Displaying Validation Errors with ASP.NET MVC. Now in this article, I’ve covered a brief introduction about How to Import or Upload and Display Excel File in GridView Using C# in ASP.NET. There are lots of ways for Importing data from Excel to ASP.NET using C#, and here I’m going to introduce one simple common method to import data.

First we will create a new excel sheet with some data.

So for this article 1st I'll create a new asp.net application and add the beneath code inside your web page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Excel File Upload Or Import and Display In GridView Using C# In Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload & Display" OnClick="btnUpload_Click" />
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    <br />
    </form>
</body>
</html>

Now please check the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
                if (fileExtention == ".xls" || fileExtention == ".xlsx")
                {
                    string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPath("~/ExcelSheet/" + fileName));
                   /*Read excel sheet*/
                    string excelSheetFilename = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/ExcelSheet/" + fileName) + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    OleDbConnection objcon = new OleDbConnection(excelSheetFilename);
                    string queryForExcel = "Select * from [UserDetail$];";
                    OleDbDataAdapter objda = new OleDbDataAdapter(queryForExcel, objcon);
                    DataSet objds = new DataSet();
                    objda.Fill(objds);
                    if (objds.Tables[0].Rows.Count > 0)
                    {
                        GridView1.DataSource = objds.Tables[0];
                        GridView1.DataBind();
                    }
                }
                else
                {
                    lblMessage.Text = "Please upload excel sheet.";
                }
            }
        }
    }
}

Now in above code I've very first read the file and saved inside a folder and also the I study the excel sheet and stored in dataset and bind it towards the gridview manage.

Now we will develop the folder.


Within this folder we'll upload the file as shown in code.

Now we've accomplished run the application and check the output.


Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: How Displaying Validation Errors with ASP.NET MVC

clock April 2, 2015 06:21 by author Ben

Today, I write about how Displaying Validation Errors with ASP.NET MVC. We all know how crucial it is to validate user input, but it’s equally crucial how we present validation errors for the user. Take the following type:


The e mail field needs to be optional but any address entered must be valid. If a validation error happens, it ought to replace the optional label using the error message.

Behind the scenes I’m employing Data Annotations to validate the email address, so any errors is going to be passed into the ModelState. MVC has built-in help for displaying these errors (using the ValidateMessageFor helper) so it is easy to create a wrapper around that, supplying the ‘optional’ text as a parameter.

Here’s an extension method for the HtmlHelper:

public static class ExtensionMethods
{
    public static MvcHtmlString HelpMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string helpText)
    {
        var validation = htmlHelper.ValidationMessageFor(expression);
        if (validation == null)
            return new MvcHtmlString("<span class='help-inline muted'>" + helpText + "</span>");
        else
            return validation;
    }
}

Here’s it’s usage:

<fieldset>
  <div class="control-group">
        @Html.LabelFor(x => x.EmailAddress, "Email", new { @class = "control-label" })
        <div class="controls">
            @Html.TextBoxFor(x => x.EmailAddress, new { @class = "input-xlarge", placeholder = "Enter an email address" })
            @Html.HelpMessageFor(x => x.EmailAddress, "Optional")
        </div>
    </div>
</fieldset>

Best ASP.NET MVC Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Data Annotations Validation in ASP.NET 4.5

clock March 18, 2015 06:28 by author Mark

Data Annotations Validation in ASP.NET

This article explains how to use data annotations for validation in ASP.Net 4.5. So, let's proceed with the following
The effect of a custom validation message: Required, String Length, Data Type, Range, Compare and Regular Expression.

Creating a Registration Page

Create a new project using "File" -> "New" -> "Project..." then select web "ASP.NET Web Forms Application". Name it "DataAnnotationsValidation".
seelct New ASP.NET Project then select the template Empty and select Web Forms then click OK.
Next, create the code-behind as follows, displaying the validation errors to the users in the Registration.aspx.

Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="DataAnnotationsValidation.Registration" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Employees Registration</title> 
    <link href="Content/bootstrap.min.css" rel="stylesheet" /> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div class="container"> 
            <div class="well"> 
                <h1>Data Annotations  Validation in ASP .NET 4.5 </h1> 
            </div> 
            <div class=" panel panel-default"> 
                <div class="panel-heading"> 
                    <h3 class="panel-title">Employees Registration</h3> 
                </div> 
                <div class="panel-body"> 
                    <div class="text-center"> 
                    <asp:ValidationSummary ID="validationSummary" runat="server" ShowModelStateErrors="true" DisplayMode="List" ForeColor="Red"  /> 
                    </div> 
                        <div class="col-md-8"> 
                            <div class="form-group col-lg-12"> 
                                <label>First Name</label> 
                                <asp:TextBox ID="FirstName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>Last Name</label> 
                                <asp:TextBox ID="LastName" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-12"> 
                                <label>User ID</label> 
                                <asp:TextBox ID="UserID" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password </label> 
                                <asp:TextBox ID="Password" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Password Confirm </label> 
                                <asp:TextBox ID="PasswordConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Mobile </label> 
                                <asp:TextBox ID="Mobile" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Age </label> 
                                <asp:TextBox ID="Age" runat="server" class="form-control"></asp:TextBox> 
                            </div>                             
                            <div class="form-group col-lg-6"> 
                                <label>Email </label> 
                                <asp:TextBox ID="Email" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Email Confirm </label> 
                                <asp:TextBox ID="EmailConfirm" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>DOB </label> 
                                <asp:TextBox ID="Date" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Salary </label> 
                                <asp:TextBox ID="Total" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>City </label> 
                                <asp:TextBox ID="HomeCity" runat="server" class="form-control"></asp:TextBox> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <label>Department </label> 
                                 
                                <asp:DropDownList ID="Department" runat="server" class="form-control"> 
                        <asp:ListItem Value="">Choose an Option</asp:ListItem>
                        <asp:ListItem Value="HR">HR</asp:ListItem> 
                        <asp:ListItem Value="Account">Account</asp:ListItem> 
                                    </asp:DropDownList> 
                            </div> 
                            <div class="form-group col-lg-6"> 
                                <asp:Button ID="btnsubmit" runat="server" Text="submit" /> 
                            </div> 
                        </div>                     
                </div> 
                </div> 
            </div> 
    </form> 
</body> 
</html>

Create DataAnnotationsValidation.Models for Validation
Now, do something with Models then click Add -> Class.
Applying validation attributes to the Validation class

Validation.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web;   
    //using Namespace 
    using System.ComponentModel.DataAnnotations; 
    namespace DataAnnotationsValidation.Models 
    { 
        public class Validation 
        {         
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string FirstName { get; set; }  
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string LastName { get; set; } 
            [Required] 
            [StringLength(25, MinimumLength = 3)] 
            public string UserID { get; set; } 
            [Required] 
            [DataType(DataType.Password)] 
            public string Password { get; set; } 
            [Required] 
            [Compare("Password")] 
            public string PasswordConfirm { get; set; } 
            [Required] 
            [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")] 
            public int Age { get; set; }   
            [Required]        
            [StringLength(10)] 
            public int Mobile { get; set; }           
            [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")] 
            public string Email { get; set; }     
            [Compare("Email")] 
            public string EmailConfirm { get; set; }    
            [Range(typeof(decimal), "0.00", "15000.00")] 
            public decimal Total { get; set; }   
            [Required] 
            [DataType(DataType.Date)] 
            public DateTime Date { get; set; }       
            [Required] 
            public string HomeCity { get; set; }      
            [Required] 
            public string Department { get; set; }     
        } 
    } 

Next, create the code-behind as follows.

Registration.aspx.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls;     
    //using Namespace Models 
    using System.Web.ModelBinding; 
    using DataAnnotationsValidation.Models;    
    namespace DataAnnotationsValidation 
    { 
        public partial class Registration : System.Web.UI.Page 
        { 
            protected void Page_Load(object sender, EventArgs e) 
            { 
                if (IsPostBack) 
                { 
                    Validation v = new Validation(); 
                    if (TryUpdateModel(v, new FormValueProvider(ModelBindingExecutionContext))) 
                    { 
                        ShowMessage(v.ToString());                     
                    } 
                } 
            } 
            /// <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>");
            }     
        } 
    }

Now run the page, it will look like the following to use validation to check the input.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET 5 Hosting :: How To Preventing Anonymous Access to Web Sites in ASP.NET

clock March 15, 2015 11:53 by author Mark

This article will explain you how to prevent the Anonymous Access in web applications deeply.
By default in an ASP.NET Web site, visitors can browse the site anonymously, load pages, and download the content we provide. They do not have to provide any credentials for example, by logging in to the site. For most Web sites, of course, this is just what we want. However, there are occasions, depending on the type of content we provide, when we want to force users to identify themselves before they access the content. This might be as soon as they arrive at the site, or it might be at some point such as a checkout, when they are buying goods, or just so that we can allocate forum posts this visitor makes to them like c-sharpcorner.com web portal.

Configuration Files

Most of the default configuration settings for ASP.NET web sites we create are in the web.config and machine.config files stored in the folder C\Windows\Microsoft.NET\Framework\v[version]\CONFIG\ of your PC. We can override most of these settings simply by placing a web.config file in the folders of your site or application. Visual Studio 2005 and Visual Web Developer can automatically create these files to enable debugging of pages as we build your site.
The <system.web> section of the web.config file can contain a section named <authorization> that controls access to the site and to individual subfolders with the site's virtual root. If there is no <authorization> in the local or default web.config file, the equivalent section in the configuration file for the machine, machine.config, provides the settings.

<system.web>
  ...
  <authorization>
    <allow users="*" />
  </authorization>
  ....
</system.web>

ASP.NET Authentication and Authorization

Once ASP.NET starts to process the request received from IIS, it does so using its own configuration and security settings. These are wholly contained in the machine.config file and more specifically the various web.config files in the root and subfolders of your Web site and application directories.
These are the settings the ASP.NET Web Administration Tool is specifically designed to manage.

ASP.NET Authentication Settings

The <authentication> element can appear in a web.config file in the root of your Web site or a virtual application root folder. It specifies the type of authentication ASP.NET uses, the specific settings for this authentication process and, optionally, the accounts that have access to ASP.NET resources

<system.web>
...
<authentication mode="Windows|Forms|Passport|None">
<forms name="name"
path="/"
domain="domain name"
loginUrl="url"
defaultUrl="url"
protection="All|None|Encryption|Validation"
timeout="30"
slidingExpiration="true|false"
requireSSL="true|false"
cookieless="UseCookie|UseUri|UseDeviceProfile|AutoDetect"
enableCrossAppRedirects="[true|false]">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="username" password="password"/>
</credentials>
</forms>
<passport redirectUrl="internal"/>
</authentication>
...
</system.web>

The mode attribute specifies the type of authentication process. The three types are:

  • Windows. In this mode, ASP.NET authenticates users against the list of Windows accounts and groups specified for the machine or the domain within which the machine resides. When using this type of authentication, we do not include the <forms> or <passport> elements within your <authentication> element. Windows authentication is ideal for intranet usage, where users can authenticate in IIS using their Windows logon credentials.
  • Forms. In this mode, ASP.NET stores a cookie on the user's machine that contains encoded authentication information. If this cookie is not present, for example, when they first visit the site, ASP.NET redirects them to a login page where they provide their username and password. The <forms> element, described in more detail in the next section, specifies the parameters and, optionally, the login credentials applied. When using this type of authentication, we do not include the <passport> element within your <authentication> element.
  • Passport. In this mode, ASP.NET redirects users to the Microsoft Passport Web site where they enter their login credentials for authentication. The Passport site then redirects them to your site after placing a suitable cookie on their machine that identifies them. The <passport> element defines the URL for the Passport site, and we must sign up with Microsoft Passport (and pay a fee) to use this service. When using this type of authentication, we do not include the <forms> element within your <authentication>

Using Forms Authentication

The most common authentication approach for public Web sites and Web applications is Forms authentication. This does not rely on any specific network protocols and works through firewalls and proxy servers as well as over the Internet. It is, in fact, similar to the custom techniques that Web site developers have used for many years. However, ASP.NET makes it easy to program and, in most cases, a lot more secure than customer techniques.

The <forms> element contains the following series of attributes that define the behavior of the authentication process:

  • name. This attribute defines the name of your application and identifies the cookie sent to the client. The default, if omitted, is .ASPXAUTH. If we run multiple applications on the same machine, we should provide each one with a unique name.    
  • path. This attribute defines the path to which the authentication cookie applies. In general, we will use "/" so that it applies to the complete site. This avoids issues such as repeated login redirects as users navigate different sections of the site.    
  • domain. This optional attribute can be used to change the name of the domain in the authentication cookie.    
  • loginUrl. This attribute specifies the URL of the login page where ASP.NET redirects visitors who do not have a valid cookie present.    
  • defaultUrl. This optional attribute specifies the URL that the Forms authentication system will redirect the user to once authentication is complete. The default value if omitted is "default.aspx".    
  • protection. This attribute defines if ASP.NET will apply encryption and/or validation to the cookie. The validation algorithm uses the value of the <machineKey> element in machine.config. The encryption method is Triple-DES (3DES) if available and the key 48 bytes or more, or DES otherwise. We should generally specify All for maximum security.    
  • timeout and slidingExpiration. This attribute defines the number of minutes before the cookie expires, and hence the user has to log in again. Each page request resets the timer by creating a new cookie, unless we set the slidingExpiration attribute to true. The default for the slidingExpiration attribute is false.    
  • requiresSSL. This attribute specifies if requests to the login page (defined in the loginUrl attribute) must be over a secure connection using SSL. We should endeavor to always use SSL for your login pages, with the possible exception of applications where security is non-critical (such as when used only for page personalization).    
  • cookieless. This attribute specifies if cookies are used to maintain authentication between requests, or if the information should be encoded into the URL. The "AutoDetect" setting causes ASP.NET to use cookies where the browser supports them and they are enabled. The "UseDeviceProfile" setting specifies that ASP.NET should use cookies whenever the browser information stored in the browser capabilities files suggests that cookies are supported, without checking if the user has disabled them.
  • enableCrossAppRedirects. This optional attribute, when set to "true", allows code to redirect users to different ASP.NET applications while preserving the authentication state. In this case, we must specify the same name, protection, and path attribute values in both applications and the same specific keys for the <machineKey> sections of the web.config files.

The <credentials> Element

Both Windows and Passport authentication techniques maintain a list of valid users, outside of your ASP.NET application. Windows stores its accounts details in an internal secure database on the server or the domain controller. The Microsoft Passport site stores user details centrally, and it does not expose them to your ASP.NET applications.
However, when we use Forms authentication, we must provide the list of valid users so that ASP.NET can validate logon requests. One way is to include the list of users in your web.config file in the <credentials> element. For each user, we include a <user> element that specifies the user name and password. To avoid storing plain text passwords, we can encrypt them using the delightfully named HashPasswordForStoringInConfigFile method of the System.Web.Security.FormsAuthentication class. We then specify the encryption type we used in the passwordFormat attribute of the <credentials> element.

Cookie-less Sessions and Cookie-less Forms Authentication

One issue that we might come across when using Forms authentication is that it depends on the client's browser accepting and then returning the special cookie that indicates they were authenticated. For clients that do not support cookies, or who have disabled them in their browser options, Forms authentication (together with session support and other features of ASP.NET) will fail to work correctly, because ASP.NET cannot then recognize users when they make a subsequent request.

To get around this, we can use cookie-less sessions and cookie-less Forms authentication methods. When we enable cookie-less sessions, ASP.NET inserts the session ID into the URL so that it recognizes the user on the next request. The <sessionState> element in the <system.web> section of web.config can specify that ASP.NET should use cookie-less sessions:

<sessionState cookieless="true" />

We specify cookie-less Forms authentication using the cookieless attribute of the <forms> element, as shown at the beginning of this current section. The FormsAuthentication class exposes the static CookiesSupported and CookieMode properties that provide information about the current configuration or the current user's cookie support.

ASP.NET Authorization Settings

Having specified the type of authentication we will use, we now have a technique that allows ASP.NET to identify visitors to the site, or to a specific subsection of the site. However, we also have to provide ASP.NET with information on what permissions and privileges each user should have. In other words, having identified a user, should ASP.NET allow that user to access a specific folder or resource?

<system.web>
...
<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
</authorization>
...
</system.web>

There are two specific characters we can use in the users attribute of the <allow> and <deny> elements:

  • • The asterisk (*) means "all users"
  • • The question mark (?) means "anonymous users," in other words, users that have been authenticated by IIS within the context of the "IUSR_[machine-name]" account

The verbs attribute refers to specific types of HTTP request; the types recognized by ASP.NET are GET, HEAD, POST, and DEBUG. This means that we can allow or deny access based on the type of request. For example, we can allow specific users (or all users) to access pages only by using values in the query string (GET) and not when posting values from a <form>.

The most stringent rules take precedence, so that (when using Windows authentication) we can deny access to a Windows account group in the <deny> element but then allow access to a specific account within that group using the <allow> element.
We use the <authorization> element in a web.config file placed in the secured target folder of your site in other words, in the folder(s) where we want to limit access to specific authenticated users. These folders must be within the virtual application to which the <authentication> element applies. Alternatively, we can use the <location> element to target parts of a web.config file at a specific folder or resource, as shown in example

<configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name="myapp" path="/" loginUrl="login.aspx"
protection="All" requireSSL="true"
timeout="30" slidingExpiration=" false">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="alex" password="56&FEw%x2K"/>
</credentials>
</forms>
</authentication>
...
</system.web>
<location path="SecureArea"
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
...
</configuration>

HAVE A HAPPY CODING!

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting Service

clock March 12, 2015 09:11 by author Ben


ASPHostPortal.com, the leader of ASP.NET & Windows hosting provider launches Reliable Zikula 1.4.0 Hosting with comprehensive package.


With the Best excellent service, ASPHostPortal.com is one of the primary Windows hosting providers providing good quality provider with quality assistance. Their servers are built using the most current know-how. They're enthusiastic about web hosting and attempt to deliver an outstanding degree of assistance to each customer. Their world wide web hosting options are well suited for tiny to medium-sized weblogs, personal, charity or business websites. Currently, they launch Zikula 1.4.0 Hosting with reliable technology and cost-effective value.

Zikula is an open source site builder that is quick and simple to use. Using a number of themes, plugins, and user-friendly tools, it is a simple and highly flexible method to get your business webpage, online shop, or blog up and running. Zikula is a powerful PHP-based application development framework which has content material management capabilities built-in. The idea is to expose all the functionality of a common Application Improvement Framework, with all the up-and-running ease of a conventional CMS.

This is achieved by constructing Zikula on top of other development frameworks and implementing a modular approach to feature development.

The day has ultimately come, ASPHostPortal.com Announces Reliable Zikula 1.4.0 Hosting. Zikula 1.4.0 has Symfony at it is foundation, which consists of Doctrine. And Zikula 1.4.0 integrates Twitter's Bootstrap 3 and Font Awesome 4 and utilizes jQuery for exciting web user-interfaces and effects.

"Zikula : an OpenSource PHP Application Framework and CMS for the site, No matter what your demands, Zikula can give the solution. Whether it is a big corporate web presence with ecommerce, a little basic blog or a community portal, Zikula can do it all. Zikula is infinitely expandable with modules and plugins that may add the functionality you need. And all with tomorrow's technology. Greatest of all, it really is totally totally free. ASPHostPortal provides you with the support and help you need," said Dean Thomas, Manager at ASPHostPortal.com.

With 7 data centers that located in USA, Europe, Australia and Asia, ASPHostPortal is superior provider in the hosting market place. They supplies Zikula 1.4.0 Hosting only from $5/month with 30 days funds back assure. Furthermore, ASPHostPortal has been awarded as one from the very best hosting firms within the market due to the excellent hosting overall performance this hosting offers. To supply ideal hosting functionality, this company often maintains the server with expert group in ASP.NET Technology. To learn a lot more about Zikula 1.4.0 Hosting, please visit http://asphostportal.com/Zikula-1-4-0-Hosting

About ASPHostPortal.com

ASPHostPortal.com will be the Reliable, Cheap and Recommended Windows & ASP.NET Hosting. ASPHostPortal.com has capability to support the latest Microsoft and ASP.NET technologies, such as: like: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 5, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch. ASPHostPortal include shared hosting, reseller hosting, and sharepoint hosting, with speciality in ASP.NET, SQL Server, and architecting very scalable options. ASPHostPortal.com strives to provide most likely the most technologically advanced hosting solutions obtainable to all customers the world over. Protection, trustworthiness, and efficiency are on the core of hosting operations to create particular each website and software hosted is so secured and performs at the ideal feasible level.




ASP.NET Hosting - ASPHostPortal.com :: Utilizing Compass Framework with ASP.NET MVC Application

clock March 7, 2015 08:11 by author Ben

In my preceding post I described Greatness ASP.NET Web Config File. In this post I'm taking subsequent step - start off working with Compass - CSS Authoring Framework. Instantly right after installing Internet Workbench, you'll be able to create/edit SCSS file, which are compiled into CSS. By default, Internet Workbench compile SCSS files with SASS compiler. But there's a trick:

Setup Compass Project
Appropriate click on project node in answer explorer, then pick "Setup Compass Project"

It will modify your project by adding "sass" folder with "ie.scss", "print.scss" and "screen.scss" files and compass project configuration file "config.rb" in root.

"config.rb" is really a Ruby file, contains configuration properties, such "css_dir" - the directory where the css stylesheets are kept and "sass_dir" - the directory where the sass stylesheets are kept.

From now, all SASS files, positioned in "sass_dir" will be complied by Compass compiler and, accordingly, CSS output files will be stored in "css_dir".

Should you never desire to alter your ASP.NET project layout, you could choose to adjust Compass configuration.

I choose to help keep all SCSS files in separate directory, consequently I produced "Content/scss" folder and moved existing *.scss files there.
Then I changed config.rb file as bellow:

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "Content"
sass_dir = "Content/scss"
images_dir = "images"
javascripts_dir = "Scripts"

Now Internet Workbench recognizes scss files as part of Compass project and runs Compass compiler against them. Output css files stay within the identical place, so no need to update views.

Get Magic of Compass

Just open Compass API references and commence coding. Lest consume certainly one of standard functions of Compass - Reset. add following line in beginning of SCSS file @import "compass/reset"; The only line will create plenty of reset rules in output css


Compass has a large amount of valuable functions, and all of them are obtainable in your ASP.NET application.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



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