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

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>

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:

RequiredFieldValidator

CompareValidator

CustomValidator

RangeValidator

RegularExpressionValidator

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

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>

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

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:

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.

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:

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.

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.

Authorization filters and action filters have been around for a while in ASP.NET Web API but there is this new authentication filter introduced in Web API 2. Authentication filters have their own place in the ASP.NET Web API pipeline like other filters. Historically, authorization filters have been used to implement authentication and there is ton of samples out there with all kinds of authentication implemented in authorization filters. Web API 2 introduces the authentication filter so that authentication concerns can be separated out of authorization filter and put into an authentication filter.

This blog post is just a quick introduction to writing a custom authentication filter for implementing HTTP Basic Authentication. There is a full-blown example here, if you are interested in writing a production-strength filter.First up, we create the filter class BasicAuthenticator implementing the IAuthenticationFilter interface. We also derive from Attribute so that we can apply the filter on action methods, like so.

For basic authentication, when there is a 401, we are supposed to send WWW-Authenticate header and the right place to write such challenge related logic will be the ChallengeAsync method. This is where things get interesting because it is not so straight forward to add headers here. The recommended approach is to create a class implementing IHttpActionResult and set an instance of it to context.Result, like so.

However, this approach will not work with MVC since there is no ResponseMessageResult. For the sake of consistency, it is better to create our own class. Also, the code above changes the pipeline behavior slightly. For these reasons, it is recommended to create a class implementing IAuthenticationFilter (the initial approach in this post).

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.