ASP.NET 4.5 Hosting BLOG

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

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.



ASP.NET Hosting - ASPHostPortal.com :: Greatness ASP.NET Web Config File

clock March 6, 2015 06:37 by author Dan

Utilizations of XML have been coordinated into .NET to such a degree, to the point that XML is scarcely a trendy expression any longer. Microsoft, as you presumably know, has taken XML into the center of its .NET structure. Not just is XML a by and large acknowledged organization for the trading of information, its likewise used to store design settings.

Design settings for any of your ASP.NET Web applications can be put away in a straightforward content document. Displayed in an effortlessly reasonable XML design, this document, called Web.config, can contain all inclusive information, for example, database association strings, custom slip messages, and society settings.

Since the Web.config is a XML record, it can comprise of any substantial XML labels, yet the root component ought to dependably be <configuration>. Settled inside this label you can incorporate different labels to portray your settings. Since a Web.config record comes as a standard when you begin to manufacture another Web application, how about we take a gander at the default XML document created by Visual Studio .NET:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation 
         defaultLanguage="c#"
         debug="true"
    />
    <customErrors 
    mode="RemoteOnly" 
    /> 
    <authentication mode="Windows" /> 
    <authorization>
        <allow users="*" />
    </authorization>
    <trace
        enabled="false"
        requestLimit="10"
        pageOutput="false"
        traceMode="SortByTime"
    localOnly="true"
    />
    <sessionState 
            mode="InProc"            stateConnectionString="tcpip=127.0.0.1:42424"
            sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
            cookieless="false" 
            timeout="20" 
    />
    <globalization 
            requestEncoding="utf-8" 
            responseEncoding="utf-8" 
   />    
 </system.web>
</configuration>


Experienced ASP.NET software engineers will have perceived that I've forgotten the remark labels that are produced consequently with the record. I've done that to give a reasonable perspective of the XML that is utilized here. Additionally, I'll expand on every design tag later in this article, and this discourse will make the remark labels rather out of date.

In the event that you take a gander at the illustration XML, you'll recognize that the <configuration> tag has one and only tyke tag, which we call segment amass, the <system.web> tag. An area amass regularly contains the setting segments, for example, aggregation, customErrors, confirmation, approval, and so forth. The way this works is really direct: you essentially incorporate your settings in the proper setting areas. In the event that, for instance, you needed to utilize an alternate confirmation mode for your Web application, you'd change that setting in the verification area.

Aside from the standard system.web settings, you can characterize your own particular application settings, for example, a database association string, utilizing the <appSettings> tag. Thus, your most normal Web.config blueprint would be:

<configuration>
  <system.web>
    <! -  sections-->   
  </system.web>
  <appSettings>
    <! -  sections -->   
  </appSettings >
</configuration>


How about we examine the points of interest of both segment bunches now.

The system.web Section Group


In this area bunch, you'll ordinarily incorporate arrangement settings that, in the prenet .time, you'd have set up some place in the IIS organization reassure. At Microsoft's MSDN Library, you can discover a review of every last one of labels that the system.web segment gathering sees, however, contingent upon the multifaceted nature of your website, you may not ever utilize even 50% of those choices.

How about we observe the most important changes you can make inside the system.web area bunch, in sequential order request.

<authentication>

The validation segment controls the sort of confirmation utilized inside your Web application, as contained in the characteristic mode. You'll enter the worth "None" if anybody may get to your application. In the event that verification is obliged, you'll utilize "Windows", "Structures" or "International ID" to characterize the sort of validation. For instance:

    <authentication mode="Windows" />
<authorization>


To permit or deny access to your web application to specific clients or parts, use <allow> or <deny> tyke labels.

    <authorization>
        <allow roles="Administrators,Users" />
        <deny users="*" />
    </authorization>

It's imperative to comprehend that ASP.NET's approval module repeats through the areas, applying the first decide that relates to the current client. In this sample, clients convey the part Administrators or Users will be permitted access, while all others (showed by the * special case) will experience the second control and will accordingly be denied access.

<compilation>

Here, you can arrange the compiler settings for ASP.NET. You can utilize heaps of traits here, of which the most well-known are troubleshoot and defaultLanguage. Set troubleshoot to "genuine" just on the off chance that you need the program to show troubleshooting data. Since turning on this choice decreases execution, you'd regularly need to set it to "false". The defaultLanguage property advises ASP.NET which dialect compiler to use, since you could utilize either Visual Basic .NET or C# for example. It has esteem vb of course.

<customErrors>

To furnish your end clients with custom, easy to use mistake messages, you can set the mode ascribe of this area to On. In the event that you set it to RemoteOnly, custom slips will be indicated just to remote customers, while nearby host clients will see the revolting yet helpful ASP.NET blunders - plainly, this is useful when troubleshooting. Setting the mode credit to Off will demonstrate ASP.NET mistakes to all clients.

On the off chance that you supply a relative (for occurrence,/error404.html) or outright address (http://yourdomain.com/error404.html) in the defaultRedirect characteristic, the application will be naturally diverted to this location in the event of a mistake. Note that the relative location is in respect to the area of the Web.config record, not the page in which the blunder happens. Furthermore you can utilize <error> labels to give a statusCode and a sidetrack characteristic:

    <customErrors mode="RemoteOnly" defaultRedirect="/error.html">
        <error statusCode="403" redirect="/accessdenied.html" />
        <error statusCode="404" redirect="/pagenotfound.html" />
    </customErrors>


<globalization>

The globalization segment is valuable when you need to change the encoding or the way of life of your application. Globalization is such a broad subject, to the point that a whole article could be devoted to the matter. To put it plainly, this area permits you to characterize which character set the server ought to use to send information to the customer (for occurrence UTF-8, which is the default), and which settings the server ought to use to translate and showing socially particular strings, for example, numbers and dates.

    <globalization requestEncoding="utf-8" responseEncoding="utf-8" 
        culture="nl-NL" />


Encoding is carried out through the qualities requestEncoding and responseEncoding. The qualities ought to be equivalent in each of the one-server situations. In this illustration, the application society is situated to Dutch. On the off chance that you don't supply a culture, the application will utilize the server's local settings.

<httpRuntime>

You can utilize the httpRuntime segment to design various general runtime settings, two of which are especially advantageous.

<httpRuntime appRequestQueueLimit="100" executionTimeout="600"/>

The primary quality indicates the quantity of solicitations the server may line in memory at substantial movement times. In the illustration, if there are now 100 appeals holding up to be prepared, the following appeal will bring about a 503 mistake ("Server excessively occupied").

The executionTimeout characteristic demonstrates the quantity of seconds for which ASP.NET may handle a solicitation before its timed out.

<sessionState>

In this segment of the Web.config document, we advise ASP.NET where to store the session state. The default is all the while self:

<sessionState mode="InProc"/>

Session variables are capable, yet they have a couple of drawbacks. Data is lost when the ASP.NET process accidents, and sessions are for the most part futile on account of a Web ranch (numerous Web servers). In that example, an imparted session server can explain your issues. It's past the extent of this article to develop this point, however its justified regardless of a notice. More data on sessionState can be found in the MSDN Library on the web.

<trace>

Your application's follow log is spotted in the application root organizer, under the name trace.axd. You can change the showcase of following data in the follow segment.
The properties you will search for at first are empowered: localOnly, and pageOutput.

<trace enabled="true" localOnly="true" pageOutput="false"/>

Set localOnly to "false" to get to the follow log from any customer. On the off chance that you set the estimation of pageOutput to "genuine", following data will be added to the base of every Web page.

The appSettings Section Group

Aside from the Website design settings I've been discussing in the first passages, you'll realize that a developer every now and again likes to utilize custom broad constants to store data over different pages. The most engaging case of such a custom consistent is a database association string, however you can presumably consider handfuls more from your own particular experience.

The shared element of these constants is that you need to recover their qualities automatically from your code. The Web.config document gives the likelihood to do as such, yet as a security measure, these constants must be incorporated in the <appSettings> area bunch. Much the same as <system.web>, <appSettings> is a direct youngster tag of the Web.config's arrangement root.

An average custom area gathering would look something like this:

    <appSettings>
        <add key="sqlConn" value="Server=myPc;Database=Northwind" />
        <add key="smtpServer" value="smtp.mydomain.com" />
    </appSettings>


The case demonstrates that keys and qualities can be incorporated in the custom application settings by means of a <add> tag. The best approach to get to such a worth in any of your Web pages is delineated underneath:

ConfigurationSettings.AppSettings("sqlConn")

Yes, its as simple as that! Note that the estimation of these settings is constantly a String arrangement.

A Few Other Issues

I won't go into them here, yet the Web.config record can contain a few other area bunches other than the previously stated system.web and appSettings, for example, the configSettings bunch.

  • A Web application can contain more than one Web.config document. The settings in a record apply to the catalog in which its placed, and all kid catalogs. Web.config records in kid registries outweigh the settings that are determined in guardian indexes.
  • Web.config documents are ensured by IIS, so customers can't get to them. On the off chance that you attempt to recover a current http://mydomain.com/Web.config record, you'll be given an "Entrance denied" mistake message.
  • IIS screens the Web.config records for changes and reserves the substance for execution reasons. There's no compelling reason to restart the Web server after you adjust a Web.config document.

Shutting Remarks

In this article, I've touched upon the potential outcomes that the Web.config document offers the ASP.NET developer. You can utilize the effortlessly open XML document to characterize your application settings, without the bother of utilizing the IIS administration reassure. With the Web.config document, ASP.NET gives you a chance to include, change and erase essential design settings like confirmation and approval, custom mistake showing, and following in a direct way.

Besides, the Web.config document offers you space to characterize any custom key you require, for example, database association strings. What we've accordingly seen is that, with only one line of code, you can recover the data you require from any page in your 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.



ASP.NET Hosting - ASPHostPortal.com :: How to Debugging ASP.NET vNext Beta Builds with Visual Studio 14

clock March 4, 2015 06:21 by author Ben

Nowadays, I was operating on a sample project with ASP.NET vNext. I've been functioning on this application without any Visual Studio IDE help but I decided to learn what Visual Studio 14 CTP 3 is bring to the table. I realize that Visual Studio CTP three has launched a whilst back and I was expecting to possess problems functioning with ASP.NET vNext beta builds. I was partially right. I wasn’t able to run the web application from Visual Studio. Even so, it is nevertheless feasible to debug the application and I have a workaround for you personally :)

As I was thinking in the quite starting that I would have trouble with VS 14 CTP three + vNext beta builds, I started establishing my environment in the command line instead of letting the VS deal with this.


Nevertheless, Visual Studio nonetheless insisted on installing the Aplha3 builds of the K Runtime but anyways. That is not massive of a deal provided that I have the beta 1 as the active runtime. When I open up the answer, almost everything looked OK. Even the package restore was profitable.

The develop was also functioning. Amazing!

So, it was all going wonderful till I realized that I was building with the OutputType set to "Class Library".

As soon as I changed it to web Application, the develop broke:

This really is OK and anticipated as factors have changed considering that Visual Studio 14 CTP three shipped. However, I’m unable to debug my application now. Hmm, not totally. You'll find still choices and I went using the simpler a single. I switched back to command line and ran the application from there with "k web" command:

All great as it is possible to see. Now, back to Visual Studio and press CTRL + ALT + P to bring up the Attach Process dialog box. We're searching for klr.exe to attach but you will probably see two instances of klr there. We want the one that in fact hosts our application. You can find out which 1 will be the actual host by searching at the command line arguments in the Task Manager.

In my case, it’s using the PID 1472. Finally, attach the approach and also you should have the ability to debug the application now.

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 Umbraco 7.2.2 Hosting Solution

clock March 3, 2015 08:49 by author Dan

Founded in 2008, ASPHostPortal.com has grown to become one of the leading hosting providers powering over 500,000 websites across 3 continents. Employing over 100 employees, they operate a 24 / 7 chat and ticket helpdesk. Today, we launch Umbraco 7.2.2 hosting with superior loading speed, money back guarantee and cheap price.

We offer flexible support on all of their services and response time is Avg. 15-60 minutes. We choose only the best networking partners to avoid downtimes by networking side. As well we use branded hardware and servers. Most important, we do not oversell our servers. The prices are reasonable and fit well for customers who demand services that are stable. We offer multi locations of servers and we are expanding rapidly. Just shortly: you get exactly what you pay for.

Umbraco is one of only a few open source web content management systems built on Microsoft's .NET technology stack. This CMS is no "out the box" solution. To the contrary, it's a content management system for .NET web developers. And while it's relatively straightforward to use, one must first deal with a steep learning curve. Umbraco was not designed to be a plug-and-play solution like Drupal or Joomla. Niels Hartvig, the creator of Umbraco, tried to build a system that didn't limit him on what he could do and yet still pleased non-technical clients.

Unlike many web hosts that offer outrageous amounts of space and bandwidth just to get your service, which leads to overloaded servers and poor performance, we believe in quality and not quantity. We refuse to mislead customers with "unlimited space" or "unlimited" bandwidth that has lead to the growing crowd of web hosts out there that offer unlimited plans with no intention of allowing customers to really use what they are paying for. It is the intention to stay honest and give customers what they pay for. We provide Umbraco 7.2.2 Hosting only for $5/month with easy one click installation. To learn more about Umbraco 7.2.2 Hosting, please visit http://asphostportal.com/Umbraco-7-2-2-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 :: 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 Edit ASP.NET Code Directly

clock March 2, 2015 06:11 by author Dan

It is additionally conceivable to change properties specifically by changing the ASP records on which WebLink is based, either in Visual Studio or in an outer content manager. In the ASP.NET item arranged methodology, every component of a website page is spoken to by an ASP.NET control. WebLinkControls components show up as labels introduced by "WEBLINK:" and the name of the control, for example, the accompanying case portraying the control for review the labels connected to a record:

<WEBLINK:TAGDISPLAY8 id="TheTagDisplay" runat="server" />

The properties of the control are controlled by the code inside the tag. To change the properties, essentially include, uproot or modify property definitions in the tag.

You can open pages for code altering in a few ways.

To edit the Login.aspx code in Visual Studio 2008

  1. Search to the Web Files envelope of your Laserfiche Weblink 8 establishment organizer.
  2. The default area is C:\Program Files\Laserfiche\WebLink 8.Utilizing Microsoft Visual Studio, open the WebLink8.sln record.
  3. In the Solution Explorer, twofold click Login.aspx.

To open the page for editing in Notepad

  1. Browse to the Web Files folder of your Laserfiche WebLink 8 installation folder. The default location is C:\Program Files\Laserfiche\WebLink 8.
  2. Right-click on the Login.aspx file and select Edit from the menu that appears. The page should open in Notepad. You can also choose Open With and select your preferred code text editor, or you can open Notepad and use File -> Open to browse to the Login.aspx page.

The accompanying illustration shows the code of the SearchResultsBrowser8 control on the Welcome page and reveals to it previously, then after the fact a change in the code. Note that this code contains linebreaks to elucidate the detachment between distinctive qualities inside labels and enhance lucidness. Similarly as with ordinary HTML code, the vicinity or nonappearance of linebreaks inside labels has no effect to the yield.

<weblink:SearchResultsBrowser8 ID="TheSearchResults" Visible="false" runat="server" ThumbnailCount="5" />

This tag speaks to the default arrangement of the SearchResultsBrowser8 control in the WebLink Visual Studio 2008 undertaking. Note that this default code does not set unequivocal qualities for the vast majority of the properties of the control, other than ThumbnailCount.

To change the capacity or appearance of the control, we can begin indicating qualities for the accessible properties. The accompanying sample empowers the SortableColumns property. Query items on the Welcome page can now be sorted utilizing the record name.

<weblink:SearchResultsBrowser8 ID="TheSearchResults" Visible="false" runat="server" ThumbnailCount="5" SortableColumns="COLUMN_TYPE_NAME" />

Changing the properties by altering the code specifically and changing the properties by utilizing the Properties editorial manager as a part of Visual Studio will bring about precisely the same impact.

For further help or input, please see the Laserfiche Support Site.

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 :: How to Remove the XML Formatter from ASP.NET Web API Applications

clock February 27, 2015 05:36 by author Dan

 

ASP.NET Web API's default yield arrangement should be JSON, yet when I get to my Web APIs utilizing the program location bar I'm continually seeing a XML come about. At the point when chipping away at AJAX application I like to test huge numbers of my AJAX APIs with the program while taking a shot at them. While I can't investigate all demands along  these  lines, GET appeals are anything but difficult to test in the program particularly on the off chance that you have JSON seeing alternatives set up in your different programs.

On the off chance that I review a Web API ask for in many programs I get a XML reaction like this:

Why?

Web API checks the HTTP Accept headers of an appeal to figure out what kind of yield it ought to return by searching for substance wrote that it has formatters enrolled for. This programmed arrangement is one of the immense gimmicks of Web API in light of the fact that it makes it simple and straightforward to demand various types of yield from the server.

On account of programs it just so happens most send Accept headers that resemble this (Chrome for this situation):

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Web API reviews the whole rundown of headers from left to right (in addition to the quality/need banner q=) and tries to discover a media sort that matches its rundown of upheld media sorts in the rundown of formatters enlisted. For this situation it matches application/xml to the Xml formatter thus that is the thing that gets returned and showed.

To check that Web API to be sure defaults to JSON yield as a matter of course you can open the appeal in Fiddler and pop it into the Request Composer, uproot the application/xml header and see that the yield returned returns in JSON.

An accept header like this:

Accept: text/html,application/xhtml+xml,*/*;q=0.9

alternately forgetting the Accept header inside and out ought to provide for you a JSON reaction. Interestingly enough Internet Explorer 9 likewise shows JSON on the grounds that it does exclude an application/xml Accept header:

Accept: text/html, application/xhtml+xml, */*

which for once really appears to be more sensible.

Removing the XML Formatter


We can't without much of a stretch change the program Accept headers (really you can by digging into the config however its a somewhat of a bother), so would we be able to change the conduct on the server? At the point when chipping away at AJAX applications I have a tendency to not be occupied with XML results and I generally need to see JSON results at any rate amid advancement. Web API utilizes a gathering of formatters and you can experience this rundown and uproot the ones you would prefer not to utilize - as a part of this case the XmlMediaTypeFormatter.

To do this you can work with the HttpConfiguration object and the static GlobalConfiguration article used to design it:

    protected void Application_Start(object sender, EventArgs e)
    {

        // Action based routing (used for RPC calls)
        RouteTable.Routes.MapHttpRoute(
            name: "StockApi",
            routeTemplate: "stocks/{action}/{symbol}",
            defaults: new
            {
                symbol = RouteParameter.Optional,
                controller = "StockApi"
            }
        );

        // WebApi Configuration to hook up formatters and message handlers
        RegisterApis(GlobalConfiguration.Configuration);
    }

    public static void RegisterApis(HttpConfiguration config)
    {
        // remove default Xml handler
        var matches = config.Formatters
                            .Where(f => f.SupportedMediaTypes
                                         .Where(m => m.MediaType.ToString() == "application/xml" ||
                                                     m.MediaType.ToString() == "text/xml")
                                         .Count() > 0)
                            .ToList() ;
        foreach (var match in matches)
            config.Formatters.Remove(match);   
    }
}


That LINQ code is very much a bite of settled accumulations, however it does the trap to evacuate the formatter in light of the substance sort. You can likewise search for the particular formatter (XmlMediatTypeFormatter) by its write name which is less complex, however its ideal to hunt down the backed sorts as this will work regardless of the possibility that there are other custom formatters included.

Once evacuated, now the program appeal results in a JSON reaction:

It's a basic answer for a little investigating errand that is made my life simpler. Perhaps you think that it valuable as well.

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