All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET 4.5 Hosting – :: Optimize Your Website Performance with ASP.NET 4.5

clock June 28, 2013 06:45 by author Ben

Microsoft ASP.NET is today the most powerful and fastest growing platform for Web development. ASP.NET powers some of world's largest Web sites and most demanding applications. And now, ASP.NET 4.5 can optimization your website performance.

Typical web site contains CSS files, Images and Javascript files along with you HTML elements. CSS files, Images and JS files will take some time to load into the browser though the loading time is in milliseconds but matters. The HTML is not taking much time but other elements are taking time to load in to the browser. The Typical ASP.NET web site might look like as below in Visual Studio. It may contain Scripts  folder, Images Folder, Styles Folder and a Default aspx page.

The first problem that we can see that too many HTTP requests which are going to images, CSS files and to JavaScript files. is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

We can use Bundling and Minifying the files to reduce those requests. In ASP.NET 4.5 you have the built-in features to these. Write one line of code in Global.asax to bring these HTTP Requests down.

The above line enables the minification for CSS and Javascript files, only these two. Minifying means removing whitespaces, comments and everything that browser does not need to understand. We can really compress these files using this technique.

Basically this bundling technique looks at the folder and takes all the files inside and bundles them into one file, no matter how many are in the folder. This all happens at runtime. It only happens at once.

The order of bundling of your files goes as first it takes all Jquery scripts first and then it takes custom scripts alphabetically from your solution explorer.

Instead of doing the references to individual files, You can do this

Styles/CSS is the convention. Folder name / CSS bundles all the css files on that folder. We can do the same foe JavaScript like this

Suppose if you want to bundle the files by taking from different directories in

In above code we are registering our own bundle named mycss and then we are adding file styles.css and a directory styles.

Compress components with gZip. we can enables this on IIS. You tell the server everything that respond to client that text based zip it. You can do this by changing the couple of attribute values in web.config file

In IIS 7.5 it enables for you by default, if you running on windows server 2008 then you need to set the attribute values to true.

Encoding the Images to Base64 Images

Above code shows before and after encoding the image.

You may not want to encode all images in your project but if you want the images that you want to embed along with style sheets then you can write some regular expressions as shown below.

We can even transform your response further using coffee script as shown below

You can optimize the images in your folder by using Visual Studio extension tool named Optimize Images and then you can refresh folder and compile.

ASP.NET 4.5 Hosting – :: Umbraco Open Source ASP.NET

clock June 20, 2013 11:08 by author Ben

There are a large number of CMSs to choose from when you are getting ready to design a new website. Umbraco has consistently proven to be one of the better Open Source .NET CMS options. However, because of the way that it is designed, getting everything set up is a little different than with other CMS options on the market. It is designed with developers in mind, which means that it will take a little extra effort to get it up and running. Additionally, depending on how well versed you are with the .NET framework, there can be a steep learning curve. Fortunately, once you understand how it works, using it is very easy. Here is a closer look at some of the primary features that Umbraco offers as well as some of the potential drawbacks.

     Umbraco is one of only a few open source web content management systems built on Microsoft's .NET technology stack. This CMS is no "out the box" solution. To the contrary, it's a content management system for .NET web developers. And while it's relatively straightforward to use, one must first deal with a steep learning curve. Umbraco was not designed to be a plug-and-play solution like Drupal or Joomla.

      Umbraco Advantages
1. All About Customization
Umbraco was designed to be a very customizable solution. This is made possible because it isn't a “plug in play” solution, unlike many other popular CMS solutions such as Wordpress, Joomla, and Drupal. The creator, Niels Hartvis, notes that the goal of Umbraco isn't necessary to be the perfect solution for everyone, but rather has the ability to be the perfect solution. It does take some time to learn the ins and outs of this CMS, but once you have gotten over the learning curve, the possibilities are endless. If you are already fairly fluent in .NET and common website design languages, then the learning curve will be fairly small.

Unique Tools
Umbraco Courier is a unique toll that was designed to streamline the process of moving your website into a live environment once all of the staging has been completed. It also allows you to sync up with other environments and add new functionality as well. Another great tool is Concierge. This tool is used by developers to see what is currently installed as well as what is currently in use. To do this, it also monitors action handlers as well as third party tools. This way you always know what is working within your site.
Training and Support
The available training and support is based upon what type of package you purchase. It can range from minimal support to a guaranteed 48 hour response time. What seems to be even more useful than the support system that is offered is You can get a subscription to which offers more than 8 hours of video tutorials. These videos are designed for all types of people including editors, developers, and website builders. This subscription can be done annually or monthly, it is all up to how quickly you become comfortable with Umbraco. However, many business have found value in these videos because it allows them to teach employees how to use the system without spending on in-house resources training them.

      Potential Umbraco Drawbacks
There seems to be two primary drawbacks that could determine whether or not this is the right CMS for you.
Designed For Developers
While this is it's biggest benefit, it can also become its biggest drawback. If you are just looking for a simple, straightforward CMS to set up a website quickly and without much effort, then Umbraco is not the CMS for you. If you are primarily a publisher, then there is a good chance that you may get frustrated fairly quickly and move on to another option.

The Premium
Like many open source CMS .NET options, Umbraco is both open-source as well as commercial, depending on what you need. While there is more and more documentation available, if you are sticking with the open-source option, then there are several very helpful tools that you will be missing out on. For example, both Umbraco Courier and Concierge are premium tools that only come with a pro license.
In the end, as both an open-source and commercial CMS, Umbraco has quickly become a dominant force in .NET landscape. If you already have a strong understanding of .NET or don't mind getting through the potentially steep learning curve, then could definitely reap the rewards in the long run.

ASP.NET 4.5 Hosting – :: Dropdown List in ASP.NET 4.5

clock June 17, 2013 10:06 by author Ben

The concept of model binding was first introduced with ASP.NET MVC and now it has incorporated with ASP.NET Web Forms. You can easily perform any CURD operation with any sort of data controls using any data access technology like Entity Framework,  ADO.NET, LINQ to SQL Etc.  In this post I am going talk about how you can bind the data with ASP.NET DropdownList using new Model Binding features.

Let’s say we have a speaker database and we wants to bind the name of the speakers with the DropDownList.  First placed an ASP.NET Dropdown control with the page  and set the “DataTextField” and “DataValueField” properties


We can set the  ddlName.DataSource to specifying the data source from the code behind and bind the data with dropdpwnlist, but  in this case from the code behind to providing the data source. Now, instead of specifying the DataSource, we will be setting the Dropdownlists SelectMethod property to point a method GetSpeakerNames() within the code-behind file.

Select method is expected to return us result of type IQueryable<TYPE>. Here is GetSpeakerName() method is defined as follows.

/// <summary>
/// Return the Speakers Name
/// </summary>
/// <returns></returns>
public IQueryable<Speaker> GetSpeakerNames()
DeveloperConferenceDBEntities datasource = new DeveloperConferenceDBEntities();
return datasource.Speakers;

So, Instead of specifying the data source we are specifying the SelectMethod, which return the IQueryable type of Speaker object. Run the application, you will find the names binded with dropdown list.

ASP.NET 4.5 Hosting - :: Tips to Prevent Cross-Site Scripting in ASP.NET

clock June 14, 2013 08:27 by author Ben

This How to shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.


  • Objectives
  • Overview
  • Summary of Steps
  • Step 1. Check That ASP.NET Request Validation Is Enabled
  • Step 2. Review ASP.NET Code That Generates HTML Output
  • Step 3. Determine Whether HTML Output Includes Input Parameters
  • Step 4. Review Potentially Dangerous HTML Tags and Attributes
  • Step 5. Evaluate Countermeasures
  • Additional Considerations
  • Additional Resources


  • Understand the common cross-site scripting vulnerabilities in Web page validation.
  • Apply countermeasures for cross-site scripting attacks.
  • Constrain input by using regular expressions, type checks, and ASP.NET validator controls.
  • Constrain output to ensure the browser does not execute HTML tags that contain script code.
  • Review potentially dangerous HTML tags and attributes and evaluate countermeasures.

Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.

Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:

  • Failing to constrain and validate input.
  • Failing to encode output.
  • Trusting data retrieved from a shared database.

The two most important countermeasures to prevent cross-site scripting attacks are to:

  • Constrain input.
  • Encode output.

Constrain Input
Start by assuming that all input is malicious. Validate input type, length, format, and range.

  • To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
  • To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use the System.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
  • To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.

Encode Output
Use the AntiXSS.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

Similarly, use AntiXSS.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps
To prevent cross-site scripting, perform the following steps:

  • Step 1. Check that ASP.NET request validation is enabled.
  • Step 2. Review ASP.NET code that generates HTML output.
  • Step 3. Determine whether HTML output includes input parameters.
  • Step 4. Review potentially dangerous HTML tags and attributes.
  • Step 5. Evaluate countermeasures.

Step 1. Check That ASP.NET Request Validation Is Enabled
By default, request validation is enabled in Machine.config. Verify that request validation is currently enabled in your server's Machine.config file and that your application does not override this setting in its Web.config file. Check that validateRequest is set to true as shown in the following code example.

  <pages buffer="true" validateRequest="true" />

You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input.

To test that ASP.NET request validation is enabled
Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in the following code example.

<%@ Page Language="C#" ValidateRequest="false" %>
 <script runat="server">
  void btnSubmit_Click(Object sender, EventArgs e)
    // If ValidateRequest is false, then 'hello' is displayed
    // If ValidateRequest is true, then ASP.NET returns an exception
  <form id="form1" runat="server">
    <asp:TextBox id="txtString" runat="server"
                 Text="<script>alert('hello');</script>" />
    <asp:Button id="btnSubmit" runat="server"  
                Text="Submit" />

2. Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.

3. Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.

A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").

This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.

Note: Do not rely on ASP.NET request validation. Treat it as an extra precautionary measure in addition to your own input validation.

Step 2. Review ASP.NET Code That Generates HTML Output
ASP.NET writes HTML as output in two ways, using "Response.Write" and "<% = ". Search your pages to locate where HTML and URL output is returned to the client.

Step 3. Determine Whether HTML Output Includes Input Parameters
Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:

·         Form fields, such as the following.

Query Strings

·         Query strings, such as the following:


·         Databases and data access methods, such as the following:

SqlDataReader reader = cmd.ExecuteReader();

Be particularly careful with data read from a database if it is shared by other applications.

·         Cookie collection, such as the following:


·         Session and application variables, such as the following:


In addition to source code analysis, you can also perform a simple test by typing text such as "XYZ" in form fields and testing the output. If the browser displays "XYZ" or if you see "XYZ" when you view the source of the HTML, your Web application is vulnerable to cross-site scripting.

To see something more dynamic, inject <script>alert('hello');</script> through an input field. This technique might not work in all cases because it depends on how the input is used to generate the output.

Step 4. Review Potentially Dangerous HTML Tags and Attributes
If you dynamically create HTML tags and construct tag attributes with potentially unsafe input, make sure you HTML-encode the tag attributes before writing them out.

The following .aspx page shows how you can write HTML directly to the return page by using the <asp:Literal> control. The code takes user input of a color name, inserts it into the HTML sent back, and displays text in the color entered. The page uses HtmlEncode to ensure the inserted text is safe.

<%@ Page Language="C#" AutoEventWireup="true"%>
  <form id="form1" runat="server">
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      <asp:Button ID="Button1" runat="server" Text="Show color"
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
    protected void Button1_Click(object sender, EventArgs e)
      Literal1.Text = @"<span style=""color:"
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";

Potentially Dangerous HTML Tags
While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:

  • <applet>
  • <body>
  • <embed>
  • <frame>
  • <script>
  • <frameset>
  • <html>
  • <iframe>
  • <img>
  • <style>
  • layer>
  • <link>
  • <ilayer>
  • <meta>
  • <object>

An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the <img> tag can be a source of injection, as shown in the following examples.

<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A;script:alert('hello');">

An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.

<style TYPE="text/javascript">

Step 5. Evaluate Countermeasures
When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:

  • Encode HTML output.
  • Encode URL output.
  • Filter user input.

Encode HTML Output
If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the AntiXSS.HtmlEncode method as shown in the following code example. Do this if the text came from user input, a database, or a local file.


Do not substitute encoding output for checking that input is well-formed and correct. Use it as an additional security precaution.

Encode URL Output
If you return URL strings that contain input to the client, use the AntiXSS.UrlEncode method to encode these URL strings as shown in the following code example.


Filter User Input
If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).

To safely allow restricted HTML input
Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @Page directive.

2. Encode the string input with the HtmlEncode method.

3. Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.

The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.

<%@ Page Language="C#" ValidateRequest="false"%>
<script runat="server">
  void submitBtn_Click(object sender, EventArgs e)
    // Encode the string input
    StringBuilder sb = new StringBuilder(

  // Selectively allow  <b> and <i>
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
    sb.Replace("&lt;/i&gt;", "");

    <form id="form1" runat="server">
        <asp:TextBox ID="htmlInputTxt" Runat="server"
                     TextMode="MultiLine" Width="318px"
        <asp:Button ID="submitBtn" Runat="server"
                     Text="Submit" OnClick="submitBtn_Click" />

Additional Considerations
In addition to the techniques discussed previously in this How to, use the following countermeasures as further safe guards to prevent cross-site scripting:

  • Set the correct character encoding.
  • Do not rely on input sanitization.
  • Use the HttpOnly cookie option.
  • Use the <frame> security attribute.
  • Use the innerText property instead of innerHTML.

Set the Correct Character Encoding
To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.

ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.

To set the character encoding at the page level, use the <meta> element or the ResponseEncoding page-level attribute as follows:

<meta http-equiv="Content Type"
      content="text/html; charset=ISO-8859-1" />
<% @ Page ResponseEncoding="iso-8859-1" %>

To set the character encoding in the Web.config file, use the following configuration.


Validating Unicode Characters
Use the following code to validate Unicode characters in a page. using System.Text.RegularExpressions;
public class WebForm1 : System.Web.UI.Page
  private void Page_Load(object sender, System.EventArgs e)
    // Name must contain between 1 and 40 alphanumeric characters
    // and (optionally) special characters such as apostrophes 
    // for names such as O'Dell
    if (!Regex.IsMatch(Request.Form["name"],
      throw new ArgumentException("Invalid name parameter");

    // Use individual regular expressions to validate other parameters

The following explains the regular expression shown in the preceding code:

  • ^ means start looking at this position.
  • \p{ ..} matches any character in the named character class specified by {..}.
  • {L} performs a left-to-right match.
  • {Lu} performs a match of uppercase.
  • {Ll} performs a match of lowercase.
  • {Zs} matches separator and space.
  • 'matches apostrophe.
  • {1,40} specifies the number of characters: no less than 1 and no more than 40.
  • $ means stop looking at this position.

Do Not Rely on Input Sanitization
A common practice is for code to attempt to sanitize input by filtering out known unsafe characters. Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. Instead, your code should check for known secure, safe input

Use the HttpOnly Cookie Option
The HttpOnly cookie attribute prevents client-side scripts from accessing a cookie from the document.cookie property. Instead, the script returns an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.

Use the <frame> Security Attribute
You can set the security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user's Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution.

If you use the security attribute, it must be set to "restricted" as shown in the following.

<frame security="restricted" src=""></frame>

Use the innerText Property Instead of innerHTML    
If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.

The following example shows this approach for two HTML <span> controls. The code in the Page_Load method sets the text displayed in the Welcome1 <span> element using the innerText property, so HTML-encoding is unnecessary. The code sets the text in the Welcome2 <span> element by using the innerHtml property; therefore, you must HtmlEncode it first to make it safe.

<%@ Page Language="C#" AutoEventWireup="true"%>
    <span id="Welcome1" runat="server"> </span>
    <span id="Welcome2" runat="server"> </span>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
    // Using InnerText renders the content safe-no need to HtmlEncode
    Welcome1.InnerText = "Hello, " + User.Identity.Name;

    // Using InnerHtml requires the use of HtmlEncode to make it safe
    Welcome2.InnerHtml = "Hello, " +

ASP.NET 4.5 Hosting :: Use The OnRowDataBound Event of The GridView

clock June 12, 2013 11:12 by author Ben

If you have a requirement to create a GridView paging style programmatically, then use the OnRowDataBound event of the GridView as shown below:


protected void GridView1_RowDataBound(object sender,

GridViewRowEventArgs e)
  if (e.Row.RowType == DataControlRowType.Pager)
      TableRow tRow = e.Row.Controls[0].Controls[0].
        Controls[0] as TableRow;
      foreach (TableCell tCell in tRow.Cells)
          Control ctrl = tCell.Controls[0];              
          if (ctrl is LinkButton)
              LinkButton lb = (LinkButton)ctrl;
              lb.Width = Unit.Pixel(15);
              lb.BackColor = System.Drawing.Color.DarkGray;
              lb.ForeColor = System.Drawing.Color.White;

Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
                             ByVal e As GridViewRowEventArgs)
     If e.Row.RowType = DataControlRowType.Pager Then
         Dim tRow As TableRow = _
         TryCast(e.Row.Controls(0).Controls(0).Controls(0), _
         For Each tCell As TableCell In tRow.Cells
             Dim ctrl As Control = tCell.Controls(0)
             If TypeOf ctrl Is LinkButton Then
                 Dim lb As LinkButton = CType(ctrl, LinkButton)
                 lb.Width = Unit.Pixel(15)
                 lb.BackColor = System.Drawing.Color.DarkGray
                 lb.ForeColor = System.Drawing.Color.White
                 lb.Attributes.Add("onmouseover", _
                 lb.Attributes.Add("onmouseout", _
             End If
         Next tCell
     End If
End Sub

I have set the mouseover and mouseout attributes in this example which changes the color when the user hovers over the pager. You could follow a similar technique or tweak the example to suit your requirement. I hope you get the idea.
The output would be similar to the one shown below:

ASP.NET 2.0 Hosting :: Tips for Shared Functions

clock June 7, 2013 07:52 by author Ben

When developing a recent project for ASP.NET, there was a need to migrate a large number of generic functions that were created in PHP into the .net web project. For .net 1.0, you were able to add a code page that could be used for creating a bunch of functions. However, in 2.0, you still had the ability to add a code page, but it had to be a class. This meant placing all of our migrated functions as methods inside a class. To use a generic function, such as generateNewPassword(), you would have to first create a new object for the class and then call the method.

Dim objGenericFunctions as new GenericFunctions()
blnPasswordSent = generateNewPassword(firstName, lastName, email)

There are a couple of problems with this technique. First, since .net 2.0 encourages object-oriented programming, you could either create objGenericFunctions() once and pass the object as a parameter to other classes. But this requires extra code management, especially when there are classes that call other classes that might need to use some of those Generic Functions from objGenericFunctions. Or you could create a new objGenericfunctions whenever you need it, but this means creating a number of objects for the GenericFunctions class, which seems to be a waste of system resources.

In developing classes for PHP 5.0, you could declare a class function as static. Which allowed you to use that method without having to create a new object. After some googling, I learned that also has a similar declaration, but they call it shared. So, by declaring a class function as shared, there's no need to create a new object each time.

blnPasswordSent = GenericFunctions.generateNewPassword(firstName, lastName, email)

Here's a sample class with a shared function:
Imports Microsoft.VisualBasic
Imports System.Web
Public Class GenericFunctions
   Public Shared Function isDateInRange(ByVal dateStart As DateTime, ByVal dateEnd As DateTime, ByVal dateCompare As DateTime) As Boolean
        Dim blnInRange As Boolean = False
        Dim intStartDiff As Integer = 0
        Dim intEndDiff As Integer = 0
        intStartDiff = Date.Compare(dateStart, dateCompare)
        intEndDiff = Date.Compare(dateCompare, dateEnd)
        If intStartDiff <= 0 And intEndDiff <= 0 Then
            blnInRange = True
        End If
        Return blnInRange
    End Function
End Class

We can take this one step for further by adding a namespace declaration to the class. By using a namespace, we can now add Imports GenericFunctions to the top of a code page and access those methods without having to type GenericFunctions first.

Sample of Namespace declaration:
Imports Microsoft.VisualBasic
Imports System.Web
Namespace GenericFunctions
    Public Class GenericFunctions
        ' Place all the functions here...
    End Class
End Namespace

Example of using the Imports statement:
Default.aspx.vb - Code Behind

Imports GenericFunctions
Partial Class Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender as Object, ByVal e As System.EventArgs) Handles Me.Load
        'No longer need to start with GenericFunctions
        blnPasswordSent =generateNewPassword(firstName, lastName, email)
    End Sub
End Class

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

 photo ahp banner aspnet-01_zps87l92lcl.png


Corporate Address (Location)

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

Tag cloud

Sign in