ASP.NET 4.5 Hosting BLOG

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

ASPHostPortal.com Announces ASP.NET Core 1.0 Hosting Solution

clock April 26, 2016 23:37 by author Dan

ASPHostPortal.com is a well-known Windows hosting company and even one of the most famous, though it is one of the oldest Windows hosting companies. Our packages have gone through major changes recently, and all of them goes for the goodness of every customers. Today, we launch ASP.NET Core 1.0 hosting with interested hosting packages.

3 months ago, the ASP.NET team announced during the weekly ASP.NET Community Standup was decided to rename ASP.NET 5 to ASP.NET Core 1.0. The whole “ASP.NET 5 MVC 6 Web API 2 sub-component version scheme was confusing. They’ve been working towards “One ASP.NET” now for years and they’re there. ASP.NET Core is versioned as 1.0 as it’s a near complete rewrite of ASP.NET with many new features and capabilities. It’s clearly a different product than ASP.NET 4.6.

.NET Core is a modular, streamlined subset of the .NET Framework and CLR. It is fully open-source and provides a common set of libraries that can be targeted across numerous platforms. Its factored approach allows applications to take dependencies only on those portions of the CoreFX that they use, and the smaller runtime is ideal for deployment to both small devices (though it doesn’t yet support some) as well as cloud-optimized environments that need to be able to run many small applications side-by-side. Support for targeting .NET Core is built into the ASP.NET 5 project templates that ship with Visual Studio 2015.

ASPHostPortal.com offers ASP.NET Core 1.0 Hosting with an interested hosting plan. We support this new technology with affordable price, a lot of ASP.NET features, 99.99% uptime guarantee, 24/7 support, and 30 days money back guarantee. We strive to make sure that all customers have the finest web-hosting experience as possible. To learn more about our ASP.NET Core 1.0 Hosting, please visit http://asphostportal.com/ASPNET-Core-1-0-Hosting

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.NET Hosting - ASPHostPortal.com :: How to Add the Store Locator in ASP.NET MVC Application

clock April 22, 2016 23:13 by author Dan

Recently, a reader wrote in and asked what steps would be necessary to include a “Directions” link with each marker in the map so that, when clicked, the user would see the driving directions from the address they entered and the store of interest. I decided to update the ASP.NET MVC application to include this new feature request. Now, the results page shows a “Directions” link in both the grid of nearby stores and in the info window that pops up when you click a map marker. Clicking the “Directions” link opens a new browser window and loads Google Maps, showing the directions from the user-entered address to the selected store’s address.

To show the driving directions I send the user to the following URL: http://maps.google.com/maps?f=d&source=s_d&saddr=startingAddress&daddr=destinationAddress.

When the user is sent to the store locator page, the user-entered address (a/k/a, the starting address) is passed through the querystring via a field named Address, so we already know the starting address. But how do we get our hands on the destination address? Recall that view is passed a model that is a collection of NearbyStoreLocation objects; the NearbyStoreLocation class has properties like Address (the street address), City, Region, PostalCode, and so forth. We can build up the address by concatenating these various address parts.

Rather than requiring the view to build up the address, I added a new read-only property to the NearbyStoreLocation class named FormattedAddress, which returns an address Google Maps can parse by piecing together the address-related properties into a string.

public string FormattedAddress
{
get
{
var addrPieces = new List<string>(5);
if (!string.IsNullOrEmpty(this.Address))
addrPieces.Add(this.Address);
if (!string.IsNullOrEmpty(this.City))
addrPieces.Add(this.City);
if (!string.IsNullOrEmpty(this.Region))
addrPieces.Add(this.Region);
if (!string.IsNullOrEmpty(this.CountryCode))
addrPieces.Add(this.CountryCode);
if (!string.IsNullOrEmpty(this.PostalCode))
addrPieces.Add(this.PostalCode);
return string.Join(", ", addrPieces.ToArray());
}
}

In the view, the link to the directions can be build like so:

<a target="_blank" href="http://maps.google.com/maps?f=d&source=s_d&saddr=<%=Server.UrlEncode(Request.QueryString["Address"]) %>&daddr=<%=Server.UrlEncode(store.FormattedAddress) %>">Directions</a>

And that’s it! Adding the Directions link to the info popup window is a tad more involved because the quotation marks must be escaped using \”. Happy Programming!

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET hosting -ASPHostPortal.com :: Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

clock April 22, 2016 20:34 by author Armend

Top 10 Tips You Shall Know on Choosing ASP.NET Hosting

Being devoted into ASP.NET development and ASP.NET website hosting for a couple of years, we know the secrets hidden in the ASP.NET hosting advertisement and how difficult to find a trusted and cost effective ASP.NET hosting provider. Thus, we would like to show you the top 10 tips on choosing ASP.NET hosting providers before starting with our topic.

  1. MS SQL Server database edition and limitation. The latest version of MSSQL 2012 are preferred.
  2. .NET Framework versions. Does it support the version used for your website?
  3. ASP.NET MVC versions. Does it support the version used for your website if you’re using ASP.NET MVC technology?
  4. Does it provide the dedicated application pool so that you won’t be affected by your neighbors?
  5. How long the IIS is set to recycle your website – usually 30 minutes at least is required.
  6. What’s the maximum dedicated memory allowed for the ASP.NET websites?
  7. The hosting provider needs to have the rich experiences and knowledge of how to ensure the high-quality ASP.NET hosting. Besides, it is great that they have got plenty of positive feedbacks from real customers and have been trusted and recommended by a lot of authorities, communities and hosting review sites.
  8. The ASP.NET hosting needs to ensure a high level of hosting reliability with at least 99.9% uptime. Note that this can be achieved with the utilization of cutting-edge data centers, solid server machines and no overselling practice. In addition, some confident web hosts even claim to give you some compensations if they fail to meet their promised uptime track record.
  9. The hosting speed is also pretty essential. After all, your readers can be frustrating if they find it takes a long time for accessing your website. In this case, you need to figure out that whether your web host can ensure the peak performance with no more than 3 seconds for page loading and 400 ms for the server response.
  10. The web host needs to ensure the all-time-rounded technical support to assist you 24 hours a day and 7 days a week. Also, their support staffs need to have the rich knowledge about ASP.NET hosting and related applications.

General Knowledge about ASP.NET

ASP.NET is the server-side online application framework coming with the open source nature. It is designed with the purpose of web development and dynamic webpages production mainly. In addition, developed by Microsoft, ASP.NET has been used by a lot of programmers for the creation of complicated websites, online applications and add-on services.
In fact, ASP.NET has been released since January 2002, which is the successor to the Active Server Pages technology of Microsoft. As it is built based on the Common Language Runtime, developers and programmers can write the ASP.NET code with the help of .NET language.

 



ASP.NET Hosting - ASPHostPortal.com :: Why Server Speed is Important for Increasing Revenues

clock April 12, 2016 19:31 by author Armend

Why Server Speed is Important for Increasing Revenues

If your website loads slower and takes long to respond you are literally killing your sales and revenue with your own hands. Today, the key to more sales and conversion is the combination of effective content with faster loading speed of your website. The speed of your website is the time taken from a web page to become visible on the screen after it has been requested by the browser.

The latest surveys showed that loading speed of websites has a great impact on the traffic trends. The speed of the website has a great importance, a slow website could easily frustrate your potential customers forever.

 

A slow website reflects low revenue

Often the slower websites have high bounce rates with poor sales. A number of studies have proven that the average visitors will leave your website if it does not become accessible in 3 to 6 seconds. Slower website is not only a reason to decrease your sales but the frustrated visitors are likely to develop a negative perception about your business.

Does Speed of the website can increase the revenue?

Did you know the world popular brand Shopzilla generated 12% more revenue by simply improving the website speed from 6 seconds to 1.2 seconds?

It is no more a secret that google records the web page speed to determine the ranking of the website along with other organic ranking factors. You can check the speed of your pages by inspecting the Google webmaster tools.

According to latest calculated formula you can improve 2% of conversion rate by simply speeding up the website by every single second. Shopzilla , Amazon, Yahoo and Mozilla experienced a great boost in business by speeding up the loading speed of the web pages to less than 3 seconds.

Shopzilla increased 12% revenue along with 25% increased page views
Yahoo got a 9% increase in the traffic
Mozilla got 60 million more downloads by simply improving the web page speed to 2.2 seconds faster

How fast is fast enough for a web page?

The ideal loading time of a website is under 3 seconds. If your website becomes visible in 5 seconds it seems to be good. If it is under 10 seconds it is considered to be as fair. However if your website exceeds 10 seconds you are losing the ranking and conversion. The slower your website is the less sales you will have.
There are several performance metric tools available to report the performance of your website speed along with web page improvement suggestions. You can optimize the structure of your code to get faster responses. However you certainly need hosting power to execute your application quickly to load your website faster.

Choose fast dedicated server for faster website

The speed of a website mainly depends on the architecture of your web pages, databases and the speed of hosting servers. Going with the right kind of web hosting could make or break your website ranking. Shared hosting and dedicated hosting are two major types of hosting service available online. Shared service has a low price with low resources available. Shared hosting is designed to deliver small websites with low traffic. Dedicated hosting is an expensive option with more power and performance.
Businesses are adapting dedicated server technology for more speed and power. All sorts of critical online businesses can reap the benefit of fast powerful dedicated hosting. Server speed may be the issue if your website resides on one of the cheapest shared or vps hosting service holding hundreds of websites. Shared hosting can not offer you the true speed and reliability as its resources are shared by many websites hosted on the same computer. If you have a business website, mobile application or a professional service website, fast dedicated hosting can make a difference in search engine ranking.

Below are some great advantages of dedicated hosting for faster website.

  • Your website will load faster
    • The dedicated server is a powerful machine designed and configured to execute the processes in fastest manners. Dedicated hosting has more reliable infrastructure, bandwidth and resources as compared to any other type of hosting service. Dedicated hosting enables your website to execute faster and tremendously increase the loading speed of your website.
  • Your website will be more secure
    • Another great advantage of dedicated hosting is the safety of your business data. Usually hackers break into the websites by locating a poorly coded website hosted nearby on shared hosting environment. If you have hammer tested your code for common vulnerabilities you can easily lock down your server for better security and data safety.
  • Your website will handle more traffic
    • If you have a popular website or advertising your business you may experience sudden traffic spikes at certain times. Dedicated server enables you to tackle high load without going down. If you have optimized your code and server you are in a better position to handle your website traffic faster and smoothly.


ASP.NET Hosting - ASPHostPortal.com :: How to Call ASP.NET Page Methods using your own AJAX

clock March 15, 2016 20:04 by author Armend

ASP.NET has grown very rich day by day. Recently Microsoft has introduced JQuery as a primary javascript development tool for client end application. Even though there is a number of flexibility in ASP.NET AJAX applications, many developers do seek place to actually call a page using normal AJAX based application. In this post I will cover how you can invoke an ASP.NET page method directly from your own AJAX library.

What are page methods?

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.

What is a WebMethod?

A WebMethod is a special method attribute that exposes a method directly as XML service. To implement PageMethod we first need to annotate our method as WebMethod.
Steps to Create the application :
1. Start a new ASP.NET Project.
2. Add JQuery to your page. I have added a special JQuery plugin myself which stringify a JSON object. The post looks 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 &amp;&amp; obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" &amp;&amp; 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.

3. Add the server side method to the Default.aspx page. For simplicity we 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());
}

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

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

&lt;asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"&gt;
&lt;h2&gt;
Welcome to ASP.NET!
&lt;/h2&gt;
&lt;p&gt;
Write Your message Here : &lt;input type="text" id="txtMessage" /&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;input type="button" onclick="javascript:callServer()" value="Call Server" /&gt;
&lt;/p&gt;
&lt;/asp:Content&gt;
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.
&lt;script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="Scripts/JSONStringify.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
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);
}
});
}
&lt;/script&gt;

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. On success, it returns the serializable object to msg.d.



ASP.NET Hosting - ASPHostPortal.com :: Entity Framework 7 Providing support for new platforms

clock March 8, 2016 20:40 by author Armend

EF (Entity Framework) is Microsoft's flagship data access platform -- an extended ORM (Object Relational Mapper) that abstracts the calls to the ADO.Net data access provider underneath. It is an open source ORM framework for ADO.Net and is included as part of .Net Framework. The first version of Entity Framework (EFv1) was released as part of .Net Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1 in the year 2008.

In using Entity Framework, you can work with relational data using domain-specific objects. Entity Framework has been the technology of choice for building data access layer while working with WPF, WinForms, MVC, WebAPI, WebForms and WCF applications. Here are a few design documents on Entity Framework 7.
The latest version of this ORM is Entity Framework 7. Microsoft's vision for Entity Framework 7 is "New Platforms, New Data Stores". This implies that Entity Framework 7 is an extensible and lightweight version of Entity Framework that enables provides support for new platforms and new data stores. Entity Framework 7 is a major redesign of Entity Framework and is the default data stack for ASP.Net 5 applications.

I would like to highlight some of the striking features of EF7 in this post. To get started working with Entity Framework 7 you should add the Entity Franework 7 NuGet packages to your project.
Here's quick glance at what's new in Entity Framework 7:

  • Support for non-relational data stores and in-memory data
  • Support for Windows Phone and Windows Store applications
  • Support for Linux and Macintosh machines

Support for non-relational data stores and in-memory data

NoSQL databases are widely popular these days primarily because of performance -- CRUD operations on these database are faster compared to their relational counterparts. NoSQL databases are a good choice when you have to work with a large volume of data - particularly useful in statistical or real-time analysis of data. Entity Framework 7 now provides support for non-relational databases as well. The support for no-SQL in Entity Framework 7 is great. Interestingly, for querying and updating data in non-relational databases, you can use the same approach you are familiar with.
The following code snippet illustrates how you can use Entity Framework 7 with Microsoft Azure Table Storage to initialize a connection to the database.

public class StoresContext : DbContext
 {
  protected override void OnConfiguring(DbContextOptions options)
 {
   var connection =
   ConfigurationManager.ConnectionStrings["StoresDBConnection"]
   .ConnectionString;
   options.UseAzureTableStorage(connection);
  }
 }

The supported providers in Entity Framework 7 include:

  • SQL Server
  • SQLit
  • Azure Table Storage
  • Redis
  • In Memory (for unit testing)

Support for Windows Phone, Windows Store applications and Linux and Macintosh platforms

With Entity Framework 7, Windows Phone, Windows Store and ASP.Net 5 and desktop applications can leverage Entity Framework. Entity Framework 7 would work on SQLLite database -- the database of choice for mobile devices. Entity Framework 7 also provides support for Linux and Macintosh systems where Mono framework has been installed.

Entity Framework 7 is Lightweight and Extensible

Entity Framework 7 is lightweight and extensible -- it comes with more features and flexibility and enhanced performance. Another major change will be the "code first only" approach -- all models in Entity Framework 7 will be represented in the code. You would however be able to reverse engineer a model from the underlying database thanks to the tooling support. Code based modeling is preferred as it is less repetitive and easier to use and manage.

Enhanced support for Unit testing

Unit testing allows you to test blocks or units of the source code. Unit testing is simpler with EntityFramework 7. The code snippet given below shows a sample unit test.

[TestMethod]
public void SampleTest()
{
var options = new DbContextOptions()
.UseInMemoryStore();
using (var db = new StoresContext(options))
{
//Code to perform CRUD operations
//Assert the results
}
}

Effort is an easy to use and powerful unit testing tool for applications that use Entity Framework. It is actually an ADO.Net provider that comes with some helper methods that enables you to execute the CRUD operations on a lightweight in-memory database for faster execution. Effort is an Entity Framework provider that runs in memory. When writing your unit tests you can still use your familiar DbContext or ObjectContext classes. Most importantly, you are not constrained to have an actual database – your unit tests would be executed against the in-memory database.



ASP.NET Hosting Tips - ASPHostPortal :: Simple Steps to Enable SSL in Visual Studio

clock January 15, 2016 20:14 by author Jervis

Hi… Happy New Year for you all. It’s long holiday and this is time to write new tips to open this year. This is only simple tutorial how to setup SSL for your ASP.NET project in Visual Studio.

You have your own ASP.NET project now and you want to run it on SSL. So, how to make it works?

The first step is easy. You just select the MVC/Web API project name in the solution and locate the property called “SSL Enabled” in properties window:

The same properties window will also show the HTTPS url for the application. In the above example it’shttps://localhost:44300/. Copy that URL and go to the project properties window. Locate the Web tab and override the Project Url property with the https address:

Start the application. You’ll likely get a message in the browser saying that the localhost address is not trusted, you can continue to the website at your own risk as you can see on figure below:

The problem is that the certificate that was installed automatically for you by Visual Studio is not trusted. You can locate the certificate in the Personal folder of the computer-level certificates in the certificates snap-in:

If you double-click the certificate you’ll see that it’s not trusted:

The message also provides the solution: the certificate must be imported into the trusted root certification authorities folder. You’ll see that as a folder in the same snap-in just below “Personal”. So how can we do that?

Right-click the certificate, then select All Tasks, Export… from the context menu. Click Next on the certificate export wizard. Leave the “Do not export the private key” option untouched, click Next. Accept the default on the next screen, i.e. “DER encoded binary X.509” should stay selected, then click Next. Then you’ll need to provide a name and a location for the exported file. Call it “localhost” and save it in a location where you can easily find it. Click Next and the Finish. There should be a popup message saying that the export was successful.

Next right-click the folder called Trusted Root Certification Authorities and select All Tasks, Import… from the context menu. Leave the “Local Machine” option untouched in the certificate import wizard, click Next. Browse to the certificate you saved just before. Click Next and accept all the default values along the way until you reach the end of the wizard. There should be a message saying that the import was successful.

If you now go back to the Personal store and double-click the localhost certificate then you should see that it’s trusted:

 

OK, let’s start the .NET web project again, the opening page should open without any warning. If you still see the same issue then test it a brand new browser session, e.g. here in IE:

It’s easy, right?



ASP.NET 5 Hosting - ASPHostPortal :: SEO For ASP.NET Web Sites

clock December 16, 2015 00:36 by author Kenny

SEO For ASP.NET Web Sites

One of the main sources of audience for these internet applications are the Search Engines like Google, Bing, Yahoo etc. Hence, the end application should not only handle your business problems efficiently but also follow some simple rules so that it yields good results in internet arena. This article, will list some of the simple guidelines which you need to consider if your Asp.Net application is an internet site.

1.    Add descriptive and unique Page Title for every page

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file. Refer below,

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" Title="My Home Page"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

In code behind,

Page.Title = "My Home Page";

2.    Links should be hyperlinks, no linkbutton or javascript navigation for crawlable links

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). Javascript navigations are not search engine friendly since search engines will not understand it.

3.    Use javascript navigation for site related pages that have no search values

Page rank is distributed across the links on your page. Some of the internal website pages like About us, disclaimer, Registration, login, contact us, user profile pages can be navigated through javascript so that the page rank are not distributed to them. Doing like this will make rest of the crawlable content links benefited.

4.    Add Meta Keyword and Description tag for every page

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers. You can dynamically set the meta tags from codebehind file using the below code,

HtmlHead head = (HtmlHead)Page.Header;

 HtmlMeta metasearch1 = new HtmlMeta();

 HtmlMeta metasearch2 = new HtmlMeta();  

 metasearch1.Name = "descriptions";

 metasearch1.Content = "my personal site";

 head.Controls.Add(metasearch1);

 metasearch2.Name = "keywords";

 metasearch2.Content = "ASP.Net,C#,SQL";

 head.Controls.Add(metasearch2);

The above code will add the below Meta tags to output html.

<meta name="descriptions" content="my personal site" />

<meta name="keywords" content="ASP.Net,C#,SQL" />

In ASP.Net 4.0, Microsoft added 2 new properties on the Page directive (Page object) that lets you to define the Meta keywords and Description declaratively and dynamically from codebehind.

In ASPX,

<%@ Page Language="C#" AutoEventWireup="true" MetaKeywords="asp.net,C#" MetaDescription="This is an asp.net site that hosts asp.net tutorials" CodeFile="Default.aspx.cs" Inherits="_Default" %>

In codebehind,

protected void Page_Load(object sender, EventArgs e)

    {

        Page.MetaKeywords = "asp.net,C#";

        Page.MetaDescription = "This is an asp.net site that hosts asp.net tutorials.";

    }

The similar can thing can be achieved in previous versions of .Net Framework by using a custom BasePage class.

5.    Make descriptive urls

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://www.example.com/products.aspx?catid=C91E9918-BEC3-4DAA-A54B-0EC7E874245E is not descriptive as http://www.example.com/Windows-Hosting

Apart from other parameters, search engines will also consider the website url to match your page for a searched keyword.



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 Hosting Tips - ASPHostPortal :: SQLParameters in ASP.NET C#

clock November 16, 2015 22:10 by author Jervis

SqlParameter represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. Parameter names are not case sensitive. 

To initialize a new instance of SqlParameter class, we can use many constructors such as SqlParameter(), SqlParameter(String, SqlDbType), SqlParameter(String, Object), SqlParameter(String, SqlDbType, Int32), SqlParameter(String, SqlDbType, Int32, String). 

SqlParameter() constructor initialize a new instance of SqlParameter class. Sqlparameter(String, SqlDbType) constructor require parameter name and data type. SqlParameter(String, Object) constructor require parameter name and a value of the new SqlParameter. SqlParameter(String, SqlDbtype, Int32) constructor require parameter name, SqlDbType and size. SqlParameter(String, SqlDbtype, Int32, String) constructor require parameter name , SqlDbType, size and the source column name. 

SqlParameter class have many useful properties such as CompareInfo, DbType, Direction, IsNullable, Offset, ParameterName, Precision, Scale, Size, SourceColumn, SqlDbType, SqlValue, TypeName, Value, XmlSchemaCollectionName etc. 

ParameterName property get or set the SqlParameter name. SqlDbType property get or set the SqlDbType (SQL Server specific data type) for the parameter. SqlDbType enumeration values are BigInt, Binary, Bit, Char, Date, DateTime, Decimal, Float, Image, Int, Money, Real, Text, Time, Timestamp etc. SqlParameter Size property get or set the maximum size in bytes of the data within the column. Direction property get or set a value that indicate whether the parameter is input only, output only, bidirectional or a stored procedure return value parameter. Value property get or set the value of parameter. 

The following c# example source code describe you more about SqlParameter in ASP.NET. 

Create a web form name SqlParameterExample.aspx. Now add a GridView control. We populate the GridView control with SqlDataSource Data. But here we filter the data by SqlParameter. In this example we select the NorthWind database Products table data and filter it with SqlParameter product name. The source code of SqlParameterExample.aspx is here.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        if (!Page.IsPostBack) {
            SqlConnection MyConnection;
            SqlCommand MyCommand;
            SqlDataReader MyReader;
            SqlParameter ProductNameParam;

            MyConnection = new SqlConnection();
            MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;

            MyCommand = new SqlCommand();
            MyCommand.CommandText = "SELECT * FROM PRODUCTS WHERE PRODUCTNAME = @PRODUCTNAME";
            MyCommand.CommandType = CommandType.Text;
            MyCommand.Connection = MyConnection;

            ProductNameParam = new SqlParameter();
            ProductNameParam.ParameterName = "@PRODUCTNAME";
            ProductNameParam.SqlDbType = SqlDbType.VarChar;
            ProductNameParam.Size = 25;
            ProductNameParam.Direction = ParameterDirection.Input;
            ProductNameParam.Value = "CHAI";

            MyCommand.Parameters.Add(ProductNameParam);

            MyCommand.Connection.Open();
            MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

            GridView1.DataSource = MyReader;
            GridView1.DataBind();

            MyCommand.Dispose();
            MyConnection.Dispose();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SqlParameter example: how to use SqlParameter in asp.net</title>
</head>
<body>
   
<form id="form1" runat="server">
   
<div>
       
<asp:GridView ID="GridView1" runat="server">
       
</asp:GridView>
   
</div>
   
</form>
</body>
</html>

 



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