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 :: 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.1 Hosting with ASPHostPortal.com :: How to Increase The Overall Performance of ASP.NET 4.5.1 in your App

clock October 1, 2014 07:23 by author Ben

ASP.NET is really a framework for creating net applications created by Microsoft. Initially the technologies. NET is the successor of ASP which is also a computer software product from Microsoft. With .NET ASP gives a platform for developers to design and create dynamic websites and net portals.



You will find certain items that ought to be regarded as when improving the performance from the application in developing a net application. Here are a few of the tips to improve the performance of ASP.NET 4.5.1:

Turn off Session State
Disable session state if you do not need, as this can improve the all round efficiency. By default the session state is always active. However, you'll be able to disable session state for any specific pages.

Turn off Tracing
If tracing is enabled, tracing will add a whole lot of overhead in producing applications. Though tracing is actually a useful function inside the development because it enables developers to track and trace application sequence, tracing may be turned off, unless you want to monitor the trace logging.

Avoid Page Validation Server (Steer clear of Server-side Validation)
Within this case, must be attempted use of client-side validation, not the server side. Server-side validation will consume a lot of sources around the server which can have an effect on application efficiency.

Stay away from Exceptions (Avoid Exceptions)
Exceptions may be 1 of the biggest resource eater which resulted within the lower of web applications and windows applications. Therefore, it is much better to prevent the use and handling of exceptions which can be not beneficial.

Avoid frequent connections for the database (Steer clear of Frequent Calls to Database)
Connections are frequently made for the database can devote time response and resources (resources). This can be avoided by utilizing batch processing. Producing the minimum database connection as a connection is opened and not closed, may cause efficiency slowdown.

Stay away from utilizing Recursive Functions and Nested Loops
To improve application performance, attempt to always steer clear of utilizing nested loops and recursive functions simply because these functions consume a whole lot of memory.

Turn off the View State

In ASP.NET, the default view state will probably be active and will slow down the website. So if you don't use a kind postback, it's much better to disable view state.

Use Caching
Web page caching could be employed to get a particular period of time and towards the required duration will not visit the server and are served from the cache. In the case of static internet pages and dynamic, Partial Caching [Fragment Caching] may be utilized to break into a couple of pages a user control.



Free Trial ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: How to Send Bulk Email Using ASP.Net 4.5

clock April 3, 2014 12:14 by author Kenny

In this article I’m going to explain about how to send bulk email using ASP.Net 4.5. Bulk email software is software that is used to send email in large quantities. Bulk mail broadly refers to mail that is mailed and processed in bulk at reduced rates. The term does not denote any particular purpose for the mail; but in general usage is synonymous with "junk mail". This tutorial we will use ASP.NET Web Page for provide the user interface for your Web applications, Grid View for enables you to select, sort, and edit values of a data source in a table where each column represents a field and each row represents a record, HTML Email Templates and Gmail SMTP Mail Server.

Let’s start to try this tutorial, for the first step you must create a new project.
Click "File" -> "New" -> choose "Project..." and then select web "ASP .Net Web Forms Application". Name it as "Bulk Email".
And now let’s see in the Design page “Default.aspx” design the web page as in the following screen:

This is code for Design Source (Default.aspx):
Default.aspx.cs

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="BulkEmail._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">              
                <h2>Send Bulk email using asp.net</h2>
            </hgroup>
            <p>To learn more about ASP.NET
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
       <h3>We suggest the following:</h3>
    <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
    <p>
       <asp:Button ID="btnBind" runat="server" Text="View" OnClick="btnBind_Click" /> <asp:Label
ID="Label1" runat="server" Font-Bold="true" ForeColor="Green" Text="Total
Customers:">   
</asp:Label><asp:Label ID="lbltotalcount" runat="server" ForeColor="Red" Font
Size="Larger"></asp:Label> </p>
        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
        <asp:GridView ID="grvCustomers" runat="server"></asp:GridView>
    </asp:Panel>
</asp:Content>

In the Web.config file create the connection string as:
Web.config

<connectionStrings>   
<add name="ConnectionString"connectionString="Server=localhost;userid=root;password=;Database=
orthwind"providerName="MySql.Data.MySqlClient"/>      
</connectionStrings>


In the code behind file (Default.aspx.cs) write the code as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Using namespaces 
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;

namespace BulkEmail
{
    public partial class _Default : Page
    {
        #region MySqlConnection Connection
        MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            Try
            {
                if (!Page.IsPostBack)
                {

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion
        #region show message
        /// <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>");
        }       
        #endregion
        #region Bind Data
        /// <summary>
        /// This display the data fetched from the table using MySQLCommand,DataSet and
MySqlDataAdapter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBind_Click(object sender, EventArgs e)
        {
            Try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("Select
CustomerID,ContactName,Address,Phone,Email from customers", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                grvCustomers.DataSource = ds;
                grvCustomers.DataBind();
                lbltotalcount.Text = grvCustomers.Rows.Count.ToString();
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();

            }
            btnBind.Visible = false;
        }
        #endregion
        #region Bulk email,GridView,gmail
        /// <summary>
        /// this code used to Send Bulk email 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Try
            {
                lbltotalcount.Text = string.Empty;
                foreach (GridViewRow grow in grvCustomers.Rows)
               {
                    string strCustomerID = grow.Cells[0].Text.Trim();
                    string strContactName = grow.Cells[1].Text.Trim();
                    string strAddress = grow.Cells[2].Text.Trim();
                    string strPhone = grow.Cells[3].Text.Trim();
                    string strEmail = grow.Cells[4].Text.Trim();               

                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("##NAME##", strContactName);
                    string to = strEmail;
                    string from = "YouEmailID@gmail.com";
                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Auto Response Email";
                    message.Body = mailbody;
                    message.BodyEncoding = Encoding.UTF8;
                    message.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    System.Net.NetworkCredential basicCredential = newSystem.Net.NetworkCredential("YouEmailID@gmail.com", "Password");
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = true;
                    client.Credentials = basicCredential;
                    try
                    {
                        client.Send(message);
                        ShowMessage("Email Sending successfully...!" + strContactName + " &nbsp;");                                           
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                } 
            }
            catch (MySqlException ex)
            {
                ShowMessage(ex.Message);
            }
            Finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}


Finally, Bulk Sending an E-Mail Using ASP.NET 4.5 with HTML Email Templates and Gmail SMTP Mail Server.



ASP.NET 4.5.1 Hosting with ASPHostPortal.com :: Capture images using web camera in ASP.NET 4.5.1

clock March 25, 2014 09:11 by author Kenny

In this article, i'm going to explain about how to integrate a webcam into your web application using ASP.NET 4.5.1. A web camera can capture images at the server end and a web page can display them. It’s very simple for integrate a webcam and capture images in your website that using ASP.NET 4.5.1.

Before it, make sure that your device has Latest Flash player and Web camera.
Let's following these steps:

First, copy the “WebcamResources” into your new application.
After that, add the following code in to your Default.aspx page:
<object width="450" height="200"param name="movie1" value="WebcamResources/save_picture.swf"

embed src="WebcamResources/save_picture.swf" width="45
0"
height="200" >
</object>

This code will place your Flash object into your web page, used to capture the images from the web cam.
Add one more page there with the name ImageConversions.aspx.
Add the following code into ImageConversion.aspx at the page load event:
string str_Photo = Request.Form["image_Data"]; //Get the image from flash file
byte[] photo = Convert.FromBase64String(str_Photo);
FileStream f_s = new FileStream("C:\\capture.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter b_r = new BinaryWriter(f_s);
b_r.Write(photo);
b_r.Flush();
b_r.Close();
f_s.Close();


The above code will convert the bytes to an image and will save the image in the c drive.



FreeTrial ASP.NET 4.5.1 Hosting :: How to Make Web Chat Box Using ASP.NET

clock March 19, 2014 07:19 by author Kenny

You can get your chat box on your website using ASP.NET. The advantage of chat box is make websites and web applications more user interactive and provide a dynamic look too. The functionality of chat box in a website is increasing day by day, because it provides some extra functionalities and looks.

Now, we will explain about how to make Chat Box using ASP.NET.
For the first, Open Visual Studio>Create a new page (class file)
And then, Design your chat box (through HTML and CSS).

Coding (as shown below):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Window1.Visible = true;
    }
 
    private string Chat
    {
        get
        {
            if (Application["a"] == null)
                Application["a"] = "";
            return Application["a"].ToString();
        }
        set
        {
           Application["a"] = value;
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        Label1.Text = Chat;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Chat = TextBox1.Text +"<br/>"+ Chat;
    }
}


The chat box code that we explain here is a combination of GAIA Toolkit and Coding. We are doing this coding in C#.

 



ASP.NET 4.5.1 Hosting - with ASPHostPortal.com :: How to Load GMap Direction from Database in ASP.NET

clock March 11, 2014 06:45 by author Kenny

Well i am going to explain how to load GMap direction from database in ASP.NET.
Google maps is a web mapping service application and technology provided by Google, powering many map-based services, including the Google maps website, Google ride finder, Google transit, and maps embedded on third-party websites via the Google maps API. ASP.NET is a server-side web application framework designed for web development to produce dynamic web pages.
Let’s check the steps for run this program.

For the first: Go to file > new > project > select asp.net web forms application > entry application name > click ok.

And then 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.


After that create table: Open database > right click on table > add new table > add columns > save > enter table name > ok.

This is the table sample:

Next, create a stored procedure in sql server: Open database > right click on stored procedure > add new stored procedure > write below sql code > save.

Next step, add a webpage: Go to solution explorer > right click on project name form solution explorer > add > new item > select web form/ web form using master page under web > enter page name > add.
Html code



Js code

Write this below js code for load gmap direction from database.

<script src="//maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abqiaaaaupsjpk3mbtdpj4g8cqbnjrragtyh6uml8madna0ykuwnna8vnxqczvbxtx2dyyxgstoxpwhvig7djw" type="text/javascript"></script><script language="javascript">
        var gmap;

        var directionpanel;
        var direction;
        function initialize() {
            gmap = new gmap2(document.getelementbyid("map"));
            gmap.setcenter(new glatlng(22.573438, 88.36293), 15);
// here i have set kolkata as center and 15 zoom level

            directionpanel = document.getelementbyid("route");
            direction = new gdirections(gmap, directionpanel);
        }
        $(document).ready(function ()
{
            initialize();

            $('#btngetdirection').click(function () {
                //here populate data from database and get to gmap direction
                populatedirection();
            });
        });
        function populatedirection() {
            var from = $('#<%=ddfrom.clientid%>').val();
            var to = $('#<%=ddto.clientid%>').val();

            $.ajax({
                url: "default.aspx/getdirectioin",
// here url for code behind function
                type: "post",
                data: "{from: '"+from+"', to: '"+to+"'}",
                datatype: "json",
                contenttype: "application/json; charset=utf-8",
                success: function (data) {
                    direction.load(data.d.tostring());

                },
                error: function () {
                    alert("error!");
                }
            });
        }
    </script>

And then: write following code in page_load event:
Protected void page_load(object sender, eventargs e)
{
    if (!ispostback)
    {
        populatelocation();
    }}


Here is the function...

Private void populatelocation(){

// populate location here
    datatable dt = new datatable();
    using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        string query = "select * from locations";
        sqlcommand cmd = new sqlcommand(query, con);
        if (con.state != connectionstate.open)
        {
            con.open(); }
        dt.load(cmd.executereader());}
    ddfrom.datasource = dt;
    ddfrom.datatextfield = "locname";
    ddfrom.datavaluefield = "locid";
    ddfrom.databind();
    ddto.datasource = dt;
    ddto.datatextfield = "locname";
    ddto.datavaluefield = "locid";
    ddto.databind();}


Don’t forget write this function into your page code behind for called from jquery code:

// this is the function is for called from jquery
[webmethod]
Public static string getdirectioin(string from, string to){
    string returnval = "";
    datatable dt = new datatable();
using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        sqlcommand cmd = new sqlcommand("getdirection", con);
        cmd.commandtype = commandtype.storedprocedure;
        cmd.parameters.addwithvalue("@locfrom", from);
        cmd.parameters.addwithvalue("@locto", to);
        if (con.state != connectionstate.open)
        {
            con.open();}
        dt.load(cmd.executereader());}
    returnval = "from: " + dt.rows[0]["fromloc"].tostring() + " to: " + dt.rows[0]["toloc"].tostring();
    return returnval;}


And the last, Just run your application



Free Trial ASP.NET 4.5.1 Hosting - with ASPHostPortal.com :: How to make Scrollable GridView with a Fixed Header in .NET 4.5.1

clock March 7, 2014 05:38 by author Diego

In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery. GridView control of ASP.NET 4.5.1 makes our task much simpler as compared to HTML tables. But one problem which I always faced with GridView control is of scrolling headers. I tried several forums and websites, but didn’t come up with a good solution. GridView doesn’t have the ability to scroll. But if the GridView contains the larger number of rows or columns (say more than 100 rows and 15 columns), we want it to have scrollbars.

Now it is time to see all the activity in detail :

  • create a database in the SQL ServerCreate an ASP.NET website.
  • Create jquery-1.4.1.min.js and ScrollableGridPlugin.js and write this code in the header section. copy and paste it inside  <Head>.
    These script files by using these files we can manage the GridView header fixed postion.


    <
    script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

    <
    script type="text/javascript" src="Scripts/ScrollableGridPlugin.js"></script>
  • Write the jQuery code that is given below.

    script
    type="text/javascript">
            $(document).ready(function () {
                $('#<%=GridView1.ClientID %>').Scrollable();
            });

    </
    script
    >

  • The next step is to create a new HTML table in HeaderDiv which will contain the new header for the GridView. This job will be done by a JavaScript function (say CreateGridHeader()). This JavaScript function also sets the HeaderDiv style as per the DataDiv and new HTML table style as per GridView style and also we will hide the original header of GridView. This function will be called every time after filling the GridView with data as well as on the Page Load.
    created in the Page Load Default.aspx page like this :

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

<!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>Scrollable GridView With a Fixed Header Using jQuery</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <
script type="text/javascript" src="Scripts/ScrollableGridPlugin.js"></script>
      <
script type="text/javascript">
        $(document).ready(function () {
            $('#<%=GridView1.ClientID %>').Scrollable();
        });
      </script
>
<
body>
    <form id="form1" runat="server">
    <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
        <RowStyle BackColor="#EFF3FB" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White"
/>
        <Columns>
            <asp:BoundField DataField="id" HeaderText="Id" />
            <asp:BoundField DataField="name" HeaderText="Name" />
            <asp:BoundField DataField="salary" HeaderText="Salary" />\
            <asp:BoundField DataField="addres" HeaderText="Address" />
        </Columns>
    </asp:GridView>
    </form>
</
body
>

</html>

  • Binding the GridView with a DataTable object in the code behind file of Default.aspx page.

    using
    System;
    using
    System.Collections.Generic;
    using
    System.Linq;
    using
    System.Web;
    using
    System.Web.UI;
    using
    System.Web.UI.WebControls;
    using
    System.Data;
    using
    System.Data.SqlClient;


    public
    partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=akshay;Persist Security Info=True;User ID=sa;Password=wintellect";
            SqlDataAdapter adap = new SqlDataAdapter("select * from Person",con);
            DataSet ds=new DataSet();
            adap.Fill(ds,"Person");
            GridView1.DataSource = ds.Tables["Person"];
            GridView1.DataBind();
            GridView1.UseAccessibleHeader = true;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }

    }
  • Run the Page by f5, you will see that the Header and Footer is fixed when you scrolling. You are now ready with the GridView with fixed headers.

If you looking for windows web hosting services who support ASP.Net 4.5.1 please visit our Site ASPHostPortal.com



ASP.NET 4.5.1 - with ASPHostPortal.com :: How to Convert PDF to Excel in ASP.NET

clock March 6, 2014 11:45 by author Kenny

Well, i will explain the best way to convert PDF to Excel in .NET Framework.
When dealing with digital documents, you may notice that PDF data and Excel spreadsheets often go hand in hand. Although not as easily as we’d like. The PDF format is perfect format for preservation of your content layout - whether it be an invoice, a statement or a database. Thus, even though the format can display data perfectly, it can also make it difficult to reuse, edit or analyze in Microsoft Excel. Users have no choice but to turn to PDF converter solutions.

For developers, this presents a perfect opportunity: you can provide a solution within your own applications. In fact, one developer tool, PDF2Excel SDK, will allow you to integrate PDF to Excel conversion technology into your existing software applications and projects.

Developed by Investintech.com, PDF2Excel SDK contains everything a developer needs to leverage the same conversion algorithm behind their desktop PDF converter via DLL or COM API. This introduction guide to PDF2Excel SDK will give you a closer look at their PDF to Excel 2007 conversion technology.


Implementation Methods

For those who are programming with C#, use the following methods to convert PDF to Excel.

1. Using the Function Library

Prior to using the PDF-To-Excel function library, you must declare the functions in a class:

Note: if the full path is not specified, the location of the DLL file has to be defined within the system variable named PATH. Alternatively the file should be placed in the same location as the .exe file which is using it.

2. Using the COM Server

Prior to using the PDF-To-Excel COM Server, you must define a project reference to the PDF2ExcelCom 1.0 COM Component.
The .NET COM Interop layer generates a wrapper class you may call in your code.



ASP.NET 4.5.1 with ASPHostPortal.com :: Application Development A Perfect Web App Master

clock March 3, 2014 07:48 by author Kenny

ASP.NET is a development framework for building web pages and web sites with HTML, CSS, JavaScript and server scripting. ASP.NET helps bring out dynamism with web pages, all in a very short turn around time. This is why it is known to be a unique as well as a very popular framework, especially when web apps or websites are built. The reason why this framework was developed by Microsoft is because the market admires its innovative features. So, it has gained importance and is special as well. Consider it as a tool which can work wonders for developers as well as programmers, since it allows beautiful along with very dynamic websites to be born, using C# or VB as languages.

.net development services In the days gone by, web page contents weren’t spared of being static. With time it was understood that changes were important and have to be made for the websites to survive. New content had to be brought in. Moreover, there were manual modifications to be made to keep the site on the run as well as updated. This then brought about the awareness of having sites that would be auto updated as well as dynamic. Therefore, ASP by Microsoft was brought in, and hence the name ACTIVE SERVER PAGES came about. It thus helped in more ways than one, especially in meeting such needs.

Benefits

  1. You could own a small medium enterprise online or managing a huge business across many networks. There are many beneficial features which can help you to reach your goals.
  2. Irrespective of the size or volume, the language would work on every performance problem. It is developed in such a way that apps now can be worked on from any corner of the globe with utmost efficiency.
  3. Using this language, one doesn’t have to engage in long coding to make large apps. Most popular sites including ecommerce sites use it without any difficulty. This is because there is more power along with greater flexibility. In fact, the web pages can use the html code as well as source code for enhanced dynamism.
  4. In this day and age, using Asp.net for web apps is the sure shot way of making it big, say experts. The language is independent, with more than a quarter .net languages for users as well as developers to thrive on and to work with for their web apps.
  5. Infinite loops, memory leads or any activity deemed illegal would be instantly checked on. restarts happen on the spot, wherein all illegal activity along with its source would be tarnished.
  6. Before anything is sent to the main browser, the code would run on the esteemed server. This then ensures that there is constant monitoring of the pages, its main components as well as all the important applications in it.
  7. Cheap framework, and those looking for cost effective solutions would gain widely from it.


If you take a look online, you would find a large number of offshore companies across the world, willing and waiting to help your venture with all Asp.net needs. Most companies prefer their services outsourced, because of reliability as well as efficiency. Outsourced teams are available with plenty of expertise and experience to help with Asp.net application development and maintenance too.


The face of Asp.net app development is known to be an area which is fast emerging across the IT industry, say experts. Even the non IT companies look at it for safety and security in business across the online world. Verticals therefore are changing, and it is very rapid. Right from education to retail, manufacturing to finance, banking or investment, even online ecommerce sites too, everyone is using Asp.net.

Asp.net helps with continuity, smooth functioning and also gels well with a wide range of systems to meet every edge and demands of the business world these days. With super high web apps on the go, clients as well as customers alike are deriving immense satisfaction. Companies can now showcase their products and services like never before, there by bringing in more money.

 



ASP.NET 4.5.1 - with ASPHostPortal.com :: SEO friendly URLs with ASP.NET

clock February 26, 2014 06:51 by author Kenny

Search engines like human-readable URLs with keywords in it, and hesitate to respect messy URLs with a lot of query-string parameters. So, to make our ASP.NET database-driven website SEO-friendly we have to get rid of our complex URLs.

SEO or Search Engine Optimization is the process of affecting the visibility of a website or a web page in a search engine's "natural" or un-paid ("organic") search results. In general, the earlier (or higher ranked on the search results page), and more frequently a site appears in the search results list, the more visitors it will receive from the search engine's users. SEO may target different kinds of search, including image search, local search, video search, academic search, news search and industry-specific vertical search engines.

Solution 1: Fake pages and "Server.Transfer".
As you can see the two URLs above point to the same page. Basically it is the same page and it works like this: the page mailjet-newsletter-software.aspx contains no code at all and performs a Server.Transfer (aka server-side redirect) to product.aspx like this:
Server.Transfer("product.aspx?ProductID=18");
That's it. We have one "product.aspx" page which expects a "ProductID" parameter and a lot of "fake pages" with SEO-friendly names like firstproduct.aspx, secondproduct.aspx etc., which simply perform a Server.Transfer to the "product.aspx" with the right ProductID.

Simple, isn't it?

But this solution requires a lot of hard-coding - we will have to create all these fake pages and add a Server.Transfer command. So let's go a little further: we will create one base class for all our "fake pages" and add a record to the "tblProducts" table in the database:

Now we have to create our fake pages, inherit them all from the ProductPage class and voi la - that's it! We can also optionally remove all the HTML-code from the aspx-files, leaving the "Page" directive only.

Solution 2: Virtual Pages.

This method is pretty similar, except that we don't need to create any pages at all. Instead, we will add an HttpModule, which intercepts HTTP requests, and the user requests a non-existent page, performs a Rewrite operation. First we will create our HttpModule:

Now we have to register our HttpModule in the web.config:

<httpModules>
<add type="URLRewrite.ProductPageModule, URLRewrite" name="ProductPageModule" />
<httpModules>



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