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

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

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.



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._%+-][email protected][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.



ASP.NET Hosting - ASPHostPortal.com :: 5 Various Types of Hidden Fields in .NET

clock March 3, 2015 05:27 by author Mark

 

We'll discuss the following:

_VIEWSTATE
    _EVENTVALIDATION
    _EVENTTARGET
    _EVENTARGUMENT &
    The PostBack mechanism
HTTP is a stateless protocol. To make ASP.Net applications stateful, .NET uses sessions, cookies and several hidden fields.

  • _VIEWSTATE

Let's create a demo app to understand ViewState.

Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostBackDemo.Default" %>  
<!DOCTYPE html>   
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    </form> 
</body> 
</html>

Page Source

 

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head><title></title></head> 
<body> 
    <form method="post" action="Default.aspx" id="form1"> 
<div class="aspNetHidden"> 
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZH0OltWWPaXud4euu7mw8G7bgQ/b9JRsQeJQCRIcL9GA" /> 
</div>     
    </form> 
</body> 
</html>

For an empty form with runat= “server” (an aspx page with a <form runat= “server”> element only) a hidden field “_VIEWSTATE” is also generated. In other words if any of your elements is to be used server side then the ASP.NET run time will create a “_VIEWSTATE” hidden field.
The _VIEWSTATE holds the state of the page when it was last processed on the server to map it unambiguously with a page request. Whenever a PostBack occurs the page class takes data stored in the view state, processes the data, regenerates the page with new values and sends it back to the client.

Since ViewState is stored in a hidden field in the client side, it can be tampered with. To avoid this tampering of ViewState, by default View state is encoded using the Base64 schema and hashed. The hashed content is also stored in _VIEWSTATE. The hash value is calculated with the _VIEWSTATE content and server key. Now, when the page posts back, the content and hash value in _VIEWSTATE is separeted. The hash value is recalculated using the _VIEWSTATE content and server key. If both hash keys match, it goes for further processing else throws a Security exception like “The state information is invalid for this page and might be corrupted”.
The ViewState is included in the form element and goes with each HTTP request and response. So, it inevitably increases request and response size.

  • _EVENTVALIDATION

_EVENTVALIDATION is for validating controls. To ensure the request data is from a known element, not a maliciously added element.
Now, let's add some client-side controls (HTML elements without runat= “server”) to our demo aspx page.

Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostBackDemo.Default" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <input type="text" /> 
            <input type="button" onclick="TestFunc();" /> 
        </div> 
        <script type="text/javascript"> 
            function TestFunc() { 
                alert("Hey! you clicked"); 
            } 
        </script> 
    </form> 
</body> 
</html>
    </html> 

Page Source


    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head><title></title></head> 
    <body> 
        <form method="post" action="Default.aspx" id="form1"> 
    <div class="aspNetHidden"> 
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZH0OltWWPaXud4euu7mw8G7bgQ/b9JRsQeJQCRIcL9GA" /> 
    </div> 
            <div> 
                <input type="text" /> 
                <input type="button" onclick="TestFunc();" />           
            </div> 
            <script type="text/javascript"> 
                function TestFunc() { 
                    alert("Hey! you clicked"); 
                } 
            </script> 
        </form> 
    </body> 
    </html 

I added a text box and a button, but there is not much change in page source except the changes we did in the aspx page.
Now, let's make this button a server-side button (in other words Add runat= “server”).

Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostBackDemo.Default" %> 
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <input type="text" /> 
            <input type="button" onclick="TestFunc();" runat="server" /> 
        </div> 
        <script type="text/javascript"> 
            function TestFunc() { 
                alert("Hey! you clicked"); 
            } 
        </script> 
    </form> 
</body> 
</html>

Page Source


    <!DOCTYPE html> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head><title></title></head> 
    <body> 
        <form method="post" action="Default.aspx" id="form1"> 
    <div class="aspNetHidden"> 
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDIyMjM2NTY0ZGSXEZ4qwAszJ6dR3TSLdPvX3w7362I3AOBVJK+fKRnbkg==" /> 
    </div>   
        <div class="aspNetHidden"> 
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAK5I+PyblDBmWfKCdwXh3rh4q8s12WcMm4dben72M8A363x1W3ZmPm8tm9nmU+G2hAvlotBSLddt1LAtzvX8Omx" /> 
    </div> 
            <div> 
                <input type="text" /> 
                <input name="ctl02" type="button" onclick="TestFunc();" />    
            </div> 
            <script type="text/javascript"> 
                function TestFunc() { 
                    alert("Hey! you clicked"); 
                } 
            </script> 
        </form> 
    </body> 
    </html> 

So, now another hidden field “_EVENTVALIDATION” was added. In other words “_EVENTVALIDATION” is being added for server-side input controls.
_EVENTVALIDATION is used to ensure the postbacks and callbacks are coming from expected User Interface elements. Content is stored in _EVENTVALIDATION just before rendering the page. This feature can be enabled or disabled at the page level using EnableEventValidation in the Page directive tag.
Basically, the Page matches content of the request with content stored in _EVENTVALIDATION to confirm that data is coming from a UI element known to the server, not from any maliciously added element.

  • _doPostBack, _EVENTTARGET, _EVENTARGUMENT

Now, let's add a server-side event handler to this button and a server-side button as well.

Default.aspx


    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostBackDemo.Default" %>    
    <!DOCTYPE html>    
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
        <title></title> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
            <div> 
                <input type="text" /> 
                <input type="button" onclick="TestFunc();" runat="server" id="btnTest" OnServerClick="Button_Click" value="Html Button"/> 
    <asp:Button runat="server" ID="AspBtnTest" OnClick="AspButton_Click" OnClientClick="TestFunc();" Text="Asp Button"/> 
            </div> 
            <script type="text/javascript"> 
                function TestFunc() { 
                    alert("Hey! you clicked"); 
                } 
            </script> 
        </form> 
    </body> 
    </html> 

Default.aspx.cs


    using System; 
    namespace PostBackDemo 
    { 
        public partial class Default : System.Web.UI.Page 
        { 
            protected void Page_Load(object sender, EventArgs e) 
            { } 
            protected void Button_Click(object sender, EventArgs e) 
            { 
                Page.ClientScript.RegisterClientScriptBlock(GetType(), 
                Guid.NewGuid().ToString("N"), "alert('Did a postback')", true); 
            } 
            protected void AspButton_Click(object sender, EventArgs e) 
            { 
                Page.ClientScript.RegisterClientScriptBlock(GetType(), 
                Guid.NewGuid().ToString("N"), "alert('Asp button did a postback')", true); 
            } 
        } 
    } 

Page Source


<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head><title></title></head> 
<body> 
    <form method="post" action="Default.aspx" id="form1"> 
<div class="aspNetHidden"> 
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> 
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> 
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDIyMjM2NTY0ZGSXEZ4qwAszJ6dR3TSLdPvX3w7362I3AOBVJK+fKRnbkg==" /> 
</div> 
<script type="text/javascript"> 
//<![CDATA[ 
var theForm = document.forms['form1']; 
if (!theForm) { 
    theForm = document.form1; 

function __doPostBack(eventTarget, eventArgument) { 
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) { 
        theForm.__EVENTTARGET.value = eventTarget; 
        theForm.__EVENTARGUMENT.value = eventArgument; 
        theForm.submit(); 
    } 

//]]> 
</script> 
<div class="aspNetHidden"> 
        <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAK5I+PyblDBmWfKCdwXh3rh4q8s12WcMm4dben72M8A363x1W3ZmPm8tm9nmU+G2hAvlotBSLddt1LAtzvX8Omx" /> 
</div> 
        <div> 
            <input type="text" /> 
            <input onclick="TestFunc(); __doPostBack('ctl02','')" name="btnTest" type="button" id="btnTest" value="Html Button" /> 
          <input type="submit" name="AspBtnTest" value="Asp Button" onclick="TestFunc();" id="AspBtnTest" />  
        </div> 
        <script type="text/javascript"> 
            function TestFunc() { 
                alert("Hey! you clicked"); 
            } 
        </script> 
    </form> 
</body> 
</html>


2 new hidden fields “_EVENTTARGET and _EVENTARGUMENT” were created and some script having “_doPostBack()” was added. So when you have controls that can cause postback, these hidden fields and script are created.
Here, you can see the HTML button is not doing a direct post-back. It calls _doPostBack(eventTarget, eventArgument) and this method calls the server-side event handler or causes a post-back.
The hidden field “_EVENTTARGET” holds the ID of the control causing the postback and “_EVENTARGUMENT” contains additional information associated with the control.

Note: Controllers of type IpostBackEventHandler (implementing IpostBackEventHandler) cause a direct post-back. Other controls use a _doPostback() JavaScript function to call the server-side event handler.

There are only 2 Web server controls, Button and ImageButton, that cause a direct post-back. Others trigger a post-back using the _doPostBack() JavaScript function.
So, for controls using _doPostBack(), you can get the control that causes a postBack as follows:


protected void Page_Load(object sender, EventArgs e) 

   string ControlId = Request.Params.Get("_EVENTTARGET"); 
   if (!string.IsNullOrEmpty(ControlId)) 
   { 
      Page.ClientScript.RegisterStartupScript(GetType(), 
      Guid.NewGuid().ToString("N"), 
      "alert('Control with ID:" + ControlId + " caused postback')", true); 
   } 
}


But, for Buttons and ImageButtons you need to call the _doPostBack() with button Id explicitly OnClientClick(). Then, follow the same procedure to get the element causing the PostBack().
From the code above remove the <input type= “button”> element and keep the <asp:Button>, you can see there is no _EVENTTARGET and _EVENTARGUMENT hidden field or _doPostBack() JavaScript function since asp:Button is doing a direct postback.


Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PostBackDemo.Default" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <div> 
            <input type="text" /> 
<asp:Button runat="server" ID="AspBtnTest" OnClick="AspButton_Click" OnClientClick="TestFunc();" Text="Asp Button"/> 
        </div> 
        <script type="text/javascript"> 
            function TestFunc() { 
                alert("Hey! you clicked"); 
            } 
        </script> 
    </form> 
</body>

Default.aspx.cs


    using System; 
    namespace PostBackDemo 
    { 
        public partial class Default : System.Web.UI.Page 
        { 
            protected void Page_Load(object sender, EventArgs e) 
            { } 
            protected void AspButton_Click(object sender, EventArgs e) 
            { 
                Page.ClientScript.RegisterClientScriptBlock(GetType(), 
                Guid.NewGuid().ToString("N"), "alert('Asp button did a postback')", true); 
            } 
        } 
    }  
</html>

Page Source


<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head><title></title> 
    <script src="Script/jquery-1.11.1.js"></script> 
</head> 
<body> 
    <form method="post" action="Default.aspx" id="form1"> 
<div class="aspNetHidden"> 
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkB/iWAnhisFL/BNe0slZ319eTcGFZayj3aW2rKeptEAk=" /> 
</div> 
<div class="aspNetHidden"> 
        <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAKrZZDeDrjNeyuPPqXKcefNI5oLptWPTPFd2fcP0LUic9/ED7QKOeuxn48nwM/QT7XNadP1I+7bSAmOnoTtiPYK" /> 
</div> 
        <div> 
            <input type="text" /> 
            <input type="submit" name="AspBtnTest" value="Asp Button" onclick="PostBack();" id="AspBtnTest" /> 
        </div> 
        <script type="text/javascript"> 
            function TestFunc() { 
                alert("Hey! you clicked"); 
            } 
        </script> 
    </form> 
</body> 
</html>

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, 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 guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal.com :: How to Convert DataTable To JSON String in ASP.NET

clock February 24, 2015 06:34 by author Mark

First of all you need to create an "ASP.NET Empty Web Site". Then use the following procedure.

Step 1

Create a ConvertDataTableToJson class in the App_Code folder and provide the following:

Convert DataTable To JSON String.       
    using System.Data 
    using System.Text; 
    public class ConvertDatatableToJson 
    { 
       public string DataTableToJson(DataTable dt) 
       { 
          DataSet ds = new DataSet(); 
          ds.Merge(dt); 
          StringBuilder JsonStr = new StringBuilder(); 
          if (ds != null && ds.Tables[0].Rows.Count > 0) 
          { 
             JsonStr.Append("["); 
             for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
             { 
                JsonStr.Append("{"); 
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++) 
                { 
                   if (j < ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\","); 
                   } 
                   else if (j == ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\""); 
                   } 
                } 
                if (i == ds.Tables[0].Rows.Count - 1) 
                { 
                   JsonStr.Append("}"); 
                } 
                else    
                { 
                   JsonStr.Append("},"); 
                } 
             } 
             JsonStr.Append("]"); 
             return JsonStr.ToString(); 
          } 
          else 
          { 
             return null; 
          } 
       }

Step 2

Insert the grid view control into the Default.aspx page then write the following design code:

<asp:GridView ID="ui_grdVw_EmployeeDetail" runat="server" Width="50%" AutoGenerateColumns="false" HeaderStyle-CssClass="pageheading"> 
    <Columns> 
    <asp:TemplateField HeaderText="S.NO"> 
    <ItemTemplate> 
    <%#Container.DataItemIndex+1 %> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee ID"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_id") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Name"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Name") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Post"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmpJob" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_job") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Department"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_Department" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Dep") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
    </asp:GridView> 
    <br /> 
    <asp:Button ID="ui_btn_Convert1" runat="server" Text="Manually Convert To Json" OnClick="ui_btn_Convert1_Click" /><br /><br /><br /> 
    <asp:Label ID="ui_lbl_JsonString1" runat="server"></asp:Label>

Step 3

Now, open the Deafult.asps.cs then write the following code:
    using System; 
    using System.Data;
 

    public partial class _Default : System.Web.UI.Page 
    { 
       #region Global Variable 
       DataTable dt; 
       ConvertDatatableToJson dtJ; 
       string JsonString = string.Empty;    
       #endregion 
        
       protected void Page_Load(object sender, EventArgs e) 
       { 
          if (!IsPostBack) 
          { 
             ui_grdvw_EmployeeDetail_Bind(); 
          } 
       }       
       protected void ui_grdvw_EmployeeDetail_Bind() 
       { 
          dt = new DataTable(); 
          EmployeeRecord employeeRecord = new EmployeeRecord(); 
          dt = employeeRecord.EmpRecord(); 
          ViewState["dt"] = dt; 
          ui_grdVw_EmployeeDetail.DataSource = dt; 
          ui_grdVw_EmployeeDetail.DataBind(); 
       }       
       protected void ui_btn_Convert1_Click(object sender, EventArgs e) 
       { 
          dtJ = new ConvertDatatableToJson(); 
          JsonString = dtJ.DataTableToJson((DataTable)ViewState["dt"]); 
          ui_lbl_JsonString1.Text = JsonString; 
       } 
    }

Step 4

Press F5, run the project.

Now, convert the DataTable to a JSON string using the newtonsoft DLL.

Step 1

Download the Newtonsoft DLL and move it to the ASP.Net project's bin folder.

Step 2

Then, insert a button and label UI Control in the Deafult.aspx page as in the following:

<asp:Button ID="iu_btn_Convert2" runat="server" Text="Newtonsoft Convert To Json" OnClick="iu_btn_Convert2_Click" /> 
    <br /> 
    <br /> 
    <asp:Label ID="ui_lbl_JsonString2" runat="server"></asp:Label>

Step 3

Now, write the following code in Default.aspx.cs:
using this namespace

using Newtonsoft.Json;

And then:

protected void iu_btn_Convert2_Click(object sender, EventArgs e) 
    { 
       dt = (DataTable)ViewState["dt"]; 
       JsonString = JsonConvert.SerializeObject((DataTable)ViewState["dt"]); 
       ui_lbl_JsonString2.Text = JsonString; 
    }

Now, run the project and click on the Newtonsoft Convert to JSON     

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 Hosting - ASPHostPortal.com :: Key Points of ASP.NET VNext

clock February 12, 2015 05:58 by author Mark

Microsoft openness and open source approach leads to ASP.NET vNext – The next generation of .NET. In this article we will discuss some of key points of vNext.
In vNext we have cloud optimization mode. Traditional scenario, we are having entire .NET Framework and CLR install to design and deploy ASP.NET application.
According to me Microsoft had spilt the framework and CLR in vNext as .NET Core and everything else. In the .NET Core we have cloud optimized runtime core with very minimum foot prints. Everything else can be very easily downloaded using Nuget repository. This is actually made compiler as service (CaaS) scenario.

(kpm restore – To compile and download required libraries from nuget.)
We would be having only minimum footprint and essential libraries to run the ASP.NET application. A minimum footprint delivers faster results. During compile time only essentials components are deployed application wise, each application can have different version of .NET vNext side by side.

(kvm list - to see what versions of the ASP.NET vNext are available.)
Dependency injection is design pattern used to manage orchestration between loosely coupled objects. Build in DI in ASP.NET vNext manages configuring services and libraries. Environment specific service / libraries can configure through DI. This is very useful methodology while working with cross platform development and deployment.
ASP.NET MVC and Web API have been unified into a single programming model. The new framework removes a lot of overlap between the existing MVC and Web API frameworks. It uses a common set of abstractions for routing, action selection, filters and model binding.
The Roslyn provides open-source C# and Visual Basic compilers with rich code analysis APIs. It enables building code analysis tools with the same APIs that are used by Visual Studio. (more details on Roslyn compiler in next article)
The .NET Foundation is an independent organization to foster open development and collaboration around the growing collection of open source technologies for .NET. We can find more details at this link.

Summary

  • Cloud and server-optimization.
  • NuGet everything - even the runtime itself.
  • Side by side - deploy the runtime and framework with your application.
  • ASP.NET MVC and Web API have been unified into a single programming model.
  • Dependency injection out of the box.
  • New flexible and cross-platform runtime.
  • All Open Source via the .NET Foundation and takes contributions.
  • Roslyn compiler.

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, 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 guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal.com :: Describes Caching Methods In ASP.NET

clock February 5, 2015 06:45 by author Mark

Today I will describes caching methods in ASP.NET. It's a good habit to use caching in your application and coding standards too.

Overview

Caching is one of the most interesting concepts and operations in ASP.NET. If you can handle it, you can run any web application by applying the caching concept depending on the requirements.
Currrently a majority of websites/portals (or I can say simply web pages) are dynamic (if I do talk about a dynamic website, then it doesn't mean all the pages of that website is dynamic or will be. The probability of happening this is dependent on the user's perspective and the requirements).
In veru common words I can define dynamic pages as including the following:

  • Pages that directly interact with people
  • Communication (on page)
  • Any media content
  • Any Type of grafic Interaction

So, generally these types of pages or webs are called dynamic. Now let's find why we really need caching.

Why Caching

Caching is for providing solutions or the results to the users depending on their requested request, admin needs to recreate the pages often depending on user requests…STOP!!!

The process

The process is quite bulky and time-consuming. So to overcoming that problem some websites have a page creation engine that automatically creates all the pages in one action and directly saves those pages as a HTML structured page. These HTML pages serve the user depending on their requirements.

Multiple sorts of pages

But, do you still think this will be enough? If your answer is yes, then please think some more!
Actually, the preceding solution will only work if and only if the requested pages are of the same type. Now think, what will happen if the users request a different sort of page?
In that case your web will be stuck again.
So for dealing with that kind of complex but necessary requirements, ASP.NET provides support for caching. Caching is the hero/heroine in this context that will help us to a great extent.

What a Cache does

What a cache does, in the most simple words I can say is:
"A cache simply stores the output generated by a page in the memory and this saved output (cache) will serve us (users) in the future." That's it.

Types

Page Caching

Let's explore the caching of an entire page, first.
To cache an entire page's output we need to specify a directive at the top of our page, this directive is the @ OutputCache.
Let's figure out a simple demo of it.

<%@ OutputCache Duration = 5 VaryByParam = "ID" %> 

Here, in that statement Duration and VarByParam are the two attributes of the OutputCache directive. Now let's explore how they work.

  • Duration Attribute : This attributes represents the time in seconds of how long the output cache should be stored in memory. After the defined duration the content stored in the memory will be cleared automatically.
  • VarByParam Attribute : This is the most important attributes; you can't afford to miss that in the OutputCache directory statement. It generally defines the query string parameters to vary the cache (in memory).

You can also pass multiple parameter names too, but for that you need to separate them using a semicolon (;).
You can also specify it as "*". In this case the cached content is varied for all the parameters passed using the querysrting.
For example:

<%@ OutputCache Duration = 5 VaryByParam = "*"%> 

In case of caching a page, some pages can generate different content for different browsers. In that scenario we need to add an additional attribute to our statement for overcoming the preceding problem.
For example:

<%@ OutputCache Duration = 5 VaryByParam = "ID" VaryByCustom = "Browser" %> 

Or:

<%@ OutputCache Duration = 5 VaryByParam = "*" VaryByCustom = "Browser" %>

Fragment caching

In some scenarios we only need to cache only a segment of a page. For example a contact us page in a main page will be the same for all the users and for that there is no need to cache the entire page.
So for that we prefer to use fragment caching option.
For example:

<%@ OutputCache Duration = 10 VaryByParam = "None" %> 

Or:

<%@ OutputCache Duration = 5 VaryByParam = "None" VaryByCustom = "Browser" %> 

Data Caching

Data caching is slightly different from the 2 other caching types. It's much more interesting to see how data caching actually works.
As we know in C# everything is about classes and objects. So ASP.NET supports data caching by treating them as small sets of objects. We can store objects in memory very easily and use them depending on our functionality and needs, anywhere across the page.
Now you must be thinking where is the class in that entire scenario?
Actually, this feature is implemented using the Cache class and data is treated as its object. Let's see how it works using a demo.

I am inserting a string value in the cache as:

Cache["Website"] = "CSharpCorner"; 

Now, for inserting the cache into the objects, the insert method of the Cache class can be used. This insert method is used as follows:

Cache.Insert("Website", strName, 
new CacheDependency(Sever.MapPath("Website.txt")); 

What we are missing something
We missed the Time for the cache (don't forget to use it), let's provide it:

Cache.Insert("Website", strName, 
new CacheDependency(Sever.MapPath("Website.txt") 
DateTime.Now.Addminutes(5), TimeSpan.Zero); 

Happy coding!

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, 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 guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal.com :: return View() vs return RedirectToAction() vs return Redirect() vs return RedirectToRoute()

clock January 28, 2015 05:47 by author Ben

There are various approaches for returning/rendering a view in MVC Razor. Numerous developers got confused when to utilize return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute(). In this article, I'd prefer to explain the difference amongst "return View()" and "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".


return View()

This tells MVC to create HTML to become displayed for the specified view and sends it to the browser. This acts like as Server.Transfer() in Asp.Net WebForm.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Server.Transfer() in Asp.Net WebForm
    return View("MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
    return View("MyIndex");
    }


What happens if we contact the action strategy directly like return MyIndex(). It is basically a technique call which returns a rendered view which is specified in MyIndex() action method.

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return MyIndex();
}
public ActionResult MyIndex()
{
ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
return View("MyIndex");

}

return RedirectToAction()

This tells MVC to redirect to specified action instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified action. This acts like as Response.Redirect() in Asp.Net WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and use the route table to generate the correct URL. RedirectToAction cause the browser to receive a 302 redirect within your application and gives you an easier way to work with your route table.


    public ActionResult Index()
    {
    return View();
    }
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return RedirectToAction("MyIndex");
    }
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return Redirect()

This tells MVC to redirect to specified URL instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified URL. This also acts like as Response.Redirect() in Asp.Net WebForm. In this case, you have to specify the full URL to redirect.
Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself.


    public ActionResult Index()
    {
    return View();
    }
    
    [HttpPost]
    public ActionResult Index(string Name)
    {
    ViewBag.Message = "Hi, Dot Net Tricks";
    //Like Response.Redirect() in Asp.Net WebForm
    return Redirect("Home/MyIndex");
    }
    
    public ActionResult MyIndex()
    {
    ViewBag.Msg = ViewBag.Message; // Assigned value : Null
    return View("MyIndex");
    }


return RedirectToRoute()

This tells MVC to look up the specifies route into the Route table that is is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction().

Defined Route


    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.MapRoute(
    "MyRoute", // Route name
    "Account/", // URL
    new { controller = "Account", action = "Login"} // Parameter defaults
    );
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } // Parameter defaults
    );
    }


HomeController

public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("MyRoute");
}

AccountController

public ActionResult Login()
{
return View();
}

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 SSRS hosting starts from $5/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SSRS Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal :: Describe the Lifecycle of an ASP. NET Web API Message

clock January 27, 2015 05:36 by author Mark

In this article we will describe the Lifecycle of an ASP. NET Web API message. We know that the ASP. NET Web API is a framework that helps build the services over the HTTP server. It provides the lightweight services used by multiple clients and devices of the platform to access the data via the API. For transferring the data over the wire , it uses the JavaScript Object Notation (JSON) and Extensible Markup Language (XML)
Now we will define the Lifecycle of an ASP. NET Web API Message from the client to the server and the server to the client. The request is generated by the client using HttpRequest and the return response is generated by HttpResponse.

Diagram of Web API Pipeline

Hosting of web API

We perform two types of hosting on the Web API. They are ASP.NET and Selfhosting, as described in the following:

  • ASP.Net Hosting:  When we perform the ASP.NET hosting then the Lifecycle starts from HttpControllerHeader which is the implementation of IHttpAsyncHandler and the responsibility of it is to send the request to the HttpServer pipeline.
  • Self Hosting:  In self hosting the HttpServer pipeline starts from the HttpSelfHostServer that performs the implementation of HttpServer and the responsibility is that it can be directly listen to the HTTP request.

HTTP Message Handler

After leaving the service host the request travels in the pipeline as a HttpRequestMessage. There is the Handler used in the Lifecycle.

Delegating Handler

This handler is provided to you as a Message of the request before passing onto the rest of the pipeline. The response message can be sent through the delegating handler. And other messages can be monitored and filtered at this point.

Routing Dispatcher

When the request is made using the option Delegation Handler it can be passed to the Routing Dispatcher. The dispatcher checks whether the Route Handler is Null. If the the Route Handler is null then it is passed to the next step in the pipeline.
If it is not null then there are many handlers for routing the message and the desired request is passed to the handler. We select the matching message handler to handle the request.

Controllers

After leaving the service host the request is travels in the pipeline as a HttpRequestMessage. These are the handlers used in the Lifecycle.

Authorization Filter

In the control section the first step is passed to the authorization. If there are Authorization Filters available and the authorization is failed by the request then the request is truncated and sent as a auth failure response.

Model Binding

If the authorization test is successful then it is passed to the model binding section. It is not a single-step process.
If we want to see the model binding process then it looks like the following.

View of Model Binding

In the model binding we can see the three parts of the HTTP request; they are URI, Headers and Entity Body.

 

URI

The URI works as a ModelBinderParameterBinder object that checks that there are custom IModelBinder an IValueProvider.

Formatter Binding

The Entity body of the model binding is managed by the FrmatterParameterBinding. If there is a request that needs to utilize one or two Media Type Formatters then it is piped through the appropriate Media Type Formatter.

HTTP parameter binding

There is a need for the entire request to be piped through the HTTP parameter binding module, if there is a custom HTTP Parameter Binding module.

Action Filter

After completion of the Model Binding the Action Filter is done. It is invoked two times in the pipeline before the OnExecuting event and after the OnExecution event.

Action Invoker

The action invoker invokes the actions of the control. It binds and models the state for invoking the action in HttpActionContext. It can invoke the action and also return the message in the form of a HttpResponseMessage. If there is an Exception at the time of invoking the action then the exception is routed to the Exception Filter that can send the Error Message.

Controller Action

Controller Action executes the Action Method code. And it generates the HttpResponseMessage.

Result Conversion

Now we see the image of the Result Conversion:

  • HttpResponseMessage: The message is directly passed in it and nothing needs conversion.
  • Void: The action method returns the void result in it and there is a need for conversion into a HttpPesponseMessage.

If the Action Method returns any other type then the Content Negotiation and Media Type Formatters are used. The Content Negotiation checks that we can return the requested content using the appropriate Media Type formatter.

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, 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 guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




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