Mark Mintoff My superpower is common sense


C# ASP.Net Custom HTML Button

I have opted to create an ASP.Net button (postback and event handle) from scratch.

Why? Because I can. Also because it allows me more control over the visual presentation of a button.

This little endeavor is still a work in progress however it supports a server-side click event, a client-side click event, button text, an icon image and works within ASP Update Panels as well.

The markup is relatively straight-forward:

I am using an

  • as the root element, because most of the time I make use of a
      -based layout

      The back-end for the button is as follows:

      As you can see, I am making use of the IPostBackEventHandler and registering the control with the ScriptManager as a PostBackControl or an AsyncPostBackControl, depending on whether or not the control is contained within an Update Panel.

      Currently, I am hoping there is a more efficient way of detecting whether the button is within an Update Panel, but the while loop will do for now.

      I have written a small amount of CSS for the button, in order to make it look good:

      In a perfect world, I would not need to write CSS to support anything less than IE8, but this CSS breaks on IE7. I would imagine it would do very much the same thing on IE6. However, I actually dedicated (wasted) an hour towards trying to get this to work on IE7:

      Usage is simple and can be figured out from the download:

      What I have provided is a veritable playground of design customization in lieu of the standard button whilst more or less retaining the same functionality of the standard button.

      Any customization or features are completely up to you. Happy coding/designing!

      VN:F [1.9.22_1171]
      Rating: 0.0/5 (0 votes cast)
  • 23Jan/121

    ASP.Net File Serving

    The best way to go about creating downloadable files in ASP.Net is to control the way in which those files are served to the users. Some of the most apparently obvious advantages are:

    • Controlling the response header, allowing for a forced download
    • Hiding the directory structure of your website
    • Easy way to control file access through rights
    • File download tracking

    To do this, we need to create a Generic Handler (.ashx) in our project.I added one and named it "File.ashx".

    Working with generic handlers is super easy. All it takes is programming; no design. Most systems utilize a database to track files and I will be working on this assumption.

    In the ProcessRequest method, we will first do some querystring handling to get the ID of the file:

    Here, we are simply acquiring the file of the ID and ensuring that the application will not crash through querystring manipulation.

    I did not want to get into the details of database implementation, so I wrote the following code block as a simulation of fetching from the database:

    I am making the assumption here that the MIME type is already stored in the database along with other information about the file. The best time to extract the MIME type from the file would be during the upload to the server. In order to do this, I developed my own (long...224 lines) method to extract the MIME type from an HttpPostedFile object.

    Moving on however, after we have the file name and mime type information, it is time to actually serve the file. We can do this by writing the file into the Response's Output Stream, but first we need to read the file into a byte array.

    The byte array returned from this method will then be written into the OutputStream, along with some other information. One of the things we should do is control whether or not the file is a download; forcing the browser to download the file onto the computer as opposed to handling the file how it sees fit. For example, many browsers handle images by opening the image in the browser itself which may not be a desired outcome. Alternatively there may be some files that the browser does not know how to handle (docx for example) and will instead opt to do nothing rather than download the file. Hence:

    Here, we are writing the file into the Output Stream, specifying the content type (MIME Type) and setting the content-disposition, determining whether or not the file is a download. It is necessary to wrap the file name in quotes because Firefox does not handle file names with spaces otherwise.

    Finally, the way to access the file (from the downloadable example) is creating a link as follows:

    And here is the obligatory, downloadable example:

    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    ASP.Net Keep Alive and Background Processes

    In certain specific cases within our web-based solutions, we would like to have one or several processes running at specific times or specific intervals in order to perform a specific set of tasks. Commonly, this would be used for tasks such as:

    • Sending e-mails on a daily basis at a specific time
    • Sending notifications on an hourly basis

    My original solution for this was to have a few threads running, initiated on Application_Start which would execute code. I assume many people have tried this sort of thing and many people have found that this does not work. The reason this does not work is simple.

    Web applications are essentially stateless. Working with static variables on the Application level does not mean that the web application will have a state. IIS will unload inactive web applications. Occasionally, especially on shared hosting environments, IIS will intermittently shut down a web application, frequently to clear up memory.

    Some online posts on various websites, describe setting up a thread which pings the website every 5 minutes or so, thus keeping the web application alive. I have tested this on a shared hosting environment on GoDaddy, which though admittedly is not the best web hosting environment available, is no different for the purposes of this test case. The result of the automated website pinger is that the website itself stays active for a few hours and then gets randomly unloaded by IIS, hence terminating my threads. In short, this solution appears to work, but it does not work.

    Hence, we can move on to an improved solution. This solution would ideally be developed for a dedicated hosting environment where you would have access to the windows machine through Remote Desktop and would be able to deploy a windows service. Alternatively you could setup the windows service to execute on your machine and interact with your website. In either case, the solution is the same.

    Windows Service will call a Web Service every 5 minutes. This web service then invokes the Process Code. Within the process code, we can do whatever we like.

    Ideally what we would do is keep information within a database, specifying the Next Execution Time. What we would do then, is check on invocation if the date and time are greater or equal to the current date and time. If it is, we execute the process code. On execution, we would then reset the Next Execution Time by our specified delay time.

    I will create a prototype eventually, which will be available within the Downloads section.

    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    ASP.Net URL Rewriting

    URL Rewriting is a methodology for creating dynamic, customizable "fake" URLs pointing to a real URL. This is tremendously useful:

    • URLs may be made more user-friendly and easier to remember
    • Links are more professional looking
    • Small bonus to search engine optimization
    • Possibility to offer language support
    • Hiding querystring parameters
    • Creating URLs which do not contain the page's file extension (.aspx, .html, .shtml, .php...etc)

    But how can we achieve this using ASP.Net C#? For starters, it is worth knowing that IIS 5.0 - 7.0 support URL Rewriting. IIS 7.0 supports URL Rewriting seamlessly, whereas IIS 5.0 and 6.0 require a specific configuration, which I will discuss later in the post.

    The URL Rewriting Module needs to be developed under it's own separate project within your website's solution. This is necessary, as there are some web.config configurations to be written, which will require a reference to that project. For the purposes of simplicity, I will create a URL Rewrite module from scratch which will work using a hard-coded collection. For your own project you may use an XML file or preferably a database implementation.

    So first things, first: I created a web application project (ProtoURLRewrite) and added a class library project (Proto.Core.URLRewrite). I added a reference to System.Web to Proto.Core.URLRewrite and added a reference to Proto.Core.URLRewrite from ProtoURLRewrite. I then created a class (RewriteModule.cs) in Proto.Core.URLRewrite which inherits from IHttpModule.

    I then added two event handlers, for BeginRequest and PreRequestHandlerExecute. Since for simplification purposes, I will be using hard-coded URLs, I also added a static Dictionary and populated some values. Currently, the class looks like this:

    At this stage it would be worth mentioning how this will be working. All requests (and that includes file requests such as .css, .js, .jpg...etc) will go through our RewriteModule. It is perfectly fine to let these file requests slip through the logic, however to improve performance, I added a bit of Regex to filter out those file requests.

    What we are doing now is looping through our collection of URL Rewrite "rules"; again I recommend doing this by using a database. If the requested path (ex: "/mainpage") matches the Key one of the entries, the requested path is set to be the Value from the entry (ex: "/Default.aspx"). Additionally, if there is an existing query string (ex: "?lang=en") it is appended to the url (ex: from "/mainpage?lang=en" to "/Default.aspx?lang=en"). After all of that is done, the original raw url is set on the a context item for later use and the path is rewritten.


    For the purposes of being able to handle querystrings, we will now create a RewriteContext object:

    This object will act as a querystring proxy, and for future querystring processing, we would need to query both the RewriteContext and the regular Request.QueryString in order to find our querystring. For this purpose, I have created an extension (which makes use of some other extensions I have created):

    This extension will not only return the query string value from the RewriteContext and Request.QueryString, but will also return it in the specified type <T>.

    Within the context_PreRequestHandlerExecute event, we shall now write the following code:

    What we are doing here is creating a RewriteContext object to be used instead of the querystring. Additionally, we are changing the Form's action to the rewritten path, so that after a postback is done, the path remains the same. Only one thing left before we can test: web.config settings:

    1. Under the <system.webServer> tag, enter the following details:
      <validation validateIntegratedModeConfiguration="false" />
    2. In the <modules> tag, which resides within the <system.webServer> tag, add the following attribute:
    3. Under the <modules> tag which resides within the <system.webServer> tag, add the following:
      <add name="RewriteModule" type="Proto.Core.URLRewrite.RewriteModule,Proto.Core.URLRewrite />
    4. Under the <httpModules> tag which resides within the <system.web> tag, add the following:
      <add name="RewriteModule" type="Proto.Core.URLRewrite.RewriteModule,Proto.Core.URLRewrite />

    For clarity:

    Finally, I get to test. Within the Default.aspx's Page_Load event I have added the following bit of code:

    /pageOne resolved to the id being 1
    /pageTwo resolved to the id being 2
    /pageThree resolved to the id being 3

    The test has been a success. One final point to mention is IIS configuration for 5.0 and 6.0. As previously mentioned, IIS 7.0 will integrate seamlessly so the following steps are not required:

    1. Open inetmgr.exe
    2. Right click your website -> Properties
    3. Select the Virtual Directory tab
    4. Click Configuration
    5. Select the Mappings tab
    6. Click Insert
    7. Type in C:WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_isapi.dll
    8. Uncheck Verify that file exists
    9. Click OK
    10. Click OK
    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    ASP.Net JQuery Confirm Dialog

    How does one go about replacing the javascript default functionality of "confirm", which despite being very useful, is terribly out of touch with modern web design?

    Achieved, naturally through the use of this simple bit of code:

    Over the past few days, I combed the web searching for a nice, clean and simple way to replace the confirm dialog with a stylized version; preferably with JQueryUI. All solutions and plugins which I found seemed to be concentrated towards passing in functions or URLs to be executed upon the user pressing the "Yes" button. This is insufficient. The great advantage attained from "confirm" is that it halts the form from submitting until user input is provided; something which is very very useful in ASP.Net.

    What I needed was to emulate the same functionality; putting the form submission on hold, until the user has clicked "Yes" and to do nothing if "No" is pressed.

    My first approach was to use a JQueryUI Dialog normally. To my great dismay, I found that the page does not even wait for user input through the use of this dialog. So much for modal.

    My second approach was to resort to Pascal-based thinking; an infinite loop waiting for input. To my surprise, the dialog does not even come up when this is done, and the client side is locked under an infinite loop.

    My third approach turned out to be made of the right stuff. What if the default functionality was prevented (returning false) while the dialog is presented to the user and then re-executing the click command if "Yes" is pressed? It's so simple and elegant, I'm in love with it.

    Here's how it works:

    • Pass the button itself to the function "confirmDialog"
    • The variable "confirmed" is set as "false" by default.
    • First time condition check: confirmed is false, so display the dialog.
    • Return confirmed (false); hence preventing the code from executing.
    • Dialog is up
    • User presses "Yes", confirmed is set to true
    • Re-execute the button's click function
    • Second time condition check: confirmed is true, do not display the dialog.
    • Return confirmed (true); hence allowing the code to execute.

    Simple no? Here's what it looks like:

    If "No" is pressed, nothing happens. Confirmed is still false, hence no executions will take place. It is only when "Yes" is pressed and the button's click function is re-executed, will the action execution take place. A simple and yet elegant solution. And what's better is that it involves zero plugins.

    The following is a more customizable implementation which I would suggest you make use of:

    This has the advantage of dynamically creating the dialog div, as well as allowing customization of the title and dialogText. The close event also cleans up, by removing the generated dialog div.

    There is one caveat, which IS solvable I assure you; usage within UpdatePanels. For this I would suggest taking a look at Rick Strahl's ClientScriptProxy and writing something along the lines of:

    Putting a "confirmed = false;" in the BindControlEvents() function.

    I do not wish to go into too much detail about it here, but this is my implementation:

    Now all you need to do is literally writing "confirmed = false;" in a function named BindControlEvents(). Personally, I like using JQuery and UpdatePanels in conjunction with each other, so I write a few things in there such as:

    You can obviously customize this to suit your merry needs!

    Downloadable example:

    VN:F [1.9.22_1171]
    Rating: 3.9/5 (26 votes cast)

    XmlNode Reader

    This is a simple little addition I have made to my Helper class today, in order to facilitate reading XMLFiles for settings. It makes use of XPath and is pretty simple: What this does is return a collection of XmlNodes so that you may loop through and get the information necessary. Here is an example of a Configuration-Style XML File: Now what I need to do is get the path attribute for files of type js for the page with the name Default. All I will need to do is: or even Like I said; pretty simple. Basic even. But it saves me a couple of lines of code, so I'm happy about it.
    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    Session Manager

    How often do you find yourself needing to use Sessions when developing using ASP.Net C# and are absolutely antagonized at the sheer amount of validations which you end up making in order to use the Session as a property? The above, is simply annoying to implement, and as usual I have my own little wrapper class which not only simplifies implementation, but allows you to access the Session even from classes which do not make a reference to System.Web (handy if your DAC (Data Access Layer) needs to know a value on the Session (a LanguageID perhaps?). This post is divided into two parts:
    1. The Session Object
    2. The Session Manager (which comes with Page and UserControl extensions!)

    SessionObject<T> The SessionObject is an object which will be stored in a static collection (on the Session Manager) used to acquire values from the session. The reason I am making use of an empty interface will become more apparent in the implementation of the SessionManager. A brief explanation: The Session property returns the current session which is being used. Hence this class requires the use of System.Web, but if you're anything like me, you would have created a separate Class Library with all your C# 3.0 Extensions in it and making a reference to System.Web here won't matter. Don't worry, you won't need to make a reference to System.Web in your Data Access Layer; I won't go back on my word. The Constructor puts together an object which consists primarily of a Session ID, or more commonly known as the Session's key (like "pageID" mentioned in the example above) and the Default Value which is to be returned, should the Session key not exist. The Get method, does what you usually do; returns a default value if the Session is null, or returns the Session object (typed!) if it does. The Set and Clear methods are pretty obvious in their intended functions.
    SessionManager The SessionManager is the brains behind the whole setup, the controller which manages all the SessionObjects which will be present: At first look you will notice that this class is static, and hence single instance. This is to cater for two things:
    1. Instances will not be created for this class, hence less Garbage Collection
    2. Accessible from within static methods; particularly useful when you are using C# Web Methods for AJAX
    In order to utilize Context.Session.SessionID (highlighted in red), I built the following simple class into my Extensions Library: The first two methods are overloads of each other, returning the SessionObject<T> highlighted above. There are two ways to acquire this (hence the overloads):
    1. Without a specified default value. This will utilize default(T).
    2. With a specified default value (with thanks to Lukas Pechar for the suggestion), which will return the specified default if the session is null. This is particularly useful if you wish to return "-1" as an integer's default, or true as a boolean default, or String.Empty as a string on and so forth.
    That's all there is to it! The rest, are extensions! Usage within a Class Library: Usage within a Page/UserControl Go forth and manage Sessions easier!
    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    Ajax Server Side Validation

    There are times you would want to do some sort of server-side validation on a form. As an example, you might want to validate a user's login credentials. In my case, the reasons for developing this validation wrapper, were to ensure that an ID was populated on the server, before allowing my Wizard to proceed to the next step. My opinion of ASP.Net's CustomValidator is that it is, quite frankly; horse shit. So, as per usual, I set about making my own way. My requirements were as follows:
    • User clicks "Next" (or Submit) button
    • Server checks if ID is populated
    • Server returns this information
    • If ID is not populated, prevent moving to the next step
    • If ID is populated, allow moving to the next step
    Clearly Ajax had to be used here, and I opted to use JQuery's $.ajax as I find it to be absolutely splendid. The secret to achieving the functionality we want, is to set the async property to false. The reason being that with the async property set to true, Ajax will behave as Ajax is supposed to behave. In our case we do not want Ajax to behave normally, as the form would submit while the Ajax call was being made. As is my style, I decided to create a wrapper functionality, making the whole thing rather generic and fun to use: The way this works is that it makes a call to the path which you give it, passes the data which you give it and depending on the server's response, will execute one of the functions (successEvent / failEvent) you passed to it. Meanwhile on C#'s back-end: This is pretty self explanatory, I won't insult your intelligence and explain what it does :) And to use this method on your page? Simple: If you're curious about the String.Format, please refer to here. And that's all there is to it! The process goes like this:
    • User clicks button
    • The click function we binded is fired
    • The ValidationEvent function is fired
    • Ajax call is made to server using our details
    • Depending on the response from the server, the success or fail events are executed
    • In my case, I only passed a failure function; TemplateValidationFailure
    And that's all there is to it!
    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

    Combining JavaScript or CSS Files

    I spent some time today, mulling over the evidently dismal state which lies in future Web Development. Already we see the horrors of script references upon script references as business-folk and neophyte developers alike, cram component after component after component into the same page. Buzz words like "Web 2.0", "SEO" and "value-added" being thrown around the room like the flaccid, empty whores that they are. Needless to say, I fell into a depression, realizing that there is no way to avoid these things. Forever shall pages be polluted by script references upon script references. Forever shall pages take forever to load and forever shall management complain (and rightly so) about the speed of a website. But should it remain that way? "No" says I; emphatically. Hence I decided that something needed to be done. I trust we all know about GZip and Minification. If not, please do go and educate yourself about these little things. They are quite useful. In addition to those two techniques, there is also the idea of cramming all your scripts and all your css into singular files. Why? Well clearly this is done in order to reduce the number of files requested from the server. What this achieves is that the page will load quicker. What this also achieves is further messy coding. All scripts in one single file? Really? That doesn't sit too well with me I'm afraid. I like having things organized. Folder structure and independent files are key to me maintaining the vestiges of my sanity in a world gone mad. But the results of such a technique are clear, evident, obvious. But I want the best of both worlds. And as an ASP.Net programmer, I figured out how to do this within the space of 10 minutes and decided to share it with you. I'm 100% sure this functionality may be replicated successfully in PHP and I will be making an effort to do so within the following couple of days. So, what is this technique I thought of? Imagine if you will, if the server were to read the files you wish to serve and append everything into a single file and serve that, instead of serving, say...10 JavaScript files. That's pretty much the principle of it all.
    First things first. This is coded in ASP.Net and what I will be showing you is a hard-coded version. You should definitely make this data-driven. Why? Because it's god damn cool. And I love cool things. Start out by adding a Generic Handler (and ashx file) to your solution. I called mine "IncludeHandler.ashx". Next, code it up so that it looks something like this: Next, make sure you have all the files listed in the "files" generic List<string>. For my "test.js", I entered the following script: Include the following into the <head> tag of your page: Now, run it. Result: If you're using a hip browser like Google Chrome you can go take a look through the "View Source" and click on the link to "IncludeHandler.ashx?type=js". Otherwise, you can just type in the link yourself in the address bar. What you'll see is that all the code from your script files has been tossed into one response. Let's do a comparative benchmark test using Chrome's load speed graph. The first candidate for this test will be the standard way of doing it; ie: 3 script references, ie: The result: Now, if we do the same thing, except with the previous script reference, ie: 1 script reference, ie: The result: So. 1670 ms -vs- 569 ms. An entire 1.1 seconds shaved off. Not bad! The advantages here are evident. Not only did we manage to toss in all our scripts into a single file, but we maintained an organized file structure which won't make us tear out what little hair we have left. The same advantages apply to StyleSheets. Don't believe me? Try it! I do believe it's worth your time. NOTE: Before nose-diving into this, read the following: here.
    VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)