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

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

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

clock April 20, 2015 05:52 by author Mark

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

  • OAuth 2.0: Open standard for authorization

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

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

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

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

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

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

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

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

Summary

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

Best ASP.NET Hosting Recommendation

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



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

clock April 15, 2015 05:53 by author Mark

State Management in ASP.NET

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

Client-Side State Management

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

Hidden Fields

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

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

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

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

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

View State

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

Enabling and disabling view state

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

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

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

Cookies

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

Types of cookies 

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

Persistent Cookies     

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

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

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

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

Query String

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

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

Server-Side State Management

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

  • Application state
  • Session state
  • Application State

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

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

Storing and Reading information in application state

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

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

Removing information from application state

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

Application.Remove(["MyVariable"]);

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

Application.RemoveAll();  

Synchronizing application state

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

Session State

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

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

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

Session["MyVariable"]="HELLO";     

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

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

Best ASP.NET Hosting Recommendation

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



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

clock March 18, 2015 06:28 by author Mark

Data Annotations Validation in ASP.NET

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

Creating a Registration Page

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

Registration.aspx

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

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

Validation.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web;   
    //using Namespace 
    using System.ComponentModel.DataAnnotations; 
    namespace DataAnnotationsValidation.Models 
    { 
        public class Validation 
        {         
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string FirstName { get; set; }  
            [Required] 
            [StringLength(120, MinimumLength = 3)] 
            public string LastName { get; set; } 
            [Required] 
            [StringLength(25, MinimumLength = 3)] 
            public string UserID { get; set; } 
            [Required] 
            [DataType(DataType.Password)] 
            public string Password { get; set; } 
            [Required] 
            [Compare("Password")] 
            public string PasswordConfirm { get; set; } 
            [Required] 
            [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")] 
            public int Age { get; set; }   
            [Required]        
            [StringLength(10)] 
            public int Mobile { get; set; }           
            [RegularExpression(@"[A-Za-z0-9._%+-]+@[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 :: How to Convert DataTable To JSON String in ASP.NET

clock February 24, 2015 06:34 by author Mark

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

Step 1

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

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

Step 2

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

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

Step 3

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

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

Step 4

Press F5, run the project.

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

Step 1

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

Step 2

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

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

Step 3

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

using Newtonsoft.Json;

And then:

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

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

Best ASP.NET Hosting Recommendation

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



ASP.NET Hosting - ASPHostPortal.com :: Key Points of ASP.NET VNext

clock February 12, 2015 05:58 by author Mark

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

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

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

Summary

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

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



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

clock February 5, 2015 06:45 by author Mark

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

Overview

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

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

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

Why Caching

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

The process

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

Multiple sorts of pages

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

What a Cache does

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

Types

Page Caching

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

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

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

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

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

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

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

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

Or:

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

Fragment caching

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

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

Or:

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

Data Caching

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

I am inserting a string value in the cache as:

Cache["Website"] = "CSharpCorner"; 

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

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

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

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

Happy coding!

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



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

clock January 28, 2015 05:47 by author Ben

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


return View()

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


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


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

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

}

return RedirectToAction()

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


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


return Redirect()

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


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


return RedirectToRoute()

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

Defined Route


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


HomeController

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

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

AccountController

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

Best ASP.NET Hosting Recommendation

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



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

clock January 27, 2015 05:36 by author Mark

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

Diagram of Web API Pipeline

Hosting of web API

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

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

HTTP Message Handler

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

Delegating Handler

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

Routing Dispatcher

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

Controllers

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

Authorization Filter

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

Model Binding

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

View of Model Binding

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

 

URI

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

Formatter Binding

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

HTTP parameter binding

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

Action Filter

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

Action Invoker

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

Controller Action

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

Result Conversion

Now we see the image of the Result Conversion:

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

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

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.




ASP.NET Hosting - ASPHostPortal :: How to Disable Cut, Copy and Paste in the Entire ASP.NET Web Form

clock January 22, 2015 06:22 by author Mark

This article shows how to restrict the use of cut, copy and paste by the end user in the whole page.

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

Step 1

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

Step 2

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

Step 3

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

Step 4

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


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


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

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

Conclusion

In this article, I have described how to restrict the user to use the cut, copy and paste facilities in the entire page and I hope it will be beneficial for you.

TOP No#1 Recommended ASP.NET MVC 5 Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET MVC Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET Hosting - ASPHostPortal :: How To Show Data In Doughnut Chart Using ASP.NET

clock January 15, 2015 06:49 by author Mark

Doughnut Chart In ASP.Net

Today i will explains about how to show data in doughnut chart. In this article we will learn about the Doughnut Chart of ASP.Net.
what's Donut or Doughnut chart?? Donut or Doughnut chart is just a simple pie chart with a hole inside. You can define hole radius to any size you need, both in percent or pixels. Sometimes we need to show data in a chart like a Doughnut chart, such as to show quarterly data and on, so by considering the preceding requirement and to introduce the ASP.Net Doughnut Chart controls I have decided to write this article.

Let us learn about the ASP.Net chart type Doughnut chart that provides a powerful UI and great design quality. We will learn about these chart type controls step-by-step. All the charts are in the System.Web.UI.DataVisualization.Charting namespace.
The chart data is represented using the following points:

  • X Axis: the horizontal line of the chart termed the X axis
  • Y Axis: the vertical line of the chart termed the Y axis

Now let us learn about the properties of the Doughnut chart. A Doughnut chart type has the following common properties:

  • AlternetText: Sets the alternate text when the image is not available.
  • Annotation: Stores the chart annotations.
  • AntiAliasing: sets a value that determines whether anti-aliasing is used when text and graphics are drawn.
  • BackGradientStyle: sets the orientation for the background gradient for the Chart control. Also determines whether a gradient is used, the default is None.
  • Backcolor: sets the background color for a chart, the default color is White.
  • BackImage: sets the background image for the chart control.
  • BackHatchStyle: sets the hatching style for the chart control, the default is None.
  • Height: Sets the height for the chart control.
  • Width: Sets the width for the chart control.
  • Palette: Sets the style with the color for the chart control, the default style is Chocolate.
  • PaletteCustomColors: Sets the custom color for the chart control.
  • Series: Sets the series collection for the chart control.
  • Legends: Sets the series of legends to the chart.

Now let us show the preceding explanation with a practical example by creating a simple web application.

Step 1: Create the table for the chart data

  • Now before creating the application, let us create a table named QuarterwiseSale in a database from where we show the records in the chart using the following script:

CREATE TABLE [dbo].[QuarterwiseSale](    
    [id] [int] IDENTITY(1,1) NOT NULL,    
    [Quarter] [varchar](50) NULL,    
    [SalesValue] [money] NULL,    
 CONSTRAINT [PK_QuarterwiseSale] PRIMARY KEY CLUSTERED     
    (    
    [id] ASC    
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
    ) ON [PRIMARY]   

  • The table has the following fields (shown in the following image): 
  • Now insert some records using the following script: 

SET IDENTITY_INSERT [dbo].[QuarterwiseSale] ON          
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (1, N'Q1', 100.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (2, N'Q2', 50.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (3, N'Q3', 150.0000)    
    GO    
    INSERT [dbo].[QuarterwiseSale] ([id], [Quarter], [SalesValue]) VALUES     (4, N'Q4', 200.0000)    
    GO    
    SET IDENTITY_INSERT [dbo].[QuarterwiseSale] OFF    
    GO   

Now the records will look as in the following image:
Now create the Stored Procedure to fetch the records from the database as in the following:

Create Procedure [dbo].[GetSaleData]    
    (    
    @id int=null             
    )    
    as    
    begin    
    Select Quarter,SalesValue from QuarterwiseSale    
    End 
  

I hope you have the same type of table and records as above.

Step: 2 Create Web Application

  • Now create the project using the following:
  • "Start" - "All Programs" - "Microsoft Visual Studio 2013".
  • "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  • Provide the project a name such as UsingDoughnutChart or another as you wish and specify the location.
  • Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.
  • Drag and Drop a Chart control from the ToolBox onto the Default.aspx page.
  • Now the Default.aspx source code will be as follows:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>         
    <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
        Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>  
    <!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>Article by Vithal Wadje</title>  
    </head>  
    <body bgcolor="silver">  
        <form id="form1" runat="server">  
        <h4 style="color: Navy;">  
            Article for C#Corner  
        </h4>  
        <asp:Chart ID="Chart1" runat="server" BackColor="0, 0, 64" BackGradientStyle="LeftRight"  
            BorderlineWidth="0" Height="360px" Palette="None" PaletteCustomColors="Maroon"  
            Width="380px" BorderlineColor="64, 0, 64">  
            <Titles>  
                <asp:Title ShadowOffset="10" Name="Items" />  
            </Titles>  
            <Legends>  
                <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default"  
                    LegendStyle="Row" />  
            </Legends>  
            <Series>  
                <asp:Series Name="Default" />  
            </Series>  
            <ChartAreas>  
                <asp:ChartArea Name="ChartArea1" BorderWidth="0" />  
            </ChartAreas>  
        </asp:Chart>  
        </form>  
    </body>  
    </html> 

  • Create a method to bind the chart control. Then open the default.aspx.cs page and create the following function named Bindchart to bind the Chart Control as in the following:

private void Bindchart()  
        {  
            connection();  
            com = new SqlCommand("GetSaleData", con);  
            com.CommandType = CommandType.StoredProcedure;  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds);         
            DataTable ChartData = ds.Tables[0];  
            //storing total rows count to loop on each Record  
            string[] XPointMember = new string[ChartData.Rows.Count];  
            int[] YPointMember = new int[ChartData.Rows.Count];         
            for (int count = 0; count < ChartData.Rows.Count; count++)  
            {  
                //storing Values for X axis  
                XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
                //storing values for Y Axis  
                YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);  
            }  
            //binding chart control  
            Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);         
            //Setting width of line  
            Chart1.Series[0].BorderWidth = 10;  
            //setting Chart type   
            Chart1.Series[0].ChartType = SeriesChartType.Doughnut;       
            foreach (Series charts in Chart1.Series)  
            {  
                foreach (DataPoint point in charts.Points)  
                {  
                    switch (point.AxisLabel)  
                    {  
                        case "Q1": point.Color = Color.YellowGreen; break 
                        case "Q2": point.Color = Color.Yellow; break;  
                        case "Q3": point.Color = Color.SpringGreen; break;
                    }  
                    point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);         
                }  
            }           
            //Enabled 3D  
          //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            con.Close();         
        } 

Note that we have written a small code snippet to provide the different color for each point as in the following:

//To give different color for each point             
    foreach (Series charts in Chart1.Series)      
           {      
               foreach (DataPoint point in charts.Points)      
               {      
                   switch (point.AxisLabel)      
                   {      
                       case "Q1": point.Color = Color.RoyalBlue; break;   
                       case "Q2": point.Color = Color.SaddleBrown; break; 
                       case "Q3": point.Color = Color.SpringGreen; break; 
                   }      
                   point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);                
               }      
           }       

  • Now, call the preceding function on page load as in the following:

protected void Page_Load(object sender, EventArgs e)      
        {      
            if (!IsPostBack)      
            {      
                Bindchart();                 
            }      
        }  
  

  • The entire code of the default.aspx.cs page will look as follows:

      using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
    using System.Data.SqlClient;  
    using System.Configuration;  
    using System.Data;  
    using System.Web.UI.DataVisualization.Charting;  
    using System.Drawing;         
    public partial class _Default : System.Web.UI.Page  
    {  
        private SqlConnection con;  
        private SqlCommand com;  
        private string constr, query;  
        private void connection()  
        {  
            constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
            con = new SqlConnection(constr);  
            con.Open();  
               }  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!IsPostBack)  
            {  
                Bindchart();    
            }  
        }     
        private void Bindchart()  
        {  
            connection();  
            com = new SqlCommand("GetSaleData", con);  
            com.CommandType = CommandType.StoredProcedure;  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds);         
            DataTable ChartData = ds.Tables[0];         
            //storing total rows count to loop on each Record  
            string[] XPointMember = new string[ChartData.Rows.Count];  
            int[] YPointMember = new int[ChartData.Rows.Count];         
            for (int count = 0; count < ChartData.Rows.Count; count++)  
            {  
                //storing Values for X axis  
                XPointMember[count] = ChartData.Rows[count]["Quarter"].ToString();  
                //storing values for Y Axis  
                YPointMember[count] = Convert.ToInt32(ChartData.Rows[count]["SalesValue"]);         
            }  
            //binding chart control  
            Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);         
            //Setting width of line  
            Chart1.Series[0].BorderWidth = 10;  
            //setting Chart type   
            Chart1.Series[0].ChartType = SeriesChartType.Doughnut;      
            foreach (Series charts in Chart1.Series)  
            {  
                foreach (DataPoint point in charts.Points)  
                {  
                    switch (point.AxisLabel)  
                    {  
                        case "Q1": point.Color = Color.YellowGreen; break 
                        case "Q2": point.Color = Color.Yellow; break;  
                        case "Q3": point.Color = Color.SpringGreen; break;
                    }  
                    point.Label = string.Format("{0:0} - {1}", point.YValues[0], point.AxisLabel);  
                }  
            }    
            //Enabled 3D  
          //  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;  
            con.Close();  
        }  
    } 

We now have the entire logic to bind the chart from the database, let us run the application. The chart will look as follows:

I hope this article work for you.

TOP No#1 Recommended ASP.NET 5 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.



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