Mark Mintoff My superpower is common sense

16Nov/120

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)
  • 26Oct/120

    C# Programmatic Active Directory Impersonation

    Recently, a requirement involving shared folders forced me to dabble into Active Directory account impersonation.

    The following is what I ended up doing:

    Usage is pretty simple:

    And you're good to go. I managed to browse through the shared folder programmatically and copy over the files needed for my ETL.

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

    C# Console Progress Bar

    At work, I sometimes find myself needing to make Console applications which take some time. For example, I have a few console applications which parse dump files into objects and then insert the data into a database. Usually, I represent the progress of these applications with a simple incremental percentage display, however I thought I'd create a generic method which would display an ASCII progress bar.

    The code itself is pretty self explanatory and probably more verbose than it really needs to be, but it gets the job done and looks good. It is a nice throwback to Pascal and QBasic for me.

    EDIT: Amended code to append characters to a string before writing on screen. This fixes the flickering problem.

    VN:F [1.9.22_1171]
    Rating: 5.0/5 (13 votes cast)
    27May/120

    The Towers of Hanoi Problem

    About a year ago, in the summer of 2011 I had found myself unemployed for 2 months through no fault of my own. I had accepted an ASP.Net development position with a gaming company called GamingVC and had thus resigned from my job at WagerLogic.

    Unfortunately, on the day I was to begin my new job with GamingVC, as soon as I entered the building; I was taken into a boardroom and fired without reason. Thus, I spent two months searching for gainful employment and had many a strange interview.

    The worst interview I had that summer, and consequently the worst interview I had in my entire life is what I shall be talking to you about today.

    By nature, I am an introverted person. I do make an effort to be sociable, however it takes me some time to warm up to a person and be comfortable. The interview, unbeknownst to me consisted of an interview with a woman in human resources and then a surprise interview consisting of the IT manager and a senior programmer. The IT manager was boisterous and rude, bouncing a stress ball against the wall, seemingly paying no regard to a word I was saying. I felt stressed, sweating inside a thick suit in the middle of June, when suddenly the CIO walks in. After a few minutes he launches into a tirade about games.

    He mentions to me Towers of Hanoi as if it were the greatest game ever to have been created (he's wrong, the greatest game is chess), framing it with arrogant disdain aimed at me with the term "before your World of Warcraft nonsense we had a game called Towers of Hanoi". It is funny, come to think of it, because I never even played World of Warcraft. Anyway, he wanted me to programmatically solve Towers of Hanoi on a whiteboard whilst they all watched. Given my character and nervousness I failed miserably and here's why:

    Towers of Hanoi is a game I played when I was seven years old. I played it on a cheap hand-held device along with Tetris, Snake and some other monochrome pixel games. At that age, I had not a care in the world and I had not yet started to analyze everything in terms of functional programming. Nor had I any idea what recursion was when I was that young. Suffice it to say, I knew how to solve it myself, which I saw mentally as a while loop, without having figured out that it was a recursive loop. What's more I am not accustomed to programming without a computer and with three people burning a hole in the back of my head.

    So, for the sake of no longer feeling stupid (because they made me feel pretty stupid) at having mucked it up so badly during my interview, I present to you the solution:

    I believe that redeems me from the absolute mess of a while loop I had tried to do on a whiteboard and I can (after a year) finally move on.

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

    C# Timed Execution

    A nice and comfortable way to time how long a particular code block has taken to execute.

    Usage is easy. Here's a simple example:

    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)
    20Dec/111

    Benchmarking Infinite Loops

    cycle

    Today, my good friend Andrew Calleja and I set about discussing infinite loops and which technique for infinite loops would be the most efficient. Our choices boiled down to four:

    • for( ; ; )
    • while(true)
    • while(1==1)
    • GOTO loop

    I created a small program to perform a benchmark test and the discrepancy between the four techniques was negligible enough to attribute to other operations in the background, so we agreed that we would have to look into the CIL using ILSpy. What was discovered was very, very interesting. First and foremost, the loops are programmed as follows:

    After opening the .exe file in ILSpy, I noticed that all of the above were converted into while(true) loops!!

    However, when I switched the language from C# to IL:

    As can clearly be seen, the GOTO loop gets compiled into the shortest IL. Additionally the GOTO loop does not create a superfluous boolean. Quite interesting!

    Please note that this IL was generated when the program was compiled in Debug mode. When generating the IL in Release mode, the loops all generate the same IL:

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

    C# Search Stop Words

    VN:F [1.9.22_1171]
    Rating: 5.0/5 (2 votes cast)
    11Jul/112

    Using Programming for Groceries

    This is not something which fits in with the general theme of my blog, but it does involve programming. One of the things which I find irritating, wasteful and unnecessarily time consuming, is grocery shopping. If you want a lean grocery list with little waste, you need to spend time writing a list. If you don't have the time to write a list, you end up impulse buying and then eventually throwing out something when it starts going bad.

    I decided that a little bit of programming would resolve this issue. What I resolved to do is type up an XML file with meals and the ingredients required of that meal. For example:

    I then used XPath to walk over the XML file, creating a collection of objects. Then X (user-defined) meals are selected at random. The ingredients of each meal are collected together (aggregating the amounts for equivalently named ingredients) and a shopping list is generated. The costs of the ingredients are also aggregated to produce an estimate of the cost of your shopping trip.

    My plans for this small application are to also add items which are recurring buys such as coffee, sugar, soap..etc. I am at this stage unsure of how to go about with this. Do I simply tack it onto every shopping list and then check my supplies? I think the best way would be to integrate this with an inventory-style system so that your list would be checked against your stock levels, effectively filtering out the items you already have from your final shopping list. I just wonder on the practicality of keeping an inventory system in a small household.

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

    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)