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

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.



European ASP.NET Hosting - France :: How to Improve your ASP.NET Web API Performance

clock February 24, 2015 08:46 by author Scott

In this article, I will share about how to improve your ASP.NET Web API performance

1. Use fastest JSON serializer

JSON serialization  can affect overall performance of ASP.NET Web API significantly. A year and a half I have switched from JSON.NET serializer on one of my project to ServiceStack.Text .

2. Use other formats if possible (protocol buffer, message pack)

If you can use other formats like Protocol Buffers or MessagePack in your project instead of JSON do it.

You will get huge performance benefits not only because Protocol Buffers serializer is faster, but because format is smaller than JSON which will result in smaller and faster responses.

3. Implement compression

Use GZIP or Deflate compression on your ASP.NET Web API.

Compression is an easy and effective way to reduce the size of packages and increase the speed.

4. Use Caching

If it makes sense, use output caching on your Web API methods. For example, if a lot of users accessing same response that will change maybe once a day.

5. Implement async on methods of Web API

Using asynchronous Web API services can increase the number of concurrent HTTP requests Web API can handle.

Implementation is simple. The operation is simply marked with the async keyword and the return type is changed to Task.

[HttpGet] 
public async Task OperationAsync() 
{  
    await Task.Delay(2000); 
}

6. Use classic ADO.NET if possible

Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

Please just see this table performance below

The Dapper and the hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

LLBLGen with resultset caching is very fast, but it fetches the resultset once and then re-materializes the objects from memory.

Hope above tutorial help you.



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 ASP.NET 4.5 Hosting - Spain :: How to Count Your Visitors on Website Using ASP.NET C#

clock August 5, 2014 06:22 by author Scott

This is only simple tutorial how to count number of visitors to a website in asp.net using C#. Just only brief description and hope you enjoy this tutorial

1. First thing to do is open Global.asax file and write the code as shown below

void Application_Start(object sender, EventArgs e)
{
Application["VisitorCount"] = 0;
}

void Session_Start(object sender, EventArgs e)
{
Application["VisitorCount"] = (int)Application["VisitorCount"] + 1;


void Session_End(object sender, EventArgs e)
{
Application["VisitorCount"] = (int)Application["VisitorCount"] - 1;
}

2. Now open your aspx page in which you want to show the count and write the following code.

<div>
<asp:Label ID="lbl_Count" runat="server" ForeColor="Red" /> 

</div>

3. You’ll see the below code in the cs file on page load event

protected void Page_Load(object sender, EventArgs e)
{
lbl_Count.Text = Application["VisitorCount"].ToString();
}

Good luck and hope this tutorial help



European ASP.NET Hosting - Germany :: How to Fix - The specified string is not in the form required for an e-mail address

clock July 10, 2014 09:08 by author Scott

Hello, in this post, I will describe short tutorial about how to solve The specified string is not in the form required for an e-mail address. I found many people find this error on forums. Here is the error message:

As you can see above, that is the error message that you might find. So, what’s the problem?

OK, the problem in this case is not from the page itself, but it comes from your web.config file. This configuration file has a <system.net /> element that enables you to store information about the mail server and the from account. I will give you 2 examples below how it will crash your page:

<system.net>
  <mailSettings>
    <smtp from="you.yourprovider.com">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

Please see the missing @ symbol in the mail address. And other error may come from incorrect encoded angled brackets, see this:

<system.net>
  <mailSettings>
    <smtp from="Your Name &lt;[email protected]">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

This from attributes has an opening < character (encoded as &lt;) but lacks the closing > bracket. To avoid the error, make sure the e-mail address in the from attribute has a valid syntax and uses the right angled brackets (if you use both a name and an e-mail address) like this:

<system.net>
  <mailSettings>
    <smtp from="Your Name &lt;[email protected]&gt;">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

If you are curious why your code crashed, then you can use Reflector and take a look in the class’s constructor code:

public MailMessage()
{
  this.body = string.Empty;
  this.message = new Message();
  if (Logging.On)
  {
    Logging.Associate(Logging.Web, this, this.message);
  }
  string from = SmtpClient.MailConfiguration.Smtp.From;
  if ((from != null) && (from.Length > 0))
  {
    this.message.From = new MailAddress(from);
  }
}

Here you can see that the code uses the (internal and static) MailConfiguration property of the SmtpClient class that in turn provides access to the From name and address. This name and address value is then passed into the constructor of the MailAddress class which performs the actual validation using its private ParseValue method.

Choosing Best ASP.NET Hosting with HostForLIFE.eu

We know that it is quite hard to find good asp.net hosting in Europe. Why you need to choose us to be your hosting partner?


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/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.



Free ASP.NET 4.5 Cloud Hosting Spain - HostForLIFE.eu :: Count Number of Nodes in XML File in ASP.NET 4.5

clock May 6, 2014 06:00 by author Peter

Here I will explain how to count number of records in xml file in C# using ASP.NET 4.5 Cloud Hosting Spain or how to count number of nodes in xml file in asp.net using C# and VB.NET or count number of elements in xml file in C#.

In previous articles I explained insert xml data to sql table using stored procedure, Bind xml data to dropdown/gridview in asp.net, create online poll system with percentage graphs in asp.net and many articles relating to xml, Gridview, SQL, jQuery,asp.net, C#,VB.NET. Now I will explain how to count number of records in xml file in C# using ASP.NET.

To count number of nodes from xml file we need to write the code like as shown below

XmlDocument readDoc = new XmlDocument();
readDoc.Load(MapPath("Sample.xml"));
int count = readDoc.SelectNodes("CommentsInformation/Comments").Count;
lblcount.InnerHtml = "Number of Records: "+ count;

If you want to see it in complete example we need to write the code like as shown below
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 100px">
Name:</td>
<td style="width: 100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Email:</td>
<td style="width: 100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr><td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td>
</tr>
</table>
<br />
<label id="lblcount" runat="server" />
</div>
</form>
</body>
</html>

After that add XML file to your application and give name as "Sample.xml" then add root element in xml file otherwise it will through error. Here I added CommentInformation as root element in XML file.
<?xml version="1.0" encoding="utf-8"?>
<CommentsInformation>
 </CommentsInformation>

After that add this namespace in codebehind

C# Code
using System;
using System.Xml;

After that add below code in code behind

protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("Sample.xml"));
XmlElement parentelement = xmldoc.CreateElement("Comments");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = txtName.Text;
XmlElement email = xmldoc.CreateElement("Email");
email.InnerText = txtEmail.Text;

parentelement.AppendChild(name);parentelement.AppendChild(email);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Sample.xml"));
XmlDocument readDoc = new XmlDocument();
readDoc.Load(MapPath("Sample.xml"));
int count = readDoc.SelectNodes("CommentsInformation/Comments").Count;
lblcount.InnerHtml = "Number of Records: "+ count;
}

VB.NET Code
Imports System.Xml
Partial Class vbcode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim xmldoc As New XmlDocument()
xmldoc.Load(Server.MapPath("Sample.xml"))
Dim parentelement As XmlElement = xmldoc.CreateElement("Comments")
Dim name As XmlElement = xmldoc.CreateElement("Name")
name.InnerText = txtName.Text
Dim email As XmlElement = xmldoc.CreateElement("Email")
email.InnerText = txtEmail.Text
parentelement.AppendChild(name)
parentelement.AppendChild(email)
xmldoc.DocumentElement.AppendChild(parentelement)
xmldoc.Save(Server.MapPath("Sample.xml"))
Dim readDoc As New XmlDocument()
readDoc.Load(MapPath("Sample.xml"))
Dim count As Integer = readDoc.SelectNodes("CommentsInformation/Comments").Count
lblcount.InnerHtml = "Number of Records: " & count
End Sub
End Class



Free ASP.NET 4.5 Hosting Spain - HostForLIFE.eu :: ASP.NET Validation Controls.

clock April 29, 2014 09:01 by author Peter

Today I will discuss about the various validation control that ASP.NET Hosting provide and benefit of using it over client side validation. ASP.NET validation control provide two ways validation. i.e. both Server side and Client side. They perform client-side validation if after confirming that browser allows client side validation(i.e JavaScript is enabled), thereby reducing the overhead of round trip. If client side validation is disabled, it will perform the server side validation. All this from detection to validation is all taken care by the ASP.NET.

In total ASP.NET provide 5 + 1(ValidationSummary) validation control:

  1. RequiredFieldValidator 
  2. CompareValidator
  3. CustomValidator
  4. RangeValidator
  5. RegularExpressionValidator 
  6. ValidationSummary Control      

will discuss about all the control in detail, but before that i will elaborate the attributes that are common to all the controls. 

1. Display - This attribute is used to display the error message. It takes 3 options

  • None: This will ensure that no error message is displayed. Used when Validation summary is used.
  • Static: This will ensure that space on the  page is reserved even if validation pass. i.e. Real estate area on the page will be allocated.
  • Dynamic: This will ensure that space for error message is reserved only if validation fails.

In short static and dynamic do exactly the same thing. Difference between them is that in case of static Style for the <span> is

style="visibility: hidden; color: red;"

and in case of Dynamic Style for span is

style="display: none; color: red;"

2. ControlToValidate - This attribute is used to get the control on which validation is to applied
3. EnableClientScript - Boolean value to indicate whether client- side validation is enabled or not. Default value is true.
4. IsValid - Boolean value to indicate whether the control mention is ControlToValidate attribute is valid or not. Default value is true.
5. Enabled - Boolean valued to indicate if Validation control is enabled or not. Default value is true.
6. ErrorMessage - This is the text message that will be displayed in the validation summary.

RequiredFieldValidator Control
As the name suggest, this validation control make sure that control mention in ControlToValidate cannot be empty.
<asp:TextBox ID="txtSampleTextBox" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ID="reqfldValidator" runat="server" ControlToValidate="txtSampleTextBox" 
Enabled="true" Display="Dynamic" ErrorMessage="Required" ToolTip="Required">
*</asp:RequiredFieldValidator>

CompareValidator Control
This Control is used to compare the value or one control to the value of another control or to a fixed value. One catch here is that validation pass if both the fields are empty. To handle that one require to apply Required field validator along with CompareValidator.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:TextBox ID="txtTextBox2" runat="server" />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtTextBox1" ControlToCompare="txtTextBox2" Display="Dynamic" ValidationGroup="MyGroup" ToolTip="No Match">*</asp:CompareValidator>

ControlToCompare - This take the Id of control with which comparison is being done.
Comparison can be made on following data types: Currency, Date, Double, Integer and String

RangeValidator
As the name suggest this control is used to make sure that data entered by the user fall within the specified range. Again as for Compare validator validation will pass if input control is empty. Use RequiredFieldValidator to fix this issue.
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtTextBox1" MaximumValue="800"
MinimumValue="5" ValidationGroup="MyGroup" Display="Dynamic" Type="String" ToolTip="Error">*</asp:RangeValidator>

A little explanation for this validator. It has a Type attribute that signifies the datatype for Range. In above example datatype is string with MinimumValue="5" and MaximumValue="100". The validation goes like it will accept all the value that satisfy the regex ^[5-8]+$. A little confusing but will get clear after 2 3 reading.

RegularExpressionValidator
This is one of my favorite validator control. This control provide maximum level of flexibility to the developer and almost all the validator control function can be achieved using this validator control. RegularExpressionValidator control has attribute ValidationExpression that is used to specify the regular expression that is used to validate the input control.

<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"  

ControlToValidate="txtTextBox1"
ValidationGroup="MyGroup" Display="Dynamic" ValidationExpression="^[5-8]+$" ToolTip="Error">*</asp:RegularExpressionValidator>

CustomValidator Control: Custom validator control is used to capture the validation that cannot be handled by the validator controls provided by ASP.NET. Here user is at the freedom to define his own custom method, both Client side and Server side. 
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:CustomValidator runat="server" ClientValidationFunction="YouClientValidationFunction" ControlToValidate="txtTextBox1" ID="cstmValidatorControl" OnServerValidate="ServerSideMethod" ValidateEmptyText="true" ToolTip="Error">*</asp:CustomValidator>

ValidateEmptyText  is a boolean attribute that if set to true, the input control will be validated even if it is empty.
ClientValidationFunction contains name of client validation function.
OnServerValidate contains name of server validation function.

ValidationSummary Control
This control is used to display the list of all the validation error that has occurred on the page. The error message displayed is the one set for the ErrorMessage attribute of the validation control. No error message will be displayed if this attribute is not set.  
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtTextBox1" ValidationGroup="MyGroup" Display="Dynamic" ValidationExpression="^[5-8]+$" ErrorMessage="Error" ToolTip="Error">*</asp:RegularExpressionValidator>

<asp:Button runat="server" ID="Button1" ValidationGroup="MyGroup" Text="Submit" />
<asp:ValidationSummary runat="server" ID="ValidationSummary1" ShowMessageBox="true" ValidationGroup="MyGroup" ShowSummary="true" DisplayMode="BulletList" />

DisplayMode has three options List, BulletList and SingleParagraph
ShowMessageBox when set to true will display the error as a alert popup
ShowSummary will display the error on the page. By default it is true.



Free Italy ASP.NET 4.5 Hosting - HostForLIFE.eu :: Programmatically Clearing The ASP.NET Cache For Web Forms and MVC Pages

clock April 16, 2014 06:01 by author Peter

Page level caching for ASP.NET 4.5 web forms and MVC websites is pretty awesome, because it allows you to implement something that's quite complex; multilevel caching, without having to really understand too much about caching, or even write much code. But what if you want to clear a cached ASP.net page before it's due to expire.

What page caching aims to achieve

When developers turn to caching pages in their ASP.net websites, usually it's because of one thing; the need for speed. When our code bases start to require continual requests to a data store, be it disk or database, that doesn't change too much overtime, caching is usually the first hammer we turn to to minimise fetching from slower stores. ASP.NET Web Forms and ASP.Net MVC both make this a pretty trivial thing to do by hiding the complexity of cache providers behind simple attributes to either your .aspx pages or controller actions:

WebForms page output caching example:

<%@ OutputCache Duration="300" VaryByParam="productId" %>
ASP.net MVC controller caching:
[OutputCache(Duration = 300, VaryByParam = "prodId")]
public ActionResult ProductDetails(string prodId)
{

}
}

The above is awesome because it's simplicity, but you'll notice one key thing here: I've set my cache expiry to 300 seconds. This is primarily because I want the content to pull from the source now and then just in case something has changed. I've used 300 seconds, but really the time may be inconsequential – I've just set it to an arbitrary number that I deemed would meet my needs.

This doesn't really use the cache as well as it could be used in many scenarios, the primary one being during a period where my site isn't being updated, and the content only changes once every few days/weeks/months. The .NET tooling attempts to allow for these situations by having support for providers like the SQLCacheDependency you can add to your application. But the SQL cache provider or even a CustomCacheProvider don't give you the fine grain control you really want: being able to programmatically remove page, control, action or child-action level cached pages. Like most great things: simple and elegant ASP.net does support this out of the box – you just don't hear about it much. You can tell the runtime to remove cached pages and controls simply by using a very simple recursive API that refers to it's relative URL.

// remove any webforms cached item with the wildcard default.aspx*
HttpResponse.RemoveOutputCacheItem("/default.aspx");
// just remove the webforms product page with the prodId=1234 param
HttpResponse.RemoveOutputCacheItem("/product.aspx?prodId=1234");
// remove my MVC controller action's output
HttpResponse.RemoveOutputCacheItem(Url.Action("details", "product", new { id = 1234 }));

You'll notice for the MVC page's cache reference I used the Url.Action helper, and I recommend this, as it uses the same MVC routing as the cache provider – usually taking the first route found. Using the Url.Action helper means your provided Url follows the same path in reverse to that of the cache provider. For MVC child actions there is currently no way that I know of clearing individual control's caches. MVC controller child actions are stored in the ChildActionCache. To clear the entire child action cache you can do the following:

OutputCacheAttribute.ChildActionCache = new MemoryCache("NewRandomStringNameToClearTheCache");

Obviously this is a pretty aggressive approach, but if you would like to do this in a more granular fashion, try the open source project MVC Doughnut caching instead.



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.



FREE ASP.NET 4.5 Spain Hosting – HostForLIFE.eu :: GridView and Export to Excel

clock March 29, 2014 18:18 by author Peter

This is very simple to implement in ASP.NET 4.5 Hosting. But, there are possibilities to get problems in exporting to excel from grid view. When you bind data to gridview and write some logic to export to excel then it will not be enough. We have to check or write some additional logic which will help us to solve the problems. Below is the explanation for all problems we may get in the complete process along with detailed solution. You may encounter below errors when you try to implement the export to excel for gridview.

Control of type "GridView" must be placed inside of the form tag with runat="server"
This is very well known error to ASP.NET developers and by seeing it, we think that the control is not inside the form with runat server. But this is not correct. This error will come even if we put the GridView inside form with runat server. The reason is, in the export to excel logic we are calling RenderControl() method of GridView. So, to render it without any issues we have to override the "VerifyRenderingInServerForm" in our code.  Below is the syntax of the event. Add this to the c# code in code behind file. Remember this event is a Page event means this method you should place in ASPX page. If you are using user control to implement this export to excel logic then below are the ways to go.

1. If your user control is using by less than 3-4 pages then go to each and every page and add this event to the page.

2. If your user control is using by more than 5 pages then the best solution is to create a base page [Which inherits from System.Web.UI.Page class] and all your ASPX pages should inherit from this base page.public override void VerifyRenderingInServerForm(Control control)  

{  
    //Confirms that an HtmlForm control is rendered for the specified ASP.NET   
    //server control at run time. 
}  

Now, after we added the event to page, the error will go away for sure. Even when you add the above code/event to the page, this is not enough if you have the paging, sorting enabled on gridview. If you enable paging or sorting then you encounter the below error.

"RegisterForEventValidation can only be called during Render();"

This error is coming because we are doing paging and sorting. If no paging or sorting enabled this error will not come. To resolve this error, please follow below steps.

1. In your export to excel button click event, first disable the paging, sorting on gridview and do data bind.
2. Call export to excel logic.
3. Re-enable paging, sorting on gridview and databind.

Below is the logic we have to use in export to excel button click event.

gvReport.AllowPaging = false;  
    gvReport.AllowSorting = false;  
    gvReport.DataBind();  
    ExportToExcel();//Method to use export to excel.  
    gvReport.AllowPaging = true;  
    gvReport.AllowSorting = false;  
    gvReport.DataBind();   

Now, you are clear with all errors and the logic will export all data in gridview to excel.

FYI, I am placing a sample of ExportToExcel() functionality here.

private void ExportToExcel()  
    {  
        Response.Clear();  
        Response.AddHeader("content-disposition", string.Format("attachment;filename=excel_report.xls"));  
        Response.Charset = ""; 
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        Response.ContentType = "application/vnd.xls";  
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();  
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);  
        gvReport.RenderControl(htmlWrite);  
        Response.Write(stringWrite.ToString());  
        Response.End();  
    } 

Note: gvReport is the gridview control name in my example. And there are lot of posts in internet guide you incorrect to resolve the above error. For example, they will say set EnableEventValidation="false" in the <%@ Page directive Or disable validation in web.config level to resolve the error. Please do not set it.



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