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 Store Custom Objects in web.config

clock April 28, 2015 05:54 by author Rebecca

Normally, you used to have some data in appSettings section of web.config and read it when required. That is in string form, but there are lot more than this and you can update the data in web.config programmatically as well. You can store some object of custom type in web.config as well, which you normally don’t do it. But this can be very useful in several scenarios.

Have anyone tried to update some value or add some value in web.config? In this post, I'm going to tell you about web.config and how you can store the costum objects in web.config.

First, this is very common to have some constant data at appSettings section of web.config and read it whenever required. This is the way how to read data at appSettings:

//The data is stored in web.config as

<appSettings>

        <add key="WelcomeMessage" value="Hello All, Welcome to my Website." />

</appSettings>

// To read it
string message = ConfigurationManager.AppSettings["WelcomeMessage"];

If you want to update some data of appSettings programatically, you can do like this.

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings["WelcomeMessage"].Value = "Hello All, Welcome to my updated site.";
        config.Save();


If you want to add some data in appSettings, you can add some app.config data as below:

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings.Add("ErrorMessage", "An error has been occured during processing this request.");
        config.Save();


The above code is adding one new key value pair in web.config file. Now this can be read anywhere in the application.

Now, the question is, Can we store some custom data at config? The answer is YES! We can store some object. Let’s see how:

In this example, I have saved an object of my custom class NewError in web.config file. And also updating it whenever required.
To do this, Follow the below steps.

Step 1

Create a Class that inherit From ConfigurationSection (It is available under namespace System.Configuration ). Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let’s see the NewError class:

public class NewError:ConfigurationSection
{
    [ConfigurationProperty ("Id",IsRequired = true)]
    public string ErrorId {
        get { return (string)this["Id"]; }
        set { this["Id"] = value; }
    }
    [ConfigurationProperty("Message", IsRequired = false)]
    public string Message {
        get { return (string)this["Message"]; }
        set { this["Message"] = value; }
    }
    [ConfigurationProperty("RedirectURL", IsRequired = false)]
    public string RedirectionPage
    {
        get { return (string)this["RedirectURL"]; }
        set { this["RedirectURL"] = value; }
    }
    [ConfigurationProperty("MailId", IsRequired = false)]
    public string EmailId
    {
        get { return (string)this["MailId"]; }
        set { this["MailId"] = value; }
    }
    [ConfigurationProperty("DateAdded", IsRequired = false)]
    public DateTime DateAdded
    {
        get { return (DateTime)this["DateAdded"]; }
        set { this["DateAdded"] = value; }
    }
}

You can see every property has attribute ConfigurationProperty with some value. As you can see the property ErrorId has attribute:

[ConfigurationProperty ("Id",IsRequired = true)]

it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
Now if you’ll see the property closely, it is bit different.

public string ErrorId {
get { return (string)this["Id"]; }
set { this["Id"] = value; }
}

Here the value is saved as the key “id”, that is mapped with web.config file.

Step 2

Now you are required to add/register a section in the section group to tell the web.config that you are going to have this kind of data. This must be in and will be as:

<section name="errorList"  type="NewError" allowLocation="true"

     allowDefinition="Everywhere"/>

Step 3

Now one can add that object in your config file directly as:

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

Step 4

And to read it at your page. Read it as follows:

NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList");

And also a new object can be saved programmatically as

NewError objNewError = new NewError()
       {
         RedirectionPage="www.rediff.com",
         Message = "New Message",
         ErrorId="0",
         DateAdded= DateTime.Now.Date
       };
       Configuration config =
           WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

       config.Sections.Add("errorList", objNewError);
       config.Save();


Even one can add a custom group and have some custom elements in in this section. ASP.NET provides very powerfull APIs to read/edit the web.config file easily.

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 Hosting - HostForLIFE.eu :: Calling ASP.NET Page Methods using AJAX

clock April 21, 2015 06:19 by author Rebecca

In this post, I tell you how to invoke an ASP.NET page method directly from your own AJAX library. A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine. To implement PageMethod, first you need to annotate our method as WebMethod. A WebMethod is a special method attribute that exposes a method directly as XML service.

Here are the steps to create the application:

Step 1

Start a new ASP.NET Project.

Step 2

Add JQuery to your page. Then, you can add a special JQuery plugin which stringify a JSON object. And post the codes like below :

(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.

Step 3

Add the server side method to the Default.aspx page. For simplicity, you can actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something

return string.Format("Hello ! Your message : {0} at {1}", message, DateTime.Now.ToShortTimeString());
}


You should make this method static, and probably should return only serializable object.

Step 4

Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Write Your message Here : <input type="text" id="txtMessage" />
</p>
<p>
<input type="button" onclick="javascript:callServer()" value="Call Server" />
</p>
</asp:Content>


Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.

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

<script type="text/javascript">
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
</script>


The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same.

Hope it works for you!

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 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 4.5.1 Hosting UK :: Concurrent Queue in Thread Safe collections

clock August 18, 2014 07:42 by author Onit

What is Thread Safe Collection?

People use to said that writing a collection which is mutable, thread safe and usable is an extremely difficult process. Since the .NET 4 introduce the system.collection.concurrent namespace, multiple threads can safely and efficiently add or remove items from these collection without requiring additional synchronization in user code. When you write new code, use the concurrent collection classes whenever the collection will be writing to multiple threads concurrently and in this article I’ll going to show you about thread safe collection in Concurent Queue.

Concurent in .Net

Concurrent collections in .NET work very much like their single-thread counterparts with the difference that they are thread safe. These collections can be used in scenarios where you need to share a collection between Tasks. They are typed and use a lightweight synchronisation mechanism to ensure that they are safe and fast to use in parallel programming.

Concurrent queues

The Queue of T generic collection has a thread-safe counterpart called ConcurrentQueue. Important methods:

  1. Enqueue(T element): adds an item of type T to the collection
  2. TryPeek(out T): tries to retrieve the next element from the collection without removing it. The value is set to the out parameter if the method succeeds. Otherwise it returns false.
  3. TryDequeue(out T): tries to get the first element. It removes the item from the collection and sets the out parameter to the retrieved element. Otherwise the method returns false

The ‘try’ bit in the method names implies that your code needs to prepare for the event where the element could not be retrieved. If multiple threads retrieve elements from the same queue you cannot be sure what’s in there when a specific thread tries to read from it.

Example

Declare and fill a concurrent queue:

ConcurrentQueue<int> concurrentQueue = new ConcurrentQueue<int>(); 
for (int i = 0; i < 5000; i++)
{
    concurrentQueue.Enqueue(i);
}

We’ll want to get the items from this collection and check if all of them have been retrieved using a counter. The counter will also be shared among the threads using the ‘lock’ technique we saw in this post – or actually something that is similar to the ‘lock’ keyword: the Interlocked class. Interlocked has an Increment method which accepts a ref int parameter. It will increment the incoming integer in an atomic operation.

int itemCount = 0;
Task[] queueTasks = new Task[20];

for (int i = 0; i < queueTasks.Length; i++)
{
    queueTasks[i] = Task.Factory.StartNew(() =>
    {
        while (concurrentQueue.Count > 0)
        {
            int currentElement;
            bool success = concurrentQueue.TryDequeue(out currentElement);
            if (success)
            {
                Interlocked.Increment(ref itemCount);
           }
        }
    });
}

The while loop will ensure that we’ll try to de-queue the items as long as there’s something left in the collection.
Wait for the tasks and print the number of items processed – the counter should have the same value as the number of items in the queue:


Task.WaitAll(queueTasks);
Console.WriteLine("Counter: {0}", itemCount);



European FREE ASP.NET 4.5 Hosting - Germany :: ASP.NET 4.5 Shared Web Hosting Trust Level

clock April 2, 2014 08:22 by author Scott

With more and more people and companies developing websites by Microsoft .NET technology, ASP.NET 4.5 shared web hosting comes to be the major solution provided by many web hosting companies. Most of people choose an ASP.NET 4.5 web host considering about .NET framework version, ASP.NET MVC support, SQL Server database, disk space or bandwidth but they usually ignore the most important feature “IIS security level”. That determines whether the ASP.NET 4.5 websites can run successfully on the shared web host. In result to, if you developing an ASP.NET 4.5 website that works well in the local development environment and attempt to run it in the ASP.NET 4.5 shared web host, you may get the following exception,

System.Security.SecurityException: That assembly does not allow partially trusted caller

This is caused by the security level of the ASP.NET 4.5 shared web host that your application is forced to run with the limited permission, by locking down the access to server file system, preventing the background threads, or interacting with COM interfaces, etc.

ASP.NET 4.5 Web Hosting Trust Levels

 

This security level is known as the Trust Level of IIS for ASP.NET 4.5 websites

It can be configured with the following setting:

  • Full Trust: website can do everything that the account of the application pool can do on the web server. This is the most flexible configuration for running websites on the shared web hosts. You won’t have any problems unless your website accesses the system information.
  • High Trust: websites are limited to call unmanaged code, e.g. Win32 APIs, COM interop.
  • Medium Trust: websites are limited to access the file system except the website application directory, system registry, Code DOM, and more (we will talk it later), compared to High Trust.
  • Low Trust & Minimal Trust: these two options restrict the websites seriously. Even they don’t allow websites to call the service out of process, such as database, network, etc. But we never saw an ASP.NET 4.5 shared web host configured with either one of these two options.

Full Trust and Medium Trust are two widely used levels in ASP.NET 4.5 shared web hosting. The full trust provides best flexibility but it has potential security issues to the shared server, especially when the web hosting provider doesn't have rich experience on setting up Windows permission and IIS. Compared to Full Trust, you have to review the website carefully before you go with a web host only supports Medium Trust Level. You can refer to the following checkpoints for the review,

  • The website shall not call unmanaged APIs.
  • The website shall not access to file system, system registry, event logs and anything else related to the system.
  • The website shall not generate code for execution dynamically using Code DOM.
  • The website shall not use XslTransform to transform something from XML using XSLT.
  • The website has to be signed with a Strong Name.

Check with the web page from Microsoft about which namespaces and classes are not supported in Medium Trust environment. 

And here is quick way to confirm the compatibility of websites to Medium Trust Level, in the local environment,

1. Add partially trusted callers attribute into AssemblyInfo.cs file of the website project, as following code snippet,

[assembly: AllowPartiallyTrustedCallers]

2. Add the following line into the web.config,

<trust level="Medium" />

Suggestion

It's a tradeoff between these two trust level. But if you confirm that the website can run successfully with Medium Trust in your local environment, we suggest you choose an ASP.NET 4.5 web host with Medium Trust only. It shall be more secure and reliable anyway. If you host the website based on 3rd party framework such as DotNetNuke, or using 3rd party component, we recommend you going with Full Trust web host.



European ASP.NET 4.5 Hosting - Amsterdam :: New Feature Multicore JIT in .NET Framework 4.5

clock December 30, 2013 07:45 by author Scott

This articles describe one of the newest runtime features in ASP.NET 4.5. I will describe about Muticore Just-In-Compiler (JIT) in the .NET framework 4.5.

Multicore Just-in-Time (JIT) 

In the .NET framework 4.5, Microsoft has introduced an enhancement of the pervious JIT compiler by making it a Multicore JIT compiler, that runs on the two cores and supports parallelism in the compilation process in order to improve the launch performance during application startup.

From the developer point of view the Multicore JIT is a very cool runtime feature in .NET Framework 4.5 to improve their productivity and speed up the overall performance of an application. Now the developer can benefit from multicore processors to speed up the application compilation process.

The Multicore JIT compiler works in parallel with two cores. Because of the two cores, Multicore JIT can make your application start the process faster at startup. Multicore JIT provides significant improvements to Web based applications as well as Desktop Windows Presentation Foundation (WPF) applications.

Working of Multicore JIT

Nowadays, every PC has at least two cores, so the JIT compiler is built to make the investment worthwhile. Using the Multicore JIT, methods are compiled on two CPUs so that the application is able to reach the end of its startup execution quickly.

The compilation process is done in two cores that run in parallel executing the Multicore JIT compiler. The more effective Multicore JIT will reduce the startup time of an .NET application. 

Multicore JIT uses the two modes of operation.

Recording mode: It is the first mode, when JIT compiles the entire program and creates a JIT profile using a profile optimization class and saves the profile that was executed to a given folder to disk.

Playback mode: This mode is used when the application is launched subsequently. Playback mode is used to load the profile that was saved during the Recording mode from the disk using the background JIT thread in order to support the main thread.

The feature works by the JIT compiling the methods likely to be executed based on profiles created during previous compilations, that will runs on a separate processor core taking care of the JIT Compilation while the main execution thread runs on a different core.

In the ideal case, the second core quickly gets ahead of the mainline execution of the application, so whenever a method is required it is already compiled. As a result, the main thread doesn't need to do as much compilation, and your application launches faster.

In order to know which methods to compile, the feature generates profile data in the Recording mode that keeps track of the methods that are executed. Then the next time the application runs the call will look for that profile and when it finds it then it plays back; that means it starts compiling all the methods that was saved for that profile.

Note: MultiCore JIT requires a multicore machine to take advantage of its algorithms otherwise the CLR will ignore it on single core machines.

How to enable Multicore JIT in an .NET 4.5 application.

You can use this feature of the runtime to significantly improve the startup times of both client applications and Web sites in .NET framework 4.5.

Since ASP.NET applications run in a hosted environment, this feature is turned on for these applications automatically. Therefore JIT compiling using multiple cores is enabled by default in ASP.NET 4.5 and Silverlight 5.

But, if you want to disable this feature in your ASP.NET 4.5 applications then write the following code in the web.config file.

<system.web>
  <compilation profileGuidedOptimizations="None" />
</system.web>

But in a Windows based application, you will need to enable Multicore JIT feature explicitly.

Let's see how.

It is simple to use Multicore JIT, there is a class in the .NET Framework named "System.Runtime.ProfileOptimization" that you can use to start profiling at the entry point of your application. 

Optimization Profilers

The ProfileOptimization is a new type introduced in .Net 4.5 to improve the startup performance of application domains in applications that require the just-in-time (JIT) compiler by performing background compilation of methods that are likely to be executed, based on profiles created during previous compilations.

See the MSDN documentation for more information.

http://msdn.microsoft.com/en-IN/library/system.runtime.profileoptimization.aspx

The two methods that you can call at the entry point of your application.

SetProfileRoot: This method is used to specify the root path, where to save the JIT profile compiled information for optimization.

StartProfile: This method is used to start Multcore just in-time compilation.

You must write the following code in your application constructor in order to enable Multicore JIT.

public App()
{

 ProfileOptimization.SetProfileRoot(@"C:\MyAppFolder");
 ProfileOptimization.StartProfile("Startup.Profile");

}

Now that's all to enable the Multicore feature in your application; the rest of the work will be handled by the CLR automatically.



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