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

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

ASP.NET Hosting - ASPHostPortal.com :: How to Fix ASP.NET Menu Control Cannot Work in Google Chrome

clock May 22, 2015 06:16 by author Dan

Problem

If your website is using ASP.NET Menu Control, the menu part will not work in Google Chrome browser and Apple Safari browser. The look and feel of the main menu is different. Submenu does not show up.

Solution

There is an easy fix for this problem. Just copy and paste the following codes to your page load event of your code behind master page file. You may need to copy it to every page if you do not use master page.

     Partial Class Main
        Inherits System.Web.UI.MasterPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Request.UserAgent.IndexOf("AppleWebKit") > 0 Then
                Request.Browser.Adapters.Clear()
            End If
        End Sub
    End Class

Best ASP.NET Hosting Recommendation

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



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

clock April 20, 2015 05:52 by author Mark

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

  • OAuth 2.0: Open standard for authorization

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

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

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

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

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

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

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

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

Summary

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

Best ASP.NET Hosting Recommendation

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



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

clock April 15, 2015 05:53 by author Mark

State Management in ASP.NET

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

Client-Side State Management

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

Hidden Fields

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

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

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

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

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

View State

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

Enabling and disabling view state

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

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

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

Cookies

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

Types of cookies 

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

Persistent Cookies     

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

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

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

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

Query String

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

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

Server-Side State Management

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

  • Application state
  • Session state
  • Application State

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

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

Storing and Reading information in application state

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

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

Removing information from application state

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

Application.Remove(["MyVariable"]);

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

Application.RemoveAll();  

Synchronizing application state

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

Session State

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

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

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

Session["MyVariable"]="HELLO";     

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

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

Best ASP.NET Hosting Recommendation

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



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

clock April 13, 2015 06:19 by author Ben

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

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

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

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

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

Now please check the code.

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

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

        }

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

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

Now we will develop the folder.


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

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


Best ASP.NET Hosting Recommendation

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



ASP.NET 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 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.




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