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

Free ASP.NET Hosting - HostForLIFE.eu :: How to Discover if Linked List contains Loops or Cycles in C# ?

clock April 17, 2015 07:11 by author Peter

In this post i will be able to show you how to discover loop in linked list with ASP.NET C#. We can notice the loop within the coupled list via Floyd’s Cycle-Finding formula, explained here. The method is pretty simple: We have a tendency to begin at the start of the linked list with 2 pointers. The primary pointer is incremented through every node of the list. The second pointer moves twice as quick, and skips each other node. If the coupled list contains a loop, these 2 pointers can eventually meet at the same node, so indicating that the linked list contains a loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
namespace Algo
{
    public class Node
    {
        public Node Next { get; set; }
        public int Value { get; set; }
        public Node(int value)
        {
            this.Value = value;
        } 
    }
    public class LinkedList
    {        
    private Node _head;
        public LinkedList()
        { 
        }
        public void AppendLast(Node newNode)
        {
            if (_head == null)
            {
                _head = newNode;
            }
            else
            {
                Node current = _head;
                while (current.Next != null)
                {
                    current = current.Next;
                }
                current.Next = newNode;
            }
        }
        public override string ToString()
        {
            Node current = _head;
            StringBuilder builder = new StringBuilder();
            while (current != null)
            {
                builder.Append(current.Value + "->");
                current = current.Next;
            }
            return builder.ToString();
        }
        public bool IsCycle()
        {
            Node slow = _head;
            Node fast = _head;
            while (fast != null && fast.Next != null)
            {
                fast = fast.Next.Next;
                slow = slow.Next;
                if (slow == fast)
                    return true;
            }
            return false; 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LinkedList list = new LinkedList();
            list.AppendLast(new Node(10));
            list.AppendLast(new Node(20));
            list.AppendLast(new Node(30));
            Node cycle = new Node(40);
            list.AppendLast(cycle);
            list.AppendLast(new Node(60));
            list.AppendLast(cycle);
             if (list.IsCycle())
            {
                Console.WriteLine("Linked List is cyclic as it contains cycle or loop");
            }
            else
            {
                Console.WriteLine("LinkedList is not cyclic, no loop or cycle found");
            }   
        }
   }
}

Free ASP.NET Hosting

Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Create Profiles in ASP.NET

clock April 14, 2015 06:22 by author Rebecca

The ASP.NET Framework comes with the Profile object which an alternative to using cookies or session state to store user information. The Profile object provides you with a strongly typed, persistent form of session state.

You create a Profile by defining a list of Profile properties in your application root web configuration file. The ASP.NET Framework dynamically compiles a class that contains these properties in the background. The following web configuration file defines a Profile that contains three properties: firstName, lastName, and numberOfVisits.

File: Web.Config

<configuration>
<system.web>

  <profile>
    <properties>
      <add name="firstName" />
      <add name="lastName" />
      <add name="numberOfVisits" type="Int32" defaultValue="0" />
    <add name="xmlLastName" type="String" serializeAs="Xml"/>     
    </properties>
  </profile>

</system.web>
</configuration>

When you define a Profile property, you can use any of the following attributes:

  • name sets the name of the property.
  • type sets the type of the property.

The type can be any custom type, including a custom component that you define in the App_Code folder.

The default type is string.
defaultValue is a default value for the property.
readOnly creates a read-only property.

The default value is false.
serializeAs sets how a property is persisted into a static representation.
Possible values are Binary, ProviderSpecific, String, and Xml.

The default value is ProviderSpecific.
allowAnonymous allows anonymous users to read and set the property.

The default value is false.
provider associates the property with a particular Profile provider.
customProviderData passes custom data to a Profile provider.


File: ShowProfile.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    void Page_PreRender()
    {
        lblFirstname.Text = Profile.firstName;
        lblLastName.Text = Profile.lastName;

        Profile.numberOfVisits++;
        lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Profile.firstName = txtNewFirstName.Text;
        Profile.lastName = txtNewLastName.Text;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Profile</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    First Name:
    <asp:Label
        id="lblFirstname"
        Runat="server" />
    <br /><br />
    Last Name:
    <asp:Label
        id="lblLastName"
        Runat="server" />
    <br /><br />
    Number of Visits:
    <asp:Label
        id="lblNumberOfVisits"
        Runat="server" />

    <hr />

    <asp:Label
        id="lblNewFirstName"
        Text="New First Name:"
        AssociatedControlID="txtNewFirstName"
        Runat="server" />
    <asp:TextBox
        id="txtNewFirstName"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblNewLastName"
        Text="New Last Name:"
        AssociatedControlID="txtNewLastName"
        Runat="server" />
    <asp:TextBox
        id="txtNewLastName"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnUpdate"
        Text="Update Profile"
        OnClick="btnUpdate_Click"
        Runat="server" />

    </div>
    </form>
</body>
</html>

Free ASP.NET 5 Hosting

Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



FREE ASP.NET Hosting – HostForLIFE.eu :: Displaying SubTotal & Grand Total in ASP.NET 5

clock April 13, 2015 12:17 by author Peter

In this tutorial, I will show you how to Displaying SubTotal & Grand Total in ASP.NET 5. First, create new project. The records are isolated into Groups and after that SubTotal is calculated for every Group and then shown utilizing an element Row as a part of GridView. Now , I write the following code to create Products table:

CREATE TABLE [dbo].[Products](
     [ProductID] [int] NULL,
     [ProductName] [varchar](100) NULL,
     [CategoryID] [int] NULL,
     [UnitPrice] [decimal](18, 0) NULL,
     [QuantityPerUnit] [varchar](100) NULL
) ON [PRIMARY]
GO

First create new web apps and open your GridViewSubTotalTotal.aspx and write the following code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Displaying SubTotal & Grand Total in ASP.NET 5</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3 style="color:Green">Display SubTotal and Grand Total in ASP.Net GridView</h3>
    <div>
        <asp:GridView ID="gvData" runat="server" BackColor="White" BorderColor="#CC9966"
            AutoGenerateColumns="false" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
            Font-Names="Tahoma" Font-Size="Small"  Width="475px" OnRowCreated="gvData_RowCreated"
nDataBound="gvData_OnDataBound">
            <Columns>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID"  />
                <asp:BoundField DataField="CategoryID" HeaderText="Category ID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
                <asp:BoundField DataField="Price" HeaderText="Price"  DataFormatString="{0:N2}"/>
            </Columns>
            <FooterStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="#E6E6E1" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>


Next step, write the code below:
GridViewSubTotalTotal.aspx.cs:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
public partial class GridViewSubTotalTotal : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
   {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }
    protected void BindGridData()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
        string sqlQuery = "SELECT ProductID,ProductName,CategoryID,(UnitPrice*QuantityPerUnit) AS Price FROM Products";
        sqlQuery = sqlQuery + " WHERE CategoryID in(1,2,3) ORDER BY ProductID ASC";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvData.DataSource = ds;
        gvData.DataBind();   
}
    int currentId = 0;
    decimal subTotal = 0;
    decimal total = 0;
    int subTotalRowIndex = 0;
    protected void gvData_RowCreated(object sender, GridViewRowEventArgs e)
    {
        subTotal = 0;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
            int ProductID = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["ProductID"]);
            total += Convert.ToDecimal(dt.Rows[e.Row.RowIndex]["Price"]);
            if (ProductID != currentId)
            {
                if (e.Row.RowIndex > 0)
                {
                    for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
                    {
                        subTotal += Convert.ToDecimal(gvData.Rows[i].Cells[3].Text);
                    }
                    this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
                    subTotalRowIndex = e.Row.RowIndex;
                }
                currentId = ProductID;
            }
        }
    }
    private void AddTotalRow(string labelText, string value)
    {
        GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
        row.BackColor = ColorTranslator.FromHtml("#FFA500");
        row.Cells.AddRange(new TableCell[4] {new TableCell { Text = labelText, HorizontalAlign = HorizontalAlign.Right},                                                          
 new TableCell (),
 new TableCell(), //Empty Cell,
 new TableCell { Text = value, HorizontalAlign = HorizontalAlign.Right }
);
        row.Cells[0].BorderColor = System.Drawing.Color.Orange;
        row.Cells[1].BorderColor = System.Drawing.Color.Orange;
        row.Cells[2].BorderColor = System.Drawing.Color.Orange;
        row.Cells[3].BorderColor = System.Drawing.Color.Orange;
        gvData.Controls[0].Controls.Add(row);
    }
    protected void gvData_OnDataBound(object sender, EventArgs e)
    {
        for (int i = subTotalRowIndex; i < gvData.Rows.Count; i++)
        {
            subTotal += Convert.ToDecimal(gvData.Rows[i].Cells[3].Text);
        }
        this.AddTotalRow("Sub Total", subTotal.ToString("N2"));
        this.AddTotalRow("Total", total.ToString("N2"));
    }
}


I hope this tutorial works for you!


Free ASP.NET 5 Hosting

Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



ASP.NET 5 Hosting - HostForLIFE.eu :: On Page Connection with ASP.NET 5

clock April 10, 2015 07:46 by author Peter

ASP.NET will gives you adaptability by they way you connect with databases. It would be ideal if you include the following code in your aspx page and check how to get connection on .aspx page. And here is the code that I used:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="onpageconnection.aspx.cs" Inherits="onpageconnection" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="System.Data" %>
<script  runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            System.Data.SqlClient.SqlConnection con;
            sqlconn objconn = new sqlconn();
            con = objconn.getcon();
            con.Open();
            String str = "select * from EmpDemo";
            //SqlCommand cmd = new SqlCommand(str,con);
            //SqlDataReader adp;
            SqlDataAdapter adp = new SqlDataAdapter(str,con);
                        DataSet ds = new DataSet();
            adp.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            //Response.Write("connection open");       
}
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
</script>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>

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 :: Configuring Your First Entity Framework in ASP.NET 5

clock April 7, 2015 12:33 by author Rebecca

If you're planning to get started with Entity Framework 7, at first you need to configuring the entity framework. The default is already there but when you need to update to the new versions, you must take a look at what is in the project.json file:

{
  /* Click to learn more about project.json  http://go.microsoft.com/fwlink/?LinkID=517074 */
  "webroot": "wwwroot",
  "version": "1.0.0-*",
  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta3",
    "EntityFramework.Commands": "7.0.0-beta3",
    "Microsoft.AspNet.Mvc": "6.0.0-beta3",

For your information, the startup.cs allowed for configuration to happen in two phases. First, the configuration of the different elements, then the registering of services with the dependency injection layer.

The service container is the dependency injection mechanism built into ASP.NET 5 and the ConfigureServices method is where that happens. Before you can add EF to the DI container, you need to get a connection string.

When I first came to ASP.NET 5, it looked as if the EF configuration would just load the connection string by convention, but it didn’t work. So I had to get it manually and add it (below) when I configured the context object.

// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services)
{
  var connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString");

The Configuration.Get method allows it to read a setting from the list of configuration sources. Then, the Configuration object is a merge of the config.json file and any environment variables. In the case of the connection string, you’re looking for a string called “ConnectionString” inside an object graph. This should look obvious once you see the config.json file:

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;..."
    }
  },
  "EntityFramework": {
    "ApplicationDbContext": {
      "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
    }
  }
}

Now that we have the connection string, what's next?

You can add Entity Framework to the services collection by adding it this code below:

// Add EF services to the services container.
services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyCountriesContext>(options =>
    {
      options.UseSqlServer(connectionString);
    });

SUMMARY

The AddEntityFramework method adds EF to the dependency injection container so it can be served if needed later. Additionally, calling AddSqlServer specifies the data store you’ll be using. Finally, the AddDbContext adds a DbContext object to the EF service. The options lambda allows us to specify the connection string. I suspect this extra step will go away at some point and just read from the configuration by convention, but at this point it’s necessary. If we need the context in another part of the system (e.g. Controllers) we can just let ASP.NET 5 serve it to us in the constructor like any other dependency injection framework.

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 :: How to Use POCO Controllers in ASP.NET 5

clock April 2, 2015 13:21 by author Rebecca

As you know, ASP.NET 5 supports POCO controllers. The controller classes doesn’t extend Controller base class. These controllers look a little bit different by some small aspects and sometime,s you may need to help framework detect our POCO controllers. In this post, I will give you complete overview of POCO controllers in ASP.NET 5.

Creating POCO controllers is simple. To use views and other goodies provided by controllers base class we have to use dependency injection to get required services to our POCO controller. If we don’t use MVC regular naming style for controllers we have to write action discovery convention and register it with built-in dependency injection service. To provide common strategy to detect POCO controllers with arbitrary names we can use special attribute or interface for this. We still can inherit our POCO controllers from classes we want. Here is the simple steps that you have to follow:

Simple POCO Controllers

First let’s define that simple controller doesn’t inherit from Controller base class. Follow the code below:

public class PocoController
{
    public IActionResult Index()
    {
        return new ContentResult() { Content = “Hello from POCO controller!” };
    }
}

And to make this controller work with views, you need some additional code.

public class PocoController
{
    private readonly IModelMetadataProvider _metadataProvider;
 
    public PocoController(IModelMetadataProvider metadataProvider)
    {
        _metadataProvider = metadataProvider;
    }
 
    public IActionResult Index()
    {
        var viewData = new ViewDataDictionary<string>(_metadataProvider);
        viewData.Model = “Hello from POCO controller!”;
 
        return new ViewResult() { ViewData = viewData };
    }
}

Now, you have basic primitive POCO controller that you can use in ASP.NET 5.

The second thing that you have to is use a small trick and call our controller just as "POCO" using this code:

public class Poco
{
    // …
}

When trying to use controller now you have run to problems like this. Why? Because ASP.NET cannot detect controller anymore.

How to make the controller is detected by default?

When sniffing around in MVC source you can find the method that MVC uses to find out if given type is controller type of not. It is done in DefaultActionDiscoveryConventions class.

public virtual bool IsController([NotNull] TypeInfo typeInfo)
{
    if (!typeInfo.IsClass ||
        typeInfo.IsAbstract ||
        typeInfo.ContainsGenericParameters)
    {
        return false;
    }
 
    if (typeInfo.Name.Equals(“Controller”, StringComparison.OrdinalIgnoreCase))
    {
        return false;
    }

    return typeInfo.Name.EndsWith(“Controller”, StringComparison.OrdinalIgnoreCase) ||
           typeof(Controller).GetTypeInfo().IsAssignableFrom(typeInfo);

If we have POCO controller andyou don’t name it as SomethingController then MVC is not considering our POCO controller as controller.

Using action discovery convention

If there are additional rules for detecting controllers, you can use action discovery conventions to tell MVC if class is constructor or not. Here is simple discovery convention class that works with our POCO controller.

public class MyActionDiscoveryConventions : DefaultActionDiscoveryConventions
{
    public override bool IsController(TypeInfo typeInfo)
    {
        var isController = base.IsController(typeInfo);
        return isController || typeInfo.Name.Equals(“Poco”, StringComparison.OrdinalIgnoreCase);
    }
}


To make MVC use this class, you have to register it with built-in dependency injection system. You will do it in ConfigureServices() method of your Startup class by calling AddTransient() method.

public void ConfigureServices(IServiceCollection services)
{
    // …
    services.AddMvc();
 
    services.AddTransient<IActionDiscoveryConventions, MyActionDiscoveryConventions>();

}

If you run your application now and try to use POCO controller it works again.

Defining ControllerAttribute

If you are building some extensible system and you need some better way how to detect controllers then besides naming controllers appropriately you can also define attribute in some API library that is available for developers.

public class ControllerAttribute : Attribute
{
}
Other developers who are building plugins for your system can decorate their controllers with this attribute.

[Controller]
public class Poco
{
    // …
}

And here is how you can detect controller in action discovery convention.

public class MyActionDiscoveryConventions : DefaultActionDiscoveryConventions
{
    public override bool IsController(TypeInfo typeInfo)
    {
        var isController = base.IsController(typeInfo);
        return isController || HasControllerAttribute(typeInfo);
    }
 
    private bool HasControllerAttribute(TypeInfo typeInfo)
    {
        return typeInfo.GetCustomAttribute<ControllerAttribute>(true) != null;
    }
}

You can also use marker interface for POCO controllers or some interface with properties and methods defined if your POCO controllers have to provide some functionalities.

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 :: 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.



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



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