European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 5 Hosting – HostForLIFE.eu :: How to Create an HTML Control from any HTML Elements in ASP.NET

clock March 30, 2015 07:58 by author Rebecca

Sometimes as an ASP.NET developer, you may want to create your web application using a specific html structure or specific html elements. ASP.NET Web Controls only allow so much customization over the interface and the actual markup that gets displayed in the browser. Well, I will explain to you how to use hand coded html elements known in the framework as HTML Controls. These HTML Controls allow us to have full control over our interface markup yet still allows us to use our own HTML element as a ASP.NET Server Control. Let’s get started!

First, add your element to your aspx file. In order to use the element as a Server Control, we need to specify an element ID and the runat="server" properties. Try to add the following code within the <body> tag in Default.aspx:

<h1 id="the_heading" runat="server"></h1>

To demonstrate the abilities of HTML Controls, we’re going to leave this heading tag blank, and populate it via server side code in the code-behind. This single HTML element is enough for a demonstration, but in a larger production application, you will have many elements that need to be dynamically populated throughout your project.

In order to use an HTML Control we’re going to have to import the HTML Controls namespace in Default.aspx.cs like so:

using System.Web.UI.HtmlControls;

Now that we have the required namespace referenced in the top of the code-behind, we can continue by instantiating and manipulating our HTML Control.

Within the standard Page_Load method in Default.aspx.cs, please type the following:

var a = " World!"
the_heading.InnerHtml = "Hello" + a;

In the code above, we are instantiating a variable named a that contains the string " World!". On the next line we reference our HTML Control via it’s ID attribute the_heading.

We call this method as InnerHtml on the HTML element which replaces the content within the elements tags.

Finally, we specify the content to populate the element with as the string "Hello" concatenated with our variable a to create the message "Hello World!". Now when we compile our program, our empty heading tag should contain the friendly message “Hello World!”.

The entire code-behind should look similar to the following:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace html_controls
{
  public partial class _Default : Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      var a = " World";
      the_heading.InnerHtml = "Hello" + a;
    }
  }
}

That's all about creating an HTML Control from any HTML Elements in ASP.NET. Easy right? Good luck!

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Hosting - Germany :: The Difference Between DataSet, DataReader, DataAdapter and DataView in .net

clock March 24, 2015 11:38 by author Scott

Here is short tutorial only about the difference DataSet, DataReader, DataAdapter and DataView in .net.

1. DataSet

Dataset is connection-less oriented, that means whenever we bind data from database it connects indirectly to the database and then disconnected. It has read/write access on data tables. It supports both forward and backward scanning of data.

DataSet is a container of one or more DataTable. More often than not, it will just contain one table, but if you do a query with multiple SELECT statements, the DataSet will contain a table for each.

You have to be careful about how much data you pull into a DataSet, because this is an in-memory representation. You can Fill a DataSet using the Fill() method of a DataAdapter.

You can download example code at the end of this tutorial!

2. DataReader

DataReader is connection-oriented, that means whenever we bind data from database it must require a connection and after that disconnected from the connection. It has read-only access, we can’t do any transaction on them. It supports forward-only scanning of data, in other words you can’t go backward.

DataReader fetches one row at a time so very less network cost as compare to DataSet(that fethces all the rows at a time). It is scalable to any number of records, at least in terms of memory pressure, since it only loads one record at a time. One typical way to get a DataReader is by using theExecuteReader() method of a DbCommand.

You can download example code at the end of this tutorial!

3. DataAdapter

DataAdapter is an ADO.NET Data Provider. DataAdapter can perform any SQL operations like Insert, Update, Delete, Select in the Data Source by using SqlCommand to transmit changes back to the database.

DataAdapter provides the communication between the Dataset/DataTable and the Datasource. We can use the DataAdapter in combination with the DataSet/DataTable objects. These two objects combine to enable both data access and data manipulation capabilities.

You can download example code at the end of this tutorial!

4. DataView

Generally, we use DataView to filter and sort DataTable rows. So we can say that DataView is like a virtual subset of a DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data.

For example, one control may be bound to a DataView showing all of the rows in the table, while a second may be configured to display only the rows that have been deleted from the DataTable. The DataTable also has a DefaultView property which returns the default DataView for the table.



ASP.NET 5 Hosting - HostForLIFE.eu :: Anti Forgery Tokens with AngularJS and ASP.NET 5

clock March 23, 2015 12:10 by author Peter

In this post, I will tell you about Anti Forgery Tokens with AngularJS and ASP.NET 5. Single Page Applications utilizing AngularJS with ASP.NET by default leave our Web API methods open to forgery abuse. A couple of straightforward steps will permit you to include hostile to phony security. The primary step will be to make a custom activity channel ascribe to test our answer which you can use to finish web programming interface classes or individual activities.

 

using System;
using System.Linq;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http.Filters;
namespace antiforgery
{
    public sealed class ValidateCustomAntiForgeryTokenAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
           if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            var headers = actionContext.Request.Headers;
            var cookie = headers
                .GetCookies()
                .Select(c => c[AntiForgeryConfig.CookieName])
                .FirstOrDefault();
            var tokenFromHeader = headers.GetValues("X-XSRF-Token").FirstOrDefault();
            AntiForgery.Validate(cookie != null ? cookie.Value : null, tokenFromHeader);
            base.OnActionExecuting(actionContext);
        }
    }
}


The web API classes or methods will need decorating appropriately to ensure this code is run, i.e.
[ValidateCustomAntiForgeryTokenAttribute]

The following step is to verify ASP.NET includes its standard forgery token cookie and hidden field in the markup. Include the accompanying line into the markup.
@Html.AntiForgeryToken();

Presently, we have to redesign our AngularJS code to pass anti forgery token back in the header with all our web API calls. The most straightforward approach to do this is to situated a default up in the run system for the AngularJS application module, e.g.
.run(function($http) {
    $http.defaults.headers.common['X-XSRF-Token'] =      

angular.element('input[name="__RequestVerificationToken"]').attr('value');
})

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET 5 Hosting - HostForLIFE.eu :: Custom Config Section in ASP.NET

clock March 20, 2015 08:18 by author Peter

In this post, I will tell you how to extend ASP.NET 5 configuration settings with XML configuration elements of your own. To do this, you make a custom configuration section handler. The handler must be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The area handler translates and forms the settings that are characterized in XML design components in a particular area of a Web.config file. You can read and write these settings through the handler's properties.

And now, write the following code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
   {
       [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
            {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}
<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
   </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
           {
    if (Roles.IsUserInRole("", roleRedirect.Role))
               {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
   }
}

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting UK - HostForLIFE.eu :: How to Capture Screenshot Image of Website in ASP.NET 5?

clock March 16, 2015 07:42 by author Peter

In this short article, I will tell you about How to Capture Screenshot Image of Website in ASP.NET 5. To catch the screenshot of page, I am making utilization of WebBrowser control of Windows Forms Application. Since the WebBrowser is a Windows Forms controls, so as to utilize it as a part of ASP.NET Web Projects, we will need to add reference to the accompanying libraries.

And here is the code that I used:

ASP.NET
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> How to Capture Screenshot in ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <b>Enter WebSite Url:</b>
            </td>
            <td>
                <asp:TextBox ID="txtUrl" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="btnCapture" Text="Capture" runat="server" OnClick="btnCapture_click" />
            </td>
        </tr>
    </table>
    <br />
    <asp:Image ID="imgScreenshot" runat="server" Visible="false" Height="800" Width="800" />
    </form>
</body>
</html>

Code for C#
using System.IO;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public partial class CaptureWebsite : System.Web.UI.Page
{
    protected void btnCapture_click(object sender, EventArgs e)
   {
        string url = txtUrl.Text.Trim();
        Thread thread = new Thread(delegate()
       {
            using (WebBrowser browser = new WebBrowser())
            {
                browser.ScrollBarsEnabled = false;
                browser.AllowNavigation = true;
                browser.Navigate(url);
                browser.Width = 1024;
                browser.Height = 768;
                browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webbrowse_DocumentCompleted);
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                }
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
    private void webbrowse_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser webrowse = sender as WebBrowser;
        Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height);
        webrowse.DrawToBitmap(bitmap, webrowse.Bounds);
        MemoryStream stream = new MemoryStream();
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] strbytes = stream.ToArray();
        imgScreenshot.Visible = true;
        imgScreenshot.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(strbytes);
    }
}


Code for VB.NET

Imports System.IO
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms
Partial Public Class CaptureWebsite
    Inherits System.Web.UI.Page
    Protected Sub btnCapture_click(sender As Object, e As EventArgs)
        Dim url As String = txtUrl.Text.Trim()
                   Dim thread As New Thread(Sub() Using browser As New WebBrowser()
        browser.ScrollBarsEnabled = False
        browser.AllowNavigation = True
        browser.Navigate(url)
        browser.Width = 1024
        browser.Height = 768
        browser.DocumentCompleted += New WebBrowserDocumentCompletedEventHandler(AddressOf webbrowse_DocumentCompleted)
        While browser.ReadyState <> WebBrowserReadyState.Complete            System.Windows.Forms.Application.DoEvents()
        End While
                   End Using)
        thread.SetApartmentState(ApartmentState.STA)
        thread.Start()
        thread.Join()
    End Sub   
Private Sub webbrowse_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
        Dim webrowse As WebBrowser = TryCast(sender, WebBrowser)
        Dim bitmap As New Bitmap(webrowse.Width, webrowse.Height)
        webrowse.DrawToBitmap(bitmap, webrowse.Bounds)
        Dim stream As New MemoryStream()
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
        Dim strbytes As Byte() = stream.ToArray()
        imgScreenshot.Visible = True
        imgScreenshot.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(strbytes)
    End Sub
End Class

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting Belgium - HostForLIFE.eu :: Pass Multiple Values to Command Argument in ASP.NET

clock March 13, 2015 06:05 by author Peter

In this post I will show you how to Pass Multiple Values to Command Argument in ASP.NET. First, you should create a new project and write the following code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleCommandArgument.aspx.cs"   Inherits="MultipleCommandArgument" %>
<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
               <Columns>
                  <asp:BoundField DataField="carid" HeaderText="Card Id" />
                   <asp:BoundField DataField="Year" HeaderText="year" />
                   <asp:TemplateField>
                       <ItemTemplate>
                           <asp:Button ID="btnTest" runat="Server" CommandName="Test" Text="Select" CommandArgument='<%#Eval("carid") + ","+Eval("year") %>' />
                       </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
           <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MultipleCommandArgument : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }     
    } 
    DataTable data;
    DataTable GetData()
    {
        data = Session["data"] as DataTable;
        if (data != null)
        {
            return data;
        }
        data = new DataTable();
        DataColumn primaryColumn
        = new DataColumn("carid", typeof(Int32));
        data.Columns.Add(primaryColumn);
        data.Columns.Add(new DataColumn("year", typeof(Int32)));
        data.Columns.Add(new DataColumn("make", typeof(string)));
        data.Columns.Add(new DataColumn("model", typeof(string)));
        DataRow dr;
        dr = data.NewRow();
        dr[0] = 1;
        dr[1] = 1998;
        dr[2] = "Isuzu";
        dr[3] = "Trooper";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 2;
        dr[1] = 2000;
        dr[2] = "Honda";
        dr[3] = "Civic";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 3;
        dr[1] = 2000;
        dr[2] = "BMW";
        dr[3] = "GM";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 4;
        dr[1] = 2000;
        dr[2] = "Swift";
        dr[3] = "Tata";
        data.Rows.Add(dr);
        DataColumn[] primaryColumns = new DataColumn[1];
        primaryColumns[0] = primaryColumn;
        data.PrimaryKey = primaryColumns;
        Session["data"] = data;
        return data;
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Test")
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
       Label1.Text= commandArgs[0];
       Label2.Text = commandArgs[1];
        }
    }
}

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



HostForLIFE.eu Launches New Data Center in Frankfurt (Germany)

clock March 10, 2015 11:50 by author Peter

HostForLIFE.eu, a leading Windows hosting provider with innovative technology solutions and a dedicated professional services team proudly announces new Data Center in Frankfurt (Germany) for all costumers. HostForLIFE’s new data center in Frankfurt will address strong demand from customers for excellent data center services in Europe, as data consumption and hosting services experience continued growth in the global IT markets.

The new facility will provide customers and our end users with HostForLIFE.eu services that meet in-country data residency requirements. It will also complement the existing HostForLIFE.eu. The Frankfurt (Germany) data center will offer the full range of HostForLIFE.eu web hosting infrastructure services, including bare metal servers, virtual servers, storage and networking.

HostForLIFE.eu expansion into Frankfurt gives them a stronger European market presence as well as added proximity and access to HostForLIFE.eu growing customer base in region. HostForLIFE.eu has been a leader in the dedicated Windows & ASP.NET Hosting industry for a number of years now and we are looking forward to bringing our level of service and reliability to the Windows market at an affordable price.

The new data center will allow customers to replicate or integrate data between Frankfurt data centers with high transfer speeds and unmetered bandwidth (at no charge) between facilities. Frankfurt itself, is a major center of business with a third of the world’s largest companies headquartered there, but it also boasts a large community of emerging technology startups, incubators, and entrepreneurs.

Our network is built from best-in-class networking infrastructure, hardware, and software with exceptional bandwidth and connectivity for the highest speed and reliability. Every upstream network port is multiple 10G and every rack is terminated with two 10G connections to the public Internet and two 10G connections to our private network. Every location is hardened against physical intrusion, and server room access is limited to certified employees.

All of HostForLIFE.eu controls (inside and outside the data center) are vetted by third-party auditors, and we provide detailed reports for our customers own security certifications. The most sensitive financial, healthcare, and government workloads require the unparalleled protection HostForLIFE.eu provides.

Frankfurt (Germany) data centres meet the highest levels of building security, including constant security by trained security staff 24x7, electronic access management, proximity access control systems and CCTV. HostForLIFE.eu is monitored 24/7 by 441 cameras onsite. All customers are offered a 24/7 support function and access to our IT equipment at any time 24/7 by 365 days a year. For more information about new data center in Frankfurt, please visit http://hostforlife.eu/Frankfurt-Hosting-Data-Center

About HostForLIFE.eu
HostForLIFE.eu is an European Windows Hosting Provider which focuses on the Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



ASP.NET 5 Hosting Russia - HostForLIFE.eu :: Submit Form Without Page Refresh in ASP.NET with Ajax and jQuery

clock March 9, 2015 08:06 by author Peter

In this short tutorial, I will tell you about submit form without page refresh in ASP.NET with Ajax and jQuery. First step, make a Employee table as shown on the picture below:

Now, make a new WebSite then add a new WebForm name as Index.aspx. Write the following code to the page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Script/jquery-2.1.1.min.js"></script>
    <script src="Script/Myjs.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>Name</td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
           <tr>
                <td>Age</td>
                <td>
                    <input type="text" id="txtAge" />
                </td>
            </tr>
            <tr>
                <td>Email</td>
                <td>
                    <input type="text" id="txtEmail" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" id="btnSubmit" value="Save" />
                </td>
            </tr>
        </table>
        <label id="lblResult" ></label>
    </div>
    </form>
</body>
</html>


Now, Open file Index.aspx.cs and write the following code:
using System;
using System.Web.Services;
using System.Data.SqlClient;
public partial class Index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     }
     [WebMethod]
    public static string SaveRecord(string Name,int Age, string Email)
    {
        string messageResult = string.Empty;
        string strConnection = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Peter\TestDB.mdf;Integrated Security=True;Connect Timeout=30";
        SqlConnection con = new SqlConnection(strConnection);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into Employee (Name,Age,Email) values (@name,@age,@email)",con);
        cmd.Parameters.AddWithValue("@name", Name);
        cmd.Parameters.AddWithValue("@age",Age);
        cmd.Parameters.AddWithValue("@email", Email);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if(result == 1)
        {
            messageResult = "Record Inserted";
        }
        else
        {
            messageResult="Unable to Save Record";
        }
        return messageResult;
    }
}

Above you can see, I have included a attribute [WebMethod]. What is WebMethod ?  A WebMethod Attribute Enable a system to be called through the WebServices. Now, include another JS record. Compose the accompanying code in your JS document.
$(document).ready(function () {
    $('#btnSubmit').on('click', function () {
        var getName = $('#txtName').val();
        var getAge = parseInt($('#txtAge').val());
        var getEmail = $('#txtEmail').val();
        $.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Index.aspx/SaveRecord",
                data: "{'Name':'" + getName + "','Age':" + getAge + ",'Email':'" + getEmail + "'}",
                dataType: "json",
                success:function(data)
                {
                    $('#lblResult').text(data.d);
                    $('#txtName').val('');
                    $('#txtAge').val('');
                    $('#txtEmail').val(''); 
                },
                error:function(data)
                {
                    alert(data);
               }
            });

    });
});

And here is the output:

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting - HostForLIFE.eu :: Create Web API, Run Outside IIS Application

clock March 6, 2015 06:22 by author Peter

Today, In this article I will tell you about Create Web API with ASP.NET 5, run outside IIS application. First step, open visual studio and then make a console application as you can see on the picture below:

Create the Web API & OWIN Packages
Go to Tools menu, choose Library Package Manager, then select Package Manager Console. In the Package Manager Console window, enter the following code:

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Then, right click the project. Create new class named Startup.cs and add the following code:
public class Startup
   {
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
           HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
             appBuilder.UseWebApi(config);
        }
    }

Now create a Web API controller class. In Solution Explorer, right click the project & choose Add / Class to add a new class. I named it: HelloController. Then write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace SelfHostWebApi
{
    public class HelloController : ApiController
    {
        // GET api/values/5
        public string Get(int id)
        {
            return "Hello API";
        }
    }
}


Open Program.cs and add write the code below, inside main method:
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SelfHostWebApi
{
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/";
            // Start OWIN host
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                // Create HttpCient and make a request to api/values
                HttpClient client = new HttpClient();
                var response = client.GetAsync(baseAddress + "api/hello").Result;
                Console.WriteLine(response);                
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
            Console.ReadLine();
        }    }
}


Finally, your self hosted Web API is ready. You will see the output like the picture below when you Run it.

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in