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 4.5 Hosting - ASPHostPortal.com :: Add Multiple Files Utilizing ASP.NET 4.5

clock November 28, 2014 05:07 by author Ben

In earlier versions of ASP.NET (edition under ASP.NET 4.5), we didn't have any inbuilt functionality to add several files at the same time. ASP.NET FileUpload handle permits uploading just one file in a time. Alternate answers to add numerous files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to attain comparable performance.


In ASP.NET 4.5, we can add multiple documents simultaneously making use of ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 several attribute.

Under are the steps to add numerous information utilizing ASP.NET 4.5 :

  1. In Visual Studio 2012, In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:

<asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
</asp:fileupload>

In above code, I have set AllowMultiple property of FileUpload Control to true.

Add one button to upload multiple files using FileUpload Control on button click.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

Write below code on button click event handler.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (MultipleFileUpload.HasFiles)
        {
            StringBuilder UploadedFileNames = new StringBuilder();

            foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
            {
                string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                UploadedFileNames.AppendFormat("{0}<br />", FileName);
            }
            Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
        }
    }

On button click, I am checking for multiple files and saving those files into Files folder of web application.
Compile source code and run the website application.

 

I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder.



ASPHostPortal.com to Launch New Data Center in Hong Kong

clock November 25, 2014 08:10 by author Ben

ASPHostPortal.com to Start New Data Center in Hong Kong on November 2014

ASPHostPortal is known for credible and loyal hosting solutions. Apart from the reliability in the ASPHostPortal Uptime, which features 99.9 per cent common uptime, ASPHostPortal also provides outstanding data center which displays ASPHostPortal large speed and large overall performance web hosting package deal. Lately, ASPHostPortal.com launch its new Data Center in Hons Kong on November 2014 with space for more than 10.000 physical servers, and allowing customers’ to satisfy their  data residency needs.

The brand new facility will provide consumers and their finish customers with ASPHostPortal.com providers that meet up with in-country info residency needs. It will also complement the existing ASPHostPortal.com Asia (Singapore) Data Center. The Hong Kong Data Center will offer the full variety of ASPHostPortal.com website hosting infrastructure services, which includes bare steel servers, virtual servers, storage and networking.

ASPHostPortal offers the perfect mixture of affordability and dependability. They have an excellent uptime history with numerous months this 12 months boasting a lot more than 99.9% typical uptime. Their hosting bundle displays velocity and efficiency. Their information heart might take significantly from the credit rating for such superb providers. The brand new data center will allow clients to copy or integrate data between Asia Data Center with higher transfer speeds and unmetered bandwidth (at no charge) in between amenities.

“With ASPHostPortal, picking the Data Center area is really a totally free function and alternative to all consumers. The shopper just chooses US, Europe, Asia or Australia. It is straightforward, intuitive and convenient. The choice is totally free, and there will never be any other cost to the person related with this choice,” said Dean Thomas, Manager at ASPHostPortal.com.

Customers that have any questions on the feature and also the choice which is most suitable for his or her functions ought to truly feel totally free to get in touch with ASPHostPortal via their 24/7/365 customer assistance crew. ASPHostPortal may help you select the right choice that will best fit your needs.

To find out more about new data center in Hong Kong, please visit http://asphostportal.com/Hosting-Data-Center-HongKong.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting business that greatest support in Windows and ASP.NET-based hosting. Solutions consist of shared web hosting, reseller hosting, and SharePoint hosting, with specialty in ASP.NET, SQL Server, and architecting very scalable solutions. Like a top little to mid-sized company web hosting provider, ASPHostPortal.com attempt to supply essentially the most technologically advanced hosting options obtainable to all customers across the world. Security, reliability, and efficiency are in the core of web hosting operations to make certain every site and/or software hosted is extremely secured and performs at ideal stage.

 



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Structure The Application in ASP.NET MVC Areas

clock November 25, 2014 05:11 by author Ben

This week I discovered a difficulty related to structuring an ASP.NET MVC web applications one advancement crew was dealing with. The things they have been trying to do was quite straightforward: to create a folder framework each having their particular subfolders for View/Controller/Scripts/CSS and so on. The appliance assets like JS/CSS etc. were not getting rendered properly. The difficulty was owing to NET.config file lying underneath the subfolder, which when moved to the Views folder below that subfolder things went good. The purpose of this post just isn't to debate regarding the specifics of that difficulty and it is solution.But to discuss regarding how we will very easily framework our ASP.NET MVC Web application as per distinct modules, which is an clear need for just about any big application.


ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions operates good to get a smaller sized software. But for relatively bigger a single there is a necessity to customise.The framework also offers adequate provisions for the same.You'll be able to have your personal controller manufacturing facility to get custom methods to making the controller classes and custom see engine for finding the rendering the sights. But when the necessity would be to structure the applying to distinct subfolders as per modules or subsites I believe using “Area” in ASP.NET MVC will likely be useful to make a streamlined software.

You can add a area to some ASP.NET MVC undertaking in Visual Studio as shown beneath.

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Sales";
        }
    }
 
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Sales_default",
            "Sales/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

System.Web.Mvc.AreaRegistration may be the summary base class use registering the places to the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) must be overriden to sign up the realm by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the mandatory information (like Routes) required to sign-up the area.

In Global.asax.cs Application_Start occasion we must RegisterAllAreas() technique as demonstrated under:

AreaRegistration.RegisterAllAreas();

The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults
                new String[] { "AreasDemo.Controllers" }
            );
}

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);



ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Export Data from SQL Server to Excel in ASP.net using c#

clock November 24, 2014 06:26 by author Mark

Introduction:

Here I will explain how to export data from sql server to excel in asp.net using c# or export data from sql server database to excel in asp.net using c#.

Description:

Now I will explain to you, how to export data from sql server to excel in asp.net using c#.
Before implement this example first design one table UserInformation in your database as shown below
Once table created in database enter some dummy data to test application after that write the following code in your aspx page

Column Name

Data Type

Allow Nulls

UserId

int

Yes

UserName

varchar(50)

Yes

Location

varchar(50)

Yes

<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Export data from sql server database to excel in asp.net using c#</title>
  </head>
      <body>
      <form id="form1" runat="server">
         <div>
            <asp:Button ID="btnExport" Text="Export Data" runat="server" onclick="btnExport_Click" />
         </div>
       </form>

      </body>
</html>

Now open code behind file and write the following code :  

using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        DataTable dt = GetDatafromDatabase();
        string str = string.Empty;
        foreach (DataColumn dtcol in dt.Columns)
        {
            Response.Write(str + dtcol.ColumnName);
            str = "\t";
        }
        Response.Write("\n");
        foreach (DataRow dr in dt.Rows)
        {
            str = "";
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                Response.Write(str + Convert.ToString(dr[j]));
                str = "\t";
            }
            Response.Write("\n");
        }
        Response.End();
    }
    protected DataTable GetDatafromDatabase()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select TOP 10 UserName,LastName,Location FROM UserInformation", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
        }
        return dt;
    }
}

VB.NET
Imports System.Data
Imports System.Data.SqlClient
Partial Class VBCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub
    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
        Response.ClearContent()
        Response.Buffer = True
        Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
        Response.ContentType = "application/ms-excel"
        Dim dt As DataTable = GetDatafromDatabase()
        Dim str As String = String.Empty
        For Each dtcol As DataColumn In dt.Columns
            Response.Write(str + dtcol.ColumnName)
            str = vbTab
        Next
        Response.Write(vbLf)
        For Each dr As DataRow In dt.Rows
            str = ""
            For j As Integer = 0 To dt.Columns.Count - 1
                Response.Write(str & Convert.ToString(dr(j)))
                str = vbTab
            Next
            Response.Write(vbLf)
        Next
        Response.[End]()
    End Sub
    Protected Function GetDatafromDatabase() As DataTable
        Dim dt As New DataTable()
        Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
            con.Open()
            Dim cmd As New SqlCommand("Select TOP 10 UserName,LastName,Location FROM UserInformation", con)
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            con.Close()
        End Using
        Return dt
    End Function
End Class



ASP.NET 4.5 HOSTING - ASPHostPortal :: How to Create Nested WebGrid in ASP.NET MVC6.

clock November 19, 2014 05:51 by author Mark

How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.

Introduction

In this post, I am explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC6.
Steps :

Step - 1 : Create New Project.

  • Go to File > New > Project > Select asp.net MVC6 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

  • Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

  • Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > OK.

In this example, I have used two tables as below

Step-4: Add Entity Data Model.

  • Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
  • A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
  • Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a class for create a view model.

  • 1st : Add a folder.
  • Go to Solution Explorer > Right Click on the project > add > new folder.
  • 2nd : Add a class on that folder
  • Go to Solution Explorer > Right Click on that folder > Add > Class... > Enter Class name > Add.

Write the following code in this class

using System.Collections.Generic;
namespace MVCNestedWebgrid.ViewModel
{
    public class OrderVM
    {
        public OrderMaster order { get; set; }
        public List<OrderDetail> orderDetails { get; set; }
    }
}

Step-6: Add a new Controller.

  • Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show nested data in a webgrid.

Here I have added "List" Action into "Order" Controller. Please write this following code

public ActionResult List()
{
    List<OrderVM> allOrder = new List<OrderVM>();
 
    // here MyDatabaseEntities is our data context
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var o = dc.OrderMasters.OrderByDescending(a => a.OrderID);
        foreach (var i in o)
        {
            var od = dc.OrderDetails.Where(a => a.OrderID.Equals(i.OrderID)).ToList();
            allOrder.Add(new OrderVM { order= i, orderDetails = od });
        }
    }
    return View(allOrder);
}

Step-8: Add view for the Action & design.

  • Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

NOTE " Please Rebuild solution before add view

Html Code
@model IEnumerable<MVCNestedWebgrid.ViewModel.OrderVM>

@{
    ViewBag.Title = "Order List";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
<div id="main" style="padding:25px; background-color:white;">
    @grid.GetHtml(
    htmlAttributes: new {id="gridT", width="700px" },
    columns:grid.Columns(
            grid.Column("order.OrderID","Order ID"),
            grid.Column(header:"Order Date",format:(item)=> string.Format("{0:dd-MM-yyyy}",item.order.OrderDate)),
            grid.Column("order.CustomerName","Customer Name"),
            grid.Column("order.CustomerAddress","Address"),
            grid.Column(format:(item)=>{
                WebGrid subGrid = new WebGrid(source: item.orderDetails);
                return subGrid.GetHtml(
                    htmlAttributes: new { id="subT" },
                    columns:subGrid.Columns(
                            subGrid.Column("Product","Product"),
                            subGrid.Column("Quantity", "Quantity"),
                            subGrid.Column("Rate", "Rate"),
                            subGrid.Column("Amount", "Amount")
                        )                   
                    );
            })
        )
    )
</div>
Css Code
<style>
th, td {
        padding:5px;
    }
    th
    {
        background-color:rgb(248, 248, 248);       
    }
    #gridT,  #gridT tr {
        border:1px solid #0D857B;
    }
    #subT,#subT tr {
        border:1px solid #f3f3f3;
    }
    #subT {
        margin:0px 0px 0px 10px;
        padding:5px;
        width:95%;
    }
    #subT th {
        font-size:12px;
    }
    .hoverEff {
        cursor:pointer;
    }
    .hoverEff:hover {
        background-color:rgb(248, 242, 242);
    }
    .expand {
        background-image: url(/Images/pm.png);
        background-position-x: -22px;
        background-repeat:no-repeat;
    }
    .collapse  {
        background-image: url(/Images/pm.png);
        background-position-x: -2px;
        background-repeat:no-repeat;
    }
</style>
Write the following Jquery code for make webgrid collapsible
<script>
    $(document).ready(function () {
        var size = $("#main #gridT > thead > tr >th").size(); // get total column
        $("#main #gridT > thead > tr >th").last().remove(); // remove last column
        $("#main #gridT > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
        $("#main #gridT > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td></td>")
                    .addClass("expand")
                    .addClass("hoverEff")
                    .attr('title',"click for show/hide")
                );
            //Now get sub table from last column and add this to the next new added row
            var table = $("table", this).parent().html();
            //add new row with this subtable
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            // ADD CLICK EVENT FOR MAKE COLLAPSIBLE
            $(".hoverEff", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });
        //by default make all subgrid in collapse mode
        $("#main #gridT > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });    
    });
</script>



ASP.NET 4.5 HOSTING - ASPHostPortal.com | How to Create Dynamic GridView Control in C#/ASP.Net

clock November 18, 2014 06:54 by author Dan

Introduction

In webapplications, one the most widely task is showing a table of information to clients. In Asp.net, we make utilization of the Datagrid, Datalist and Repeater controls. Every day, the need of showing the information will be diverse. Now, we will explain to you about "How to Create Dynamic GridView Control in C#/ASP.Net". Please read the steps carefully.

Implementing Dynamic GridView Control

Utilizing the gridview to show the articles will show the article a little in diverse layout when compared with Datalist. Appoint the below figure, Dynamic Gridview.

Constructing Dynamic GridView

Showing the articles in gridview will be different from showing in datalist. For that, i have made two Template classes :

  • DynamicGridViewTextTemplate
  • DynamicGridViewURLTemplate

Dynamicgridviewtexttemplate class is utilized to include a layout column with label while Dynamicgridviewurltemplate class is utilized to include URL of the article.

TemplateClass for GridView

public class DynamicGridViewTextTemplate : ITemplate
{
    string _ColName;
    DataControlRowType _rowType;
    int _Count;
    public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
    {
        _ColName = ColName;
        _rowType = RowType;
    }
    public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)
    {
        _rowType = RowType;
        _Count = ArticleCount;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColName + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:              
                 Label lbl = new Label();
                 lbl.DataBinding += new EventHandler(this.lbl_DataBind);
                 container.Controls.Add(lbl);              
                break;
            case DataControlRowType.Footer:
                Literal flc = new Literal();
                flc.Text = "<b>Total No of Articles:" + _Count + "</b>";
                container.Controls.Add(flc);
                break;
            default:
                break;
        }
    }
 
  
    private void lbl_DataBind(Object sender, EventArgs e)
    {
        Label lbl  = (Label)sender;
        GridViewRow row = (GridViewRow)lbl.NamingContainer;
        lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();
    }
 
}
public class DynamicGridViewURLTemplate : ITemplate
{
    string _ColNameText;
    string _ColNameURL;
    DataControlRowType _rowType;
 
    public DynamicGridViewURLTemplate(string ColNameText, string ColNameURL, DataControlRowType RowType)
    {
        _ColNameText = ColNameText;
        _rowType = RowType;
        _ColNameURL = ColNameURL;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + _ColNameURL + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink hpl = new HyperLink();
                hpl.Target = "_blank";
                hpl.DataBinding += new EventHandler(this.hpl_DataBind);
                container.Controls.Add(hpl);
                break;
            default:
                break;
        }
    }
 
    private void hpl_DataBind(Object sender, EventArgs e)
    {
        HyperLink hpl = (HyperLink)sender;
        GridViewRow row = (GridViewRow)hpl.NamingContainer;
        hpl.NavigateUrl = DataBinder.Eval(row.DataItem, _ColNameURL).ToString();
        hpl.Text = "<div class=\"Post\"><div class=\"PostTitle\">" + DataBinder.Eval(row.DataItem, _ColNameText).ToString() + "</div></div>";
    }
}

Using the Template Class in GridView

Utilizing dynamic template in gridview is not the same as datalist i.e. we will make the dynamic gridview in column wise with header layout, item template and footer layout from the first column till the last.

Steps:

  1. Create a Gridview Object.
  2. Create an instance of TemplateField object.
  3. Instantiate the Dynamic template class with proper ListItemType and assign it to corresponding template property of TemplateField object and finally add this object to the column collection of GridView. Refer the below code for better understanding.

Templates of GridView

TemplateField tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count); 

In the event that you analyze the usage of Datalist, in Gridview we won't make dynamic template for the grid within we make it for the grid's column (Templatefield). Appoint the below code (Using Template class) for clear understanding.

Using Template class

for (int i = 0; i < ds.Tables.Count; i++)
        {
            if (ds.Tables[i].Rows.Count > 0)
            {
                GridView gvDynamicArticle = new GridView();
                gvDynamicArticle.Width = Unit.Pixel(700);
                gvDynamicArticle.BorderWidth = Unit.Pixel(0);
                gvDynamicArticle.Caption = "<div id=\"nifty\" class=\"PostCategory\"> + ds.Tables[i].Rows[0]["Category"].ToString() + " Articles</div>";
                gvDynamicArticle.AutoGenerateColumns = false;
                gvDynamicArticle.ShowFooter = true;
                TemplateField tf = null;
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count);               
              
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
                tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("Author", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("CreatedBy", DataControlRowType.DataRow);
                gvDynamicArticle.Columns.Add(tf);
 
 
                gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(this.DynamicGrid_RowDataBound);
 
                gvDynamicArticle.DataSource = ds.Tables[i];
                gvDynamicArticle.DataBind();
                phDynamicGridHolder.Controls.Add(gvDynamicArticle);
            }
        }
In the above code (Using Template class), we can unmistakably comprehend that we are making the dynamic template for the gridview's column instead of Datalist where we made the template for the grid itself. To throw more light on this it implies that we are making the first column's header, item and footer and adding it to the gridview's column list through Templatefield article till the last column as I said before.


ASP.NET 4.5 HOSTING - ASPHostPortal :: How make Single Page CRUD Application (SPA) using ASP.NET Web API, MVC and Angular.js

clock November 17, 2014 07:41 by author Mark

How make Single Page CRUD Application (SPA) using ASP.NET Web API, MVC and Angular.js ??

A Single Page Application (SPA) is a web application that fits on a single web page. In this type of application, the server provides static HTML views, CSS and JavaScript and the application then loads data by making Ajax calls to the server. All subsequent views and navigation occurs without a postback to the server. This architecture provides a more fluid user experience just like a desktop application.
In this article, we will create a SPA using ASP.NET MVC, WEB API and Angular.js. Angular.js is a Model-View-* JavaScript based framework for developing SPA applications. Similarly ASP.NET Web API is a good fit for providing data for these type of applications.

  • First Download Hundreds of UI Controls for ASP.NET/MVC, WinForms - Free Trial
  • To create this application, you can use the free new Visual Studio Community 2013
  • Step 1: Open Visual Studio 2013 and create a new Empty MVC application. Name it as ‘MVC_Using_Angular’. In this MVC project,
  • Add a new Sql Server database with the name ‘Company.mdf’. In the database add a new EmployeeInfo table with the following script:

CREATE TABLE [dbo].[EmployeeInfo] (
    [EmpNo]       INT          IDENTITY (1, 1) NOT NULL,
    [EmpName]     VARCHAR (50) NOT NULL,
    [Salary]      DECIMAL (18) NOT NULL,
    [DeptName]    VARCHAR (50) NOT NULL,
    [Designation] VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);

  • Step 2: In the project, add Angular.js scripts using NuGet Package Manager. This will create a new ‘Scripts’ folder in the project, with Angular.js scripts in it.
  • Step 3: To create a model, right-click on the Models folder and add a new ADO.NET Entity Model with the name CompanyEDMX. Select the Database First approach. Select Company.mdf in the Wizard and then the EmployeeInfo table.
  • Step 4: In the Controllers folder, add a new WEB API 2 Controller with actions. Using Entity Framework, select the Model as EmployeeInfo and Context class as CompanyEntities. Name the API controller as EmployeeInfoAPIController. This will generate methods for performing GET, POST, PUT and DELETE operations.
  • Step 5: In the Controllers folder, add an empty MVC controller of the name EmployeeInfo Controller. This controller will have an ‘Index’ action method in it. To add a new Index View, right-click on the Index action method and add an Empty View without Model. In our SPA, we will use the Index.cshtml as a container for dynamically displaying all views. In the EmployeeInfo sub-folder of the Views folder, add an empty partial views for performing various operations. These views will have the following names:

ShowEmployees.cshtml - show all Employees.
AddEmployee.cshtml - allow to add new Employee.
EditEmployee.cshtml - allow to edit an Employee.
DeleteEmployee.cshtml - used to delete selected Employee.

  • Step 6: Open EmployeeInfo Controller and add the following Action Methods in it:

public ActionResult AddNewEmployee()
{
    return PartialView("AddEmployee");
}
public ActionResult ShowEmployees()
{
    return PartialView("ShowEmployees");
}
public ActionResult EditEmployee()
{
    return PartialView("EditEmployee");
}
public ActionResult DeleteEmployee()
{
    return PartialView("DeleteEmployee");
}

The above action methods returns Partial Views added in the Step 5.
Step 7: Now its’ time for us to add the necessary client-side logic for performing operations using WEB API. In the project, add a new folder of the name ‘MyScripts’. In this folder add a new JavaScript file of name ‘Module.js’.
var app = angular.module("ApplicationModule", ["ngRoute"]);


//The Factory used to define the value to
//Communicate and pass data across controllers
app.factory("ShareData", function () {
return { value: 0 }
});
//Defining Routing
app.config(['$routeProvider','$locationProvider', function ($routeProvider,$locationProvider) {
$routeProvider.when('/showemployees',
{
    templateUrl: 'EmployeeInfo/ShowEmployees',
    controller: 'ShowEmployeesController'
});
$routeProvider.when('/addemployee',
{
    templateUrl: 'EmployeeInfo/AddNewEmployee',
    controller: 'AddEmployeeController'
});
$routeProvider.when("/editemployee",
{
    templateUrl: 'EmployeeInfo/EditEmployee',
    controller: 'EditEmployeeController'
});
$routeProvider.when('/deleteemployee',
{
    templateUrl: 'EmployeeInfo/DeleteEmployee',
    controller: 'DeleteEmployeeController'
});
$routeProvider.otherwise(
{
    redirectTo: '/'
});
// $locationProvider.html5Mode(true);
$locationProvider.html5Mode(true).hashPrefix('!')
}]);

  • The above code defines module of name ‘ApplicationModule’. The module defines factory of name ‘ShareData’, which is used to communicate and pass data across controllers. The module also defines routing expressions using $routeProvider.
  • Step 8: In this step, we will add an Angular Service to encapsulate call to WEB API for performing CRUD operations. The code is as follows:

app.service("SinglePageCRUDService", function ($http) {
//Function to Read All Employees
this.getEmployees = function () {
    return $http.get("/api/EmployeeInfoAPI");
};
//Fundction to Read Employee based upon id
this.getEmployee = function (id) {
    return $http.get("/api/EmployeeInfoAPI/" + id);
};
//Function to create new Employee
this.post = function (Employee) {
    var request = $http({
        method: "post",
        url: "/api/EmployeeInfoAPI",
        data: Employee
    });
    return request;
};
//Function  to Edit Employee based upon id
this.put = function (id,Employee) {
    var request = $http({
        method: "put",
        url: "/api/EmployeeInfoAPI/" + id,
        data: Employee
    });
    return request;
};
//Function to Delete Employee based upon id
this.delete = function (id) {
    var request = $http({
        method: "delete",
        url: "/api/EmployeeInfoAPI/" + id
    });
    return request;
};
});

The service has an $http dependency to perform HTTP GET, POST, PUT and DELETE operations.

  • Step 9: Now its time for us to add Angular controllers used for performing CRUD operations. We will add controllers to make call to the Angular service which we created in the Step 8.

ShowEmployeesController.js
//The controller has dependency upon the Service and ShareData
app.controller('ShowEmployeesController', function ($scope, $location, SinglePageCRUDService, ShareData) {
loadRecords();
//Function to Load all Employees Records. 
function loadRecords()
{
    var promiseGetEmployees = SinglePageCRUDService.getEmployees();
    promiseGetEmployees.then(function (pl) { $scope.Employees = pl.data },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
}
//Method to route to the addemployee
$scope.addEmployee = function () {
    $location.path("/addemployee");
}
//Method to route to the editEmployee
//The EmpNo passed to this method is further set to the ShareData.
//This value can then be used to communicate across the Controllers
$scope.editEmployee = function (EmpNo) {
    ShareData.value = EmpNo;
    $location.path("/editemployee");
}
//Method to route to the deleteEmployee
//The EmpNo passed to this method is further set to the ShareData.
//This value can then be used to communicate across the Controllers
$scope.deleteEmployee = function (EmpNo) {
    ShareData.value = EmpNo;
    $location.path("/deleteemployee");
}
});

The above controller is used to make call to SinglePageCRUDService using ‘loadRecords()’ function. This function make use of Promise object to manage asynchronous call to the service. The retrieved data is then saved in the $scope.Employees object, which is this then passed to the View. Functions addEmployee, editEmployee and deleteEmployee are used to Create, Edit and Delete employee respectively. $location is used to load the corresponding view based upon the route defined in the Module.
AddEmpController.js
app.controller('AddEmployeeController', function ($scope, SinglePageCRUDService) {
$scope.EmpNo = 0;
//The Save scope method used to define the Employee object and
//post the Employee information to the server by making call to the Service
$scope.save = function () {
    var Employee = {
        EmpNo: $scope.EmpNo,
        EmpName: $scope.EmpName,
        Salary: $scope.Salary,
        DeptName: $scope.DeptName,
        Designation: $scope.Designation
    };
    var promisePost = SinglePageCRUDService.post(Employee);
    promisePost.then(function (pl) {
        $scope.EmpNo = pl.data.EmpNo;
        alert("EmpNo " + pl.data.EmpNo);
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
};
});
The above ‘AddEmployeeController’, is dependent on the ‘SinglePageCRUDService’. The function ‘save’ makes call to the post() function service to post Employee object.
EditEmployeeController.js
app.controller("EditEmployeeController", function ($scope, $location,ShareData,SinglePageCRUDService) {
getEmployee();
function getEmployee() {
var promiseGetEmployee = SinglePageCRUDService.getEmployee(ShareData.value);
promiseGetEmployee.then(function (pl)
{
    $scope.Employee = pl.data;
},
      function (errorPl) {
          $scope.error = 'failure loading Employee', errorPl;
      });
}
//The Save method used to make HTTP PUT call to the WEB API to update the record
$scope.save = function () {
var Employee = {
    EmpNo: $scope.Employee.EmpNo,
    EmpName: $scope.Employee.EmpName,
    Salary: $scope.Employee.Salary,
    DeptName: $scope.Employee.DeptName,
    Designation: $scope.Employee.Designation
};
var promisePutEmployee = SinglePageCRUDService.put($scope.Employee.EmpNo,Employee);
promisePutEmployee.then(function (pl)
{
    $location.path("/showemployee");
},
      function (errorPl) {
          $scope.error = 'failure loading Employee', errorPl;
      });
};
});

The above ‘EditEmployeeController’ is dependent on the ‘SinglePageCRUDService’ and ‘ShareData’ factory. The function getEmployee(), makes call to the getEmployee() function of the service and passes the ShareData.value to it. This is the EmpNo passed from the editEmployee() function from the ShowEmployeesController.
The function save() is used to make call to the put() function of the service by passing EmpNo and the Employee object to complete an edit operation. Both the save() and getEmployee() functions make use of promise object to manage asynchronous calls to angular service.
DeleteEmployeeController.js
app.controller("DeleteEmployeeController", function ($scope, $location, ShareData, SinglePageCRUDService) {
getEmployee();
function getEmployee() {
    var promiseGetEmployee = SinglePageCRUDService.getEmployee(ShareData.value);
    promiseGetEmployee.then(function (pl) {
        $scope.Employee = pl.data;
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
}

//The delete method used to make HTTP DELETE call to the WEB API to update the record
$scope.delete = function () {
    var promiseDeleteEmployee = SinglePageCRUDService.delete(ShareData.value);
    promiseDeleteEmployee.then(function (pl) {
        $location.path("/showemployee");
    },
          function (errorPl) {
              $scope.error = 'failure loading Employee', errorPl;
          });
};
});

The above DeleteEmployeeController has a dependency on the SinglePageCRUDService and ShareData factory. The function getEmployee() makes a call to the getEmployee() function of the service and passes the ShareData.value to it. This is the EmpNo passed from the editEmployee() function from the ShowEmployeesController.
The function save() is used to make call to the delete() function of the service by passing EmpNo and Employee object to complete delete operation. Both the save() and getEmployee() functions make use of promise object to manage asynchronous calls to angular service.

  • Step 10: Now we need to manage our views for performing operations. We will design it as below:

Index.cshtml:
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<body ng-app="ApplicationModule">
    <div>
        <div>
            <div>
                <table>
                    <tr>
                        <td><a href="showemployees"> Show Employees </a></td>
                        <td><a href="addemployee"> Add Employee </a></td>
                    </tr>
                </table>
            </div>
            <div>
                <div ng-view></div>
            </div>
        </div>
    </div>
</body>
@section scripts{
  <script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script> 
  <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script> 
  <script type="text/javascript" src="@Url.Content("~/MyScripts/Module.js")"></script>
<script src="~/MyScripts/Services.js"></script>
  <script type="text/javascript" src="@Url.Content("~/MyScripts/ShowEmployeesController.js")"></script>
  <script type="text/javascript" src="@Url.Content("~/MyScripts/AddEmpController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/EditEmployeeController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/DeleteEmployeeController.js")"></script> 
 }
In the above markup, <body> is bound with the ApplicationModule using ‘ng-app’ directive. The ‘ng-view’ will be used to show views which we will be loading dynamically. The Hyperlink elements define links for ‘showemployees’ and ‘addemployee’ route expressions to load corresponding views.
AddEmployee.cshtml
@{
    ViewBag.Title = "AddEmployee";
}
<h2>Add New Employee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td><input type="text" ng-model="EmpNo" />  </td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td><input type="text" ng-model="EmpName" />  </td>
    </tr>
    <tr>
        <td>Salary</td>
        <td><input type="text" ng-model="Salary" />  </td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td><input type="text" ng-model="DeptName" />  </td>
    </tr>
    <tr>
        <td>Designation</td>
        <td><input type="text" ng-model="Designation" />  </td>
    </tr>
</table>
<input type="button" value="Save" ng-click="save()" />

The above view uses ‘ng-model’ directive to bind Employee properties with the <input> elements. This view will be loaded with the /addemployee route expression. This is defined in the Module.js. This expression in the URL loads the AddEmployeeController. This controller contains method to post employee details to save in the database.
EditEmployee.cshtml
@{
    ViewBag.Title = "EditEmployee";
}
<h2>EditEmployee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td><input type="text" ng-model="Employee.EmpNo" />  </td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td><input type="text" ng-model="Employee.EmpName" />  </td>
    </tr>
    <tr>
        <td>Salary</td>
        <td><input type="text" ng-model="Employee.Salary" />  </td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td><input type="text" ng-model="Employee.DeptName" />  </td>
    </tr>
    <tr>
        <td>Designation</td>
        <td><input type="text" ng-model="Employee.Designation" />  </td>
    </tr>
</table>
<input type="button" value="Save" ng-click="save()" />
<div>{{error}}</div>

The above view is loaded for the /editemployee url. This is defined in the Module.js in the routing configuration and loads EditEmployeeController, which contains a method to fetch employees to be edited and update its values.
DeleteEmployee.cshtml
@{
    ViewBag.Title = "DeleteEmployee";
}
<h2>DeleteEmployee</h2>
<table>
    <tr>
        <td>EmpNo</td>
        <td>{{Employee.EmpNo}}</td>
    </tr>
    <tr>
        <td>EmpName</td>
        <td>{{Employee.EmpName}}</td>
    </tr>
    <tr>
        <td>Salary</td>
        <td>{{Employee.Salary}}</td>
    </tr>
    <tr>
        <td>DeptName</td>
        <td>{{Employee.DeptName}}</td>
    </tr>
    <tr>
        <td>Designation</td>
        <td>{{Employee.Designation}}</td>
    </tr>
</table>
<input type="button" value="Delete" ng-click="delete()" />

The above view is loaded for the /deleteemployee url. This is defined in the Module.js in the  routing configuration. This loads DeleteEmployeeController, which contains a method to fetch employee to be deleted and perform delete operations.

Running Application

Run the application the following View gets displayed

  • Click on ‘Show Employees’. The following result will be displayed with Employee details:
  • The URL used is http://Server/shoewmployees
  • Similarly click on the ‘Add Employee’ link and the following View will be displayed:
  • The URL is http://server/addemployee. Add the Employee details and click on the Save button, the EmpNo will be generated as follows:
  • Click on the ‘Show Employees’ link and the result will be as follows:
  • Click on the ‘Edit’ link of any row and the Edit View will be displayed:
  • The url will be http://Server/editemployee. Here we can update Employee details and click on save. After clicking on the Save we will be back to the first result (exactly the same when we ran the application) where the updated values can be verified. In a similar way, the delete functionality can also be tested.

Conclusion: SPA is the requirement of this new generation of web applications. It provides an easy interaction with WEB interfaces for users looking for a Desktop like experience on the Web. A mashup of client-server technologies like Angular.js and ASP.NET Web API helps you create enterprise ready SPA applications.
Download the entire source code of this article (Github)



ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal :: Integrate Stripe .Net Payment Processing Library With your ASP.Net 4.5 C# Application

clock November 11, 2014 06:05 by author Ben

The advantages of Stripe

Accepting payment cards on-line has not been less difficult than it's now. Businesses like Stripe have created it simple for builders like ourselves to include sophisticated payment methods into our internet programs without having to bother with the safety compliance and audits which are typically associated with payment card info storage.

 


Stripe lets you preserve customers’ details securely, create custom made payment structures, and also develop customized payment programs for multiple or one customers.

Stripe.Net

Stripe.Net is definitely an open resource library to the Microsoft .NET Framework that permits straightforward integration into your .NET tasks. Today we are going to only be masking the integration of Stripe.Net into an ASP.NET undertaking, however you can study the documentation and find out more regarding how to use the Stripe.Net library on the Stripe.Net Github repository.

Our Project

For your goal of the tutorial, we are going to be producing a brand new ASP.Net internet application. Should you already have an application that you simply want to combine Stripe.Web with, which is amazing! If not, or for those who have by no means developed an ASP.Net application, follow these initial step to obtain up and running.

Very first, we'd like to create the venture. We will do that by opening up Microsoft Visual Studio, and picking Visual C# > Web > ASP.Net Web Forms Application. Notice that we have been utilizing the .NET 4.5 Framework on the best from the window, really feel totally free to change the framework model in your liking. Push OK.

Referencing the Stripe.Net Library

When you have your software open up in Visual Studio, you’re likely to require to put in the Stripe.Net library to use it is classes and methods inside your program. By reading the Stripe.Net Github page, we have discovered the library is obtainable like a NuGet package in Visual Studio, which is the optimal way to integrate the library, so that is how we’re going to do it. Within your solution explorer locate the References listing and proper click on it. You will see a choice labelled “Manage NuGet Packages…”, click that alternative within the dropdown menu.

You'll be prompted with the Control NuGet Packages window. Navigate down the remaining menu and click on Online. Now you'll be able to kind Stripe.Net to the lookup bar in the top left corner in the window, and (if you are related to the world wide web) you will note the Stripe.Net library seem within the center of the window. Set up the package and you'll notice that it installs the json.NET and Stripe.NET package inside the references listing. The explanation this occurs, would be that the Stripe.Net library relies on the json.NET library, so that you must include it into your references directory to ensure that Stripe.Net to operate.

Authentication

The last step of integration in this process, is verifying your account with Stripe. The designated authentication method that Stripe has provided for us is their developer API Key. This key is unique to each Stripe user and verifies your account so Stripe knows which user account all of your transactions belong to.

We only need to place this API Key into our application once by opening up the Web.config file and placing the following code before the </configuration> tag.

<appSettings>
  <add key="StripeApiKey" value="[your API Key]"/>
</appSettings>

Now you’re all set to use the Stripe.NET library in your application! Just remember to reference the json.NET and Stripe.NET libraries in any files you are using Stripe.NET functionality.

 



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