ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 Hosting - ASPHostPortal :: Timeout in Regular Expressions ASP.NET 4.5

clock December 10, 2015 21:07 by author Jervis

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems.

Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it. 

Try
{
    Regex regexpr =
new Regex("[A-Z ]{10}", RegexOptions.Singleline, TimeSpan.FromMilliseconds(1));
    Match mch = regexpr.Match(
"ABHISHEK SUR");
   
if (mch.Success)
        Console.WriteLine(
"Match found");
   
else
        Console.WriteLine(
"Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine(
"Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(
true);
}

Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

 You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.

Try
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(2));

    Regex regexpr = new Regex("[A-Z ]{10}", RegexOptions.Singleline);
    Match mch = regexpr.Match("ABHISHEK SUR");
    if (mch.Success)
        Console.WriteLine("Match found");
    else
        Console.WriteLine("Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine("Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(true);
}

Now this works exactly the same as the previous one. Here the Regex constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.

This is the actual code that runs in background and generates the timeouts. In fact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If you read MSDN thoroughly, it suggests to use Timeouts when specifying the Regular expressions. If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: How You Can Develop Asynchronous Device Page in ASP.Net 4.5

clock November 4, 2014 05:15 by author Ben

Within this tutorial we'll make use of the most recent ASP.Net 4.5 methods to come back up with a asynchronous gadget web page via help of Visual Studio Express.

The sample software that we're going to use listed here makes use of new async and awaits key phrases and they're obtainable in .NET 4.5 and Visual Studio 2012. This allows the complier to hold the responsibility of getting care from the complex transformations that are necessary for asynchronous programming. Also the compiler will allow you to write the code using the C#'s synchronous manage movement constructs. Therefore the compiler on its own applies the transformations which can be necessary to deploy call-backs. This is done in order to prevent blocking threads.



ASP.Net asynchronous web pages has to comprise in the Web page directive and Async feature label set to “true”. The code detailed under demonstrates the Page directive with all the value of Async attribute set to accurate for the DeviceAsync.aspx page.

<%@ Page Async="true" Language="C#" AutoEventWireup="true"
    CodeBehind="DeviceAsync.aspx.cs" Inherits="WebAppAsync.DeviceAsync" %>

The below code reflects the Device synchronous Page_Load method as well as the DeviceAsync asynchronous page. In case the browser supports the HTML5 <mark> element, the changes can be seen in DeviceAsync in yellow highlight.

protected void Page_Load(object sender, EventArgs e)
{
   var deviceService = new DeviceService();
   DeviceGridView.DataSource = deviceService.GetDevice();
   DeviceGridView.DataBind();
}

The below displays the asynchronous version:
protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDeviceSvcAsync));
}

private async Task GetDeviceSvcAsync()
{
    var deviceService = new DeviceService();
    DeviceGridView.DataSource = await deviceService.GetDeviceAsync();
    DeviceGridView.DataBind();
}

The beneath lists the changes that were applied to permit DeviceAsync page to be asynchronous.

  • This is a need to to set the Webpage directive Async attribute to "true".
  • The RegisterAsyncTask indicates is deployed to sign up an asynchronous task that includes of the code which can be operated asynchronously.
  • The new GetDeviceSvcAsync approach is labelled with the async key phrase that informs the compiler to make callbacks for parts of the body and in addition to generate a Job of its personal which is returned.
  • Should you recognize, we appened "Async" towards the asynchronous technique title although this is not required however it is the conference while you're writing asynchronous methods.
  • The return sort in the Task defines the perform in progress and offers the callers of the approach having a deal with through which to halt for your completion of the asynchronous operation. The return type in the new GetDeviceSvcAsync method is Activity.
  • Internet support call helps make use of the await keyword.
  • The asynchronous web service API was referred to as GetDeviceAsync.

GetDeviceAsync is another asynchronous method that's known as inside of the GetDeviceSvcAsync method physique. Task<List<Device>> is immediately returned by a GetDeviceAsync that will finally full on the availability of the info. For your purpose that you'd not want to proceed additional just before you have the device data, the code waits for the task making use of the await keyword. 1 might make usage of the await keyword just in techniques annotated with all the async search term.

Until finally we have the completion from the task, the thread is not blocked from the await search term. It indications up the rest of the method as being a callback within the job, and immediately returns. Within the completion in the awaited activity, that callback will likely be invoked thereby resuming the implementation from the method right exactly where it left off.

The below code displays the GetDevice and GetDeviceAsync techniques:

public List<Device> GetDevice()
{
   var uri = Util.getServiceUri("Device");
   using (WebClient webClient = new WebClient())
   {
        return JsonConvert.DeserializeObject<List<Device>>(
            webClient.DownloadString(uri)
        );
    }
}

public async Task<List<Device>> GetDevicesAsync()
{
    var uri = Util.getServiceUri("Devices");
    using (HttpClient httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(uri);
        return (await response.Content.ReadAsAsync<List<Device>>());
    }
}

The asynchronous modifications which were utilized are same as those applied to the DevicesAsync above.

  • Async key phrase was used to annotate the method signature, the return sort was changed to Task<List<Device>>, and Async was appended for the technique title.
  • The asynchronous HttpClient is utilized rather than synchronous WebClient class.
  • The await keyword was used to the HttpClient GetAsync asynchronous method.

The below image displays the asynchronous device see.

The browsers screen of the gadget info is same concerning the check out that's created by the synchronous contact. Here the only difference will be the asynchronous model might be more execute ant below main hefty loads.

Methods that are hooked up with RegisterAsyncTasks will likely be executed instantly after PreRender. 1 may also utilize async void page events directly as may be seen from the under code:

protected void Page_Load(object sender, EventArgs e) {
    await ...;
    // do work
}

The disadvantage for the async occasions is that the programmers now don't have the complete use of the occasions when activities are applied. Example, in case both an .aspx as well as a .Master signifies Page_Load occasions and a minimum of 1 of them is asynchronous, there's no guarantee from the execution.

Getting a developer, it is recommended to apply the above stated procedure to come up with the asynchronous unit web page making use of the newest ASP.Net 4.5 systems.

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: Producing Data-driven Web Apps Utilizing ASP.Net 4.5 Web Forms

clock October 16, 2014 06:30 by author Ben

Data binding is less complicated and more effective in ASP.Net 4.5 Kinds.This publish discuss about making Data-driven software using ASP.Net 4.5 preview. Additionally, it discuss about distinct Info access methods, especially about design entry binding features in Internet Types. You need to install Visual Studio 11 Developer preview to use this function.

Typical ASP.Net developer could use a single from the following Info Access mechanisms for binding the data

  • You could set up your Database Initial - Making a Schema and creating product from it. Listed here model is actually a class which you're going to communicate with your databases from your code.
  • You may setup your Product Initial - Instead of developing the database first, we design the entity model initial eg: making use of entity framework. Style your product first after which generate a schema and code.
  • You could setup your Code First- On this strategy you very first write code to design and style the product and after that produce a schema making use of that code.

Your model designer floor could search like beneath should you stick to the any of above Information Accessibility mechanisms


This post discuss the third strategy Code Very first Information Entry mechanism to connect with the databases. This method makes use of the Product Binding , the phrase barrowed from MVC. In MVC whenever you call an motion method which received some parameters in which you need to move values from question string or from cookie assortment and bind these values into parameters. Design Binding does this in MVC. The concept is comparable Web Types but context is little little bit different.

Step1 Construct courses which represent your model.

Incorporate a folder within your remedy referred to as Model and then add new item class named Issue.



The difficulty class code getting some homes which appear like as below


Consequently the above mentioned code turns into a database desk. You can discover info annotations on every home. You'll be able to specify your validation at a single spot. eg: Required in above properties.

Produce an additional class which represent the database context named IssuesDb.


Now add the connection string in web.config file with same name as your DbContext. Here it is IssuesDb.

Create another class which initializes your database as shown below

public class Dbinitializer : DropCreateDatabaseIfModelChanges<IssuesDb>

    {

      protected override void Seed(IssueDb context)

        {

            context.Issues.Add(new Issue { CreatedBy="xyz",

            CreatedOn = new DateTime(), Title="Issue1"})

            context.Issues.Add(new Issue { CreatedBy="abc",

             CreatedOn = new DateTime(), Title="Issue2"})

            context.Issues.Add(new Issue { CreatedBy="aaa",

           CreatedOn = new DateTime(), Title="Issue3"})       

      

       }

You'll be able to override the tactic See to insert some values into the produced desk.

Step2 Displaying the above specifics in UI. We will set up a Gridview to Model Binding to list the details from database table.


We are not performing anything at all new listed here , Product Binding is merge of concept from Object information resource and MVC Design Binding. Specify your ModelType and SelectMethod to point out the main points.

We will also template fields to gridview and established the binding expression to point out the values but in different way.

The normal way is one thing proven below


The problem with the above expression is we do not know the type of the column. Now you will get an intellisense inside data binding expressions with a name Item.


The GetIssues method code will look like as below


Before running your application, Initialize the database initializer class in Global.asax file Application Start method

DataBase.SetInitializer(new IssueDbInitializer());


It also creates database and tables as you specified in the model class


Step3 Now let us add a filter to this application.

Add a lable, text box and a button to UI.


Now modify GetIssues method as shown below where Model Data binding comes into the picture.


The method having a parameter named createdSince that is a textbox id and we have been telling the strategy it is a handle. You are able to go ahead and take price from parameter and filter the values as demonstrated below


Instead of finding the control and writing the code, Model Binding takes the input from the user and retrieves the values from Dbcontext.

Points to note:

There's no If !(IsPostBack) or button handlers to attain this functionality. Just get in touch with this process by passing the worth from this handle. that is it!. We will dynamically manipulate the query by just using the values in the user.

Step4 Adding a FormView which exhibits all particulars and permits you to insert and edit the issue. The FormView markup seems like as below


The GetIssue method code as below. The idea is enable autogenerated select column in gridview and show the details when you select the particular issue.


You saying to method to get the id value from issuesGrid control and return the issue details. Run the application then you will see the below result


Note that we've not composed any code to re-bind the values from database to grid. Design Binding maintain observe from the values of parameters across the submit backs. It truly retailers these values in viewstate.

The InsertMethod code seems as below


and above code you can see we are validating whether user is logged in or not and based  on that we are using ModelState to add the model error message.

ModelState represents the current state of Model Binding system on your page.

You can pass this error message to Validation Summary on your page by setting ShowModelStateErrors = true.


Another new point to notice is TryUpdateModel method which is an explicit Model Binding. This method tells model to try and bind the data from current request in to this issue variable.

The binding expression in InsertItem template in gridview will look like


Previously we do something like this


Run the application you then will begin to see the under screen


The update method exactly looks like insert method but having an additional parameter named id which is an id of record in the current Model Binding expression.


We have seen the new data-related improvements in ASP.NET 4.5 Web Forms with Model Binders and Data annotations.



ASP.NET 4.5 Hosting :: Publishing Your ASP.NET 4.5 Site with Visual Studio 2012

clock May 6, 2014 08:33 by author Ben

Microsoft Visual Studio 2012 is loaded with new capabilities for Windows 8, the web, SharePoint, mobile, and cloud development—as well as the application management lifecycle tools you need to break down team barriers and reduce cycle times to deliver value continuously.

Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

This Article can tell you how to publish your asp.net 4.5 site in vistul studio 2012.
Steps to Publish Web Application in Visual Studio 2012:
Step 1: Right click on the web project in the solution explorer window and then select the option Publish.

Step 2: Publish Web Application Window will open .Here under the option Select or Import a publish profile Select the option New in the drop down.

Step 3: In New Profile Window give any name to Profile and then click on Ok.

Step 4: Next in Connection Select the Publish method File System.

Step 5: Again in Connection for Target location select the folder on your computer where you want to publish the web application and then click on Next Button.
Step 6: In Settings Select the Configuration Release in the drop down and then click on Next Button.

Step 7: Finally in the Preview Click on Publish to Publish the web Project to  folder selected in the Step 5 above.



Best and Affordable Visual Studio 2012 Hosting with ASPHostPortal.com

We have supported site developed with
Visual Studio 2012 Hosting. Host your site on our Windows Server 2012 today. Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

For fast, secure and reliable Visual Studio 2012 Hosting, look no further than ASPHostPortal.com for all your web hosting related needs. Microsoft Visual Studio 2012 provides many new capabilities to support development on the latest platforms with modern lifecycle tools to make it easier for teams to deliver value continuously.

Visual Studio Updates help ensure you always have the best solution for building modern applications and for managing the modern application lifecycle. New to Windows Extensions, Modules, and Libraries? Ready to try out? Sign up for a FREE Trial Hosting account from ASPHostPortal.com with absolutely no cost and get going in minutes. Our Windows Server is also compatible with Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010.



Free Trial ASP.NET 4.5 Hosting with ASPHostPortal.com :: How to Resolve Unobtrusive validation on Your ASP.NET 4.5 Apps

clock April 4, 2014 08:36 by author Ben

Now, I want to tell you How to Resolve Unobtrusive validation on Your ASP.NET 4.5 Apps.

By default, ASP.NET 4.5 has changed the way validation works. On the surface, it works exactly the same as usual, but under the hood, now it uses by default a new kind of unobtrusive validation based in jQuery, instead of the previous default scripts.

Now, the client-side validation is made in a simpler way by using the jQuery validation plugin, and by decorating the different controls with “data-val” attributes, instead of polluting your page with a lot of validation scripts.

For example, this is the resulting HTML for a Requiredvalidator control when you are using the unobtrusive validation mode:


<span
id="RequiredFieldValidator1"
data-val-controltovalidate="TextBox1"
data-val-focusonerror="t"

data-val-errormessage="Required!"

data-val-display="Dynamic"
data-val="true"
data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"

data-val-initialvalue=""
style="color:Red;display:none;">Required!</span>


Notice all those “data-val” attributes. By simply inspecting this code you can easily tell how this validation control is behaving. That’s great!

However, if you create a new Empty Web Application using Visual Studio 2012 or later and add a validation control to one page, when you run the app you’ll get this error screen:

 


“UnobtrusiveValidationMode requires a ScriptResourceMapping for jQuery”
You get this error because the validation scripts search for a script resource called “jquery”, and it’s not present in your app.

You have several options to make it work correctly:

1. Disable the unobtrusive validation on a per-page fashion.
This enables again the former validation system from previous ASP.NET Web Forms versions (up to v.4.0).
Doing this bay hand is tedious if you have more than one or two pages, but is easy. You just need to add this line to the Load event of your page:
   
Page.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;

2. Disable de unobtrusive validation for the whole app.
For achieving this you just need to add one line to our web.config file, under the app.settings node, like this:

<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

</appSettings>


3. Add a ScriptResourceMapping for jQuery, as indicated in the error page.
For achieving this, first you need to download the latest version of jQuery. Download both available editions (the production and development one) and copy those .js files to a “scripts” folder in your app’s root folder.

Now we need to add the Global.asax file to your project. In the Application_Start event you need to define a new ScriptResourceMapping with the name “jquery”, so that the framework knows where to get the jQuery scripts.
This is the needed code in C#:

protected void Application_Start(object sender, EventArgs e)

{

    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",

                new ScriptResourceDefinition

                {

                    Path = "~/scripts/jquery-1.8.3.min.js",

                    DebugPath = "~/scripts/jquery-1.8.3.js",

                    CdnPath = "http://<a title="ajax" href="#">ajax</a>.aspnetcdn.com/<a title="ajax" href="#">ajax</a>/jQuery/jquery-1.8.3.min.js",

                    CdnDebugPath = "http://<a title="ajax" href="#">ajax</a>#"

                });

}

Don’t forget to include a:

using System.Web.UI;


at the beginning of the page.

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Page Instrumentation in ASP.NET 4.5

clock December 27, 2013 11:03 by author Robert

 

In this article, I showed you how to use Page Instrumentation, a new  feature in ASP.NET 4.5 which might be useful for you during debugging.
ASP.NET 4.5 include a hidden gem called Page Instrumentation, very few people aware of this gem. You can use page instrumentation in ASP.NET 4.5 WebForm and MVC 5 or 4(assuming it targets 4.5). It allows you to inspect/instrument a web form or a mvc view during the rendering process. Page instrumentation are useful in scenarios when you have some performance issues regarding view engine rendering. In this article, I will show you how to use this feature in ASP.NET 4.5.

To start instrumenting a page, you need to inherit PageExecutionListener class.

The BeginContext will be called by a view engine before it renders the output for the specified context. Similarly, EndContext called by a view engine after it renders the output for the specified context. Both of these methods accept PageExecutionContext class as a parameter which have the following members.

All the properties of PageExecutionContext class are self explanatory. Let assume we have the following MVC view(for understanding how many times and when the BeginContext and EndContext will be invoke by the framework).

The Razor View Engine will emit the following C# code


Finally, here is a simple implementation of PageExecutionListener class which calculates the total time each time whenever something is written to the output response.

 



ASP.NET 4.5 Hosting with ASPHostPortal.com :: How to Send E-mail using ASP.NET 4.5

clock December 7, 2013 11:41 by author Mike

If you build a large site then you will be required to provide a facility for the users to contact the relevant department or web master through online form. This is the best way to prevent spam messages as users will not know the real e-mail id. The whole process of sending emails from an ASP.NET form has been simplified with the release of .NET Framework 4.5.

Look at the below figure where I added few Textbox controls.


Figure_1


You need to substitute FROM EMAIL ID, MAIL SERVER NAME, EMAIL ID and PASSWORD on the below code with relevant correct values.

Copy the code given below after providing correct values as mentioned above using Notepad, save it as an .aspx file and upload to your web server. The below code requires access to a shared Windows hosting server with ASP.NET 4.5:

<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
 
<script runat="server">  
 
    Protected Sub btnSubmit_Click1(sender As Object, e As EventArgs)
        Dim mail As New MailMessage()
 
        mail.To.Add(txtEmail.Text)
        mail.From = New MailAddress("FROM EMAIL ID")
        mail.Subject = "Contact Form"
 
        mail.Body = txtName.Text & vbCrLf & txtComments.Text
 
        Dim smtp As New SmtpClient("MAIL SERVER NAME")
        smtp.Credentials = New NetworkCredential("EMAIL ID", "PASSWORD")
 
        smtp.Send(mail)
        lblStatus.Text = "Your data has been submitted successfully"
        txtName.Text = ""
    txtEmail.Text = ""
    txtComments.Text = ""
 
    End Sub
</script>
 
<html>
 
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Contct Form Demo</title>
</head>
 
<body>
    <form id="form1" runat="server">
        Name -
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <br />
        Email -
        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
 
ErrorMessage="Please Enter Valid Email ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)
 
*"></asp:RegularExpressionValidator>
        <br />
        <br />
        Comments -
        <asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="71px" Width="301px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblStatus" runat="server"></asp:Label>
        <br />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click1" />
        <br />
        <br />
    </form>
</body>
</html>

Figure_2

In the above code, I have enabled validation for E-mail ID field. This means that if you forgot to enter e-mail id in correct format you will not be able to submit the form.

Looking for quality ASP.NET 4.5 Hosting? Look no further than ASPHostPortal.com Hosting!



ASP.NET 4.5 Hosting :: Regex (Regular Expressions) Time Out In ASP.NET 4.5

clock November 13, 2013 07:13 by author Ben

One of new features from ASP.NET 4.5 is Regex. Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it.



Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.



Now this works exactly the same as the previous one. Here the Regex(new feature of ASP.NET 4.5) constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.



This is the actual code that runs in background and generates the timeouts. Infact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  I hope you like it. More to come shortly.



ASP.NET 4.0 Hosting - ASPHostPortal.com :: Handling Error HTTP Error 500.19 - Internal Server Error - There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler'section defined

clock September 18, 2013 11:08 by author Ben

have you ever come across this error when you try to run your website from localhost??




and when I looking for the real problem in production server, I understand that version. NET Framework that I use is 4.0. for that I need to replace the actual version .NET Framework version 2.0.



Here is a short step to change. NET version:

1. Open your IIS ( for this article i use IIS 8)
2. Click your Application Pool (Before that, make sure your dedicated pool was tick on your server) and search your domain name.
    You'll find that your .NET Framework version is 4.0. (this version is default by plesk control panel 11)
3. Click Basic Setting.

4. then change .NET Framework version to 2.0 - Ok


5. Yeah.. now you can reload your web browser and check your website.

 



ASP.NET 4.5 Hosting :: How to Password-Protect Web Pages Using .htaccess Files

clock September 13, 2013 07:34 by author Mike

A .htaccess file (pronounced ‘dot aitch tee access’ or simply ‘aitch tee access’) is aspecial configuration file used on web servers running the Apache httpd web server software. When someone visits a page that is sitting in a directory alongside, or in the same branch as, a .htaccess file then that configuration file will be loaded by the server and processed.

.htaccess files are used to reconfigure the web server without needing to restart it. These files can be used to enable or disable additional functionality and features, such as creating redirects, disabling directory listings and password protecting directories.

If you want to password protect some of your web pages, then you need to use a .htaccess file with a .htpasswd password file. This tutorial will tell you step-by-step what you need to do.


Step By Step Instructions
Let's suppose you want to restrict files in a directory called members to username memberone with password memberonepassword. Here's what to do:
1. Create a file called .htaccess in directory members that looks like this:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd
require valid-user


Notes
:

  • In the AuthUserFile line, replace USERNAME with your ftp username.
  • The .htaccess file must be an ASCII text document.
  • A .htaccess file can be created in any word processor but must be saved as text only.
  • IF you upload your .htaccess file via FTP, the FTP client must be set to ASCII mode for transfer.
  • For security reasons, the .htaccess file on the server cannot be seen in a directory listing. If you don't see it after uploading it, don't worry.
    Also note that AuthName can be anything you want. The AuthName field gives the Realm name for which the protection is provided. This name is usually given when a browser prompts for a password, and is also usually used by a browser in correlation with the URL to save the password information you enter so that it can authenticate automatically on the next challenge.

2. Use the htpasswd command, from your home directory, to create a password file called .htpasswd in your home directory:
SSH to your home directory. This is simply done by connecting with your SSH client and NOT entering any path, and NOT changing directories after connecting. After connecting to your home directory via SSH, enter:

# htpasswd -c .htpasswd memberone

Type the password -- memberonepassword -- twice as instructed.
3. That's the setup done. Now test by trying to access a file in the directory members; your browser should demand a username and password, and not give you access to the file if you don't enter memberone and memberonepassword.


Multiple Usernames/Passwords

If you want to give access to a directory to more than one username/password pair, follow the steps above to create the .htaccess file and to create the .htpasswd file with one user. Then, add additional users to the .htpasswd file by using the htpasswd command without the -c:

# htpasswd .htpasswd membertwo
New password:
Re-type new password:
Adding password for user membertwo


Changing Passwords

If you want to change the password for an existing user, simply issue the same command as when you added the user. You will then be prompted for a new password. For example, if the user membertwo already exists and you want to change the password, just SSH to your home directory and enter:

# htpasswd .htpasswd membertwo


Password Protecting Multiple Directories
If you want to password protect multiple directories, and allow all users access to all password protected directories, then all you need to do is put the same .htaccess file in each directory that you want to password protect.

However, if you want to password protect multiple directories, and only allow certain users access to each directory, then you can create a different password file (all in your home directory) for each password protected directory.

Let's say you have 3 different directories (members, admins, board) you want password protected, and each one has a different set of users that you want to allow access. Then just do the following:

Create three .htaccess files and put them in their appropriate directory:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.members
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.admins
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.board
require valid-user

Remember to replace USERNAME with your ftp username (in lower case).

Create three .htpasswd files in your home directory:

# htpasswd -c .htpasswd.members memberone
# htpasswd -c .htpasswd.admins adminone
# htpasswd -c .htpasswd.board boardmemberone

That's it. Now when you need to add a user to one of the directories, just issue the htpasswd command on the appropriate .htpasswd file.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in