page 1 of 4
1 2 3 4 next>>  

Sorry I haven't blogged anything lately...

February 20, 2008 • 7:50AM • permalink
I appreciate the emails I've received asking about when I'll blog next or giving suggestions for topics. I have a few pending entries, I've just been wayyyyyy too busy over the past couple of months. I appreciate all the messages I receive and will absolutely respond to every one of you as quickly as possible, so if you don't receive a prompt response - be patient!

I recently cleared up a very large project and I have another deal in the works that will clear up some more time (more details on this later).

So look forward to new entries in the near future!


.NET Interview Questions - Part 3

December 02, 2007 • 7:56PM • permalink
I received such an overwhelming response to my last two blog posts on .NET interview questions, that I decided to post a third.

Part 1 can be found here.

Part 2 can be found here.

Continuing from where we left off...


6. If placed in the Page_Load method of a ASP.NET page, what will the following code output?


Response.Write("<br />Before");

try
{
   Response.Write("<br />In the 'try'");
   int i = 0;
   int j = 1 / i;
}
catch
{
   Response.Write("<br />In the 'catch'");
   Response.End();
   return;
}
finally
{
   Response.Write("<br />In the 'finally'");
}

Response.Write("<br />After");



Pretty simple question, right? Wrong!

I got it wrong the first time round too and even for the posting of this blog I made sure to execute the program and check the results!

You would see the following:


Before
In the 'try'
In the 'catch'
In the 'finally'


Remember that the finally clause will execute without exception (no pun intended). I tried to really drive that home by first executing Response.End, which even throws a second exception, and then executing a return function, in an attempt to leave the currently executing method.

Regardless of the return, the finally clause still executes before returning control to the return statement, preventing the display of the word "After".


7. Write a script to generate a dynamic image on a webpage, such as for use as a CAPTCHA, placing a watermark on an image or checking the referring url of a requested image?

For my example, I'll display 10 characters of randomly sized/styled/selected text in on a Red background. Note that I'm not going to introduce any warping, backgrounds or any other security features. This code is not intended for use as a real CAPTCHA and it would be trivial to write a OCR script to attack it.


I'm going to put the whole block of code without too much discussion. Most of the work is done by the GDI functions, which you can easily look up on MSDN. This would be placed in the OnLoad portion of a page and then called through a img object in the HTML like:

<img src="CaptchaImage.aspx" />


Note that we have previously defined the following helper structure to avoid repeated boxing/unboxing:


struct CaptchaCharacter
{
   public char character;
   public Font font;
}



The rest of the code follows:


int width = 600;
int height = 400;


int number_of_characters = 10;
string character_choices = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
//NUMBERS 0+1, LETTERS I+O removed for legibility reasons

string[] font_families = { "Tahoma", "Arial", "Verdana" };
int[] font_sizes = { 36, 60, 84, 108 };


Rectangle bmp_rect = new Rectangle(0, 0, width, height);

Bitmap bmp = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bmp);
graphics.SmoothingMode = SmoothingMode.AntiAlias;



graphics.FillRectangle(Brushes.Red, bmp_rect);

CaptchaCharacter[] character_array = new CaptchaCharacter[number_of_characters];

Random rnd = new Random();
for (int x = 0; x < number_of_characters; x++)
{
   CaptchaCharacter new_char = new CaptchaCharacter();

   new_char.character = character_choices[rnd.Next(0, character_choices.Length)];

   new_char.font = new Font(font_families[rnd.Next(0, font_families.Length)],
font_sizes[rnd.Next(0, font_sizes.Length)]);


   character_array[x] = new_char;
}

StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

GraphicsPath path = new GraphicsPath();

for (int a = 0; a < number_of_characters; a++)
{
   RectangleF rect = new RectangleF((width / number_of_characters) * a,
0,
width / number_of_characters,
height);

   path.AddString(character_array[a].character.ToString(),
character_array[a].font.FontFamily,
0,
character_array[a].font.SizeInPoints,
rect,
format);

}


graphics.FillPath(Brushes.Black, path);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);


//we dispose all the Graphics objects

for (int z = 0; z < character_array.Length; z++)
   character_array[z].font.Dispose();

path.Dispose();
graphics.Dispose();
bmp.Dispose();



First a Bitmap object is created, which is what we will eventually output. After obtaining a reference to it's GDI Graphics object, we begin drawing on it. First a background rectangle with a Red brush is drawn and then a GraphicsPath object is created. We can use the built-in AddString method of the GraphicsPath to easily style and add our characters. We could have easily output the whole string at once, but we loop through each character to apply individual styling of FontFamily and font size to each character. Finally, we change the ResponseType of the our encapsulating page and save the bitmap to the built-in OutputStream (which will block all other output to the page).



Lately, I've seen a lot of really bad SQL come through the office on interviews. In our extensive interview process, many of the other developers focus on simple SQL problems, which is really all that is necessary for the day-to-day job at Demand.

Unlike some of the other developers, my boss constantly chastises me for worrying about security too much. I can't deny that I do obsess about security too much, given my background, but because of that I'll occasionally ask the following question, which I think any SQL developer should be able to answer:

8. Given a simple login box (with username and password fields), what input will compromise the database in a susceptible system?

I'll even go so far as to show you the poorly written code that will allow this... (Note that the code is looking for the password of the given user and will check it in C# code below, that's all it takes to allow an exploit).


string sql = string.Format(@"
SELECT
   password
FROM [dbo].[Accounts]
WHERE username='{0}' ", Request.Form["username"]);

DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(connection_string);
SqlCommand command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;

connection.Open();
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sdr);
sdr.Close(); //this will close the connection too

if (dt.Rows.Count > 0)
   if (dt.Rows[0]["password"].ToString() == Request.Form["password"])
      LoginUser();



First, the exploit. There are an infinite number of things you can do with a SQL Injection, but we'll use the simple input:

' AND 0=1 UNION SELECT '123456' -- in the username field and 123456 in the password field.


This turns the executed query into:


SELECT
   password
FROM [dbo].[Accounts]
WHERE username='' AND 0=1 UNION SELECT '123456' --'



First, you'll note that the -- placed at the end will comment out the original query ending, including the single-quote. The end result has the WHERE-clause being interpreted as username='' AND 0=1. Obviously, the AND 0=1 portion will cause the entire clause to return FALSE. At this point, we UNION a literal '123456', which will allow us access to the site. (Note that this is a very simple example, in most cases you would most likely be selecting back the matching user account and hence could theoretically login to any account.)

Some may argue that I made the impossible possible by revealing the original source code, but that's not necessarily true. For anyone that's attempting a SQL-injection, it's most likely not a large leap to write a script to brute force the parameters of the victim query. At that point, you can literally do whatever you want by using a little ingenuity and the INFORMATION_SCHEMA object, supported by most RDMS.


.NET Quickies

* Using a method of the String object, what is the optimized .NET way of performing the (often executed) compound conditional:


if (some_string != null && some_string != "")
   DoSomething();



String.IsNullOrEmpty()
(in my tests for this blog entry, it consistently performed 40-45% faster)



* When encoding data, what is the key overall difference between hashing and encrypting?

Hashing is a one-way mapping, while encryption has a corresponding decryption which will reverse the process.


* What is the effect of making a method of a class static and what might it's use be?


Static methods are not associated with any one instance of the class, nor are they able to access any instance fields of a class. Thus, instead of invoking the methods through an instance call, you use the name of the class instead (since you are referencing the single Type object of that class maintained by .NET), like so:



string s = "some test string";
bool starts_with_some = s.StartsWith("some");
//StartsWith uses the instance s


bool not_null_or_empty = string.IsNullOrEmpty(s);
//IsNullOrEmpty is a static method




Static methods allow you to provide stand-alone methods that relate to a classes functionality. Another example might be a Country class. I might use it to represent a single country object, with fields/properties like CountryID, Name or ZipCodeList. I might also include a method to use the current class' data like GetIPRange() or FindContinent(). Finally, I could also add stand-alone (static) methods, like Country.GetAllCountries() to return a List containing the name of every country on Earth.



I want to add the additional note that since I've been seeing an increase in the number of "demand media" interview questions Google searches hit my blog, we have been working on restructuring our interview process to change the questions around and are now working towards a much more hands-on interview. Note that part of the review process includes reviewing my blog for any questions and removing them (or limiting the use of them) from our interview process. So make sure you know how to use .NET in ways outside the scope of these questions.




I also want to encourage people to continue contacting me with your questions and comments. As long as there is an interest in the topic, I will continue to present real-life .NET interview questions.


Book Review: Programming Erlang

October 23, 2007 • 8:54PM • permalink
As you may know from reading my previous blog entries, I've recently been trying to mix up the books in my reading queue by exploring the benefits of a few new programming languages. Recently a friend of mine told me a few things about functional programming, concurrency and Erlang which inspired me to check it out.

Joe Armstrong, one of the creators of the Erlang language, has recently published a new book on the topic and its truly a fascinating read.

One of the biggest complaints I hear from other developers about any introductory level book about a new programming language is the lack of useful programs that can be created upon completion of the book. What I mean is that you may be able to do the normal "Hello World", Fibonacci sequence output, etc. - but you probably won't be able to do anything really useful. This isn't the case with Armstrong's book.

The main ideas of the book and of Erlang (free for most environments at http://www.erlang.org) in general is concurrency or the simultaneous execution of code. While C and its variants offer multi-threading, it is still essentially executing sequential code and hence subject to deadlocks, race-conditions, etc. Erlang enforces some strict rules from the get-go to support concurrency and allow for true simultaneous execution that is free from not only race-conditions and deadlocks, but from semaphores, mutexes and locks as well.

In order to do that, Erlang turns computer science on its head (from a sequential programming point-of-view) which Armstrong is quick to point out at every turn. For example, variables are only called as such because it makes things easier. The fact is they can't actually vary and an Exception is thrown if you even try.

On that same note, the equal sign is not the assignment operator like it usually is in programming, it is instead used to perform pattern matching. An example would probably work best to explain it:


1>X = 5.
5

2>X = 5.
5

3>X = 3.
=ERROR REPORT==== 16-Oct-2007::21:26:12 ===
Error in process <0.30.0> with exit value: {{badmatch,3},[{erl_eval,expr,3}]}

** exited: {{badmatch,3},[{erl_eval,expr,3}]} **



As I stated before, the = is not the assignment operator, it is instead used for pattern matching. An additional caveat though, when used with an uninitialized variable (which usually start with Capital letters), the variable is assigned that value. In line 1 above, we match the variable X against the literal value 5. Since X is uninitialized at the time we match it against the literal 5, it then takes on that value.

This is why, when we repeat the action in the second line, it returns the value 5 (indicating a match). Consequently, when we hit the third line, the shell throws an exception since we're matching X against 3, when it has already taken on the value 5.

You may wonder what the value of such an operator is, but when you dive into server programming, you'll see that it can be used (among other things) to direct functionality within network protocols. By matching against certain patterns, you can essentially code mini-conditional statements to perform various actions upon receipt of certain data. It seems complicated, but it's really not - since this is a Book Review and not an Introduction to Erlang, so I'll leave the explanation to Armstrong...

Within 75 pages, I had gained an enthusiasm for Erlang that was apparently infectious and it has been embraced by a few other developers in my Department (including Jon over at Rusty Razor Blade). While we're still not 100% sure it will be able to support the traffic load and perform fast enough, we're motivated enough to try. Armstrong makes it easy to learn from example too, since the book contains Erlang source to create a server for almost any major network protocol or project you could think of including IRC, SHOUTcast, a simple Error logger, a SQL Server and a Web Server.

We've discussed a plethora of different ideas we could run on our "new Erlang Framework", some more ambitious than others. We're convinced we could rewrite memcached in a few hundred lines of code, including all the features of the original - a few that are missing and commonly implemented in other cache systems - as well as a few of our own custom design. We figure if we can even get 80% of the throughput of our current memcached implementation than it will be worth our trouble. Especially if it enables us to build a Erlang Framework to support any scalable idea we can come up with.

So if the idea of scalable server applications, functional programming or Erlang in general seems interesting, I highly suggest you check out Programming Erlang.


How to Create Dynamic Blocks in Drupal

October 14, 2007 • 10:21PM • permalink
One of my clients uses the Drupal CMS Framework, which requires me to code custom modules and create custom blocks. Drupal (and PHP in general) make a lot of things very easy, but in some cases (Drupal in particular) make the simple things VERY difficult. I've come across quite a few cases where I needed to create dynamic blocks of content that can be stored and retrieved. At first I thought Drupal would make it impossible, but the solution is actually quite simple.

For this example, I'm going to build a simple Google AdSense module that will allow the creation of an infinite number of blocks.


The Assumptions

1) This module was built using Drupal 4.7. I'm not familiar enough with other Drupal environments to assure that this will work, but if anybody tries testing it on other Drupal versions - please let me know so I can update this blog entry!

2) I'm going to assume that the reader has built a basic Drupal module before and does not need a basic explanation of hooks.

3) I'm going to assume that there was previously a variable_set('google_adsense_code', 'pub-XXXXXXXXXXXX-XXXX') call in some form that will allow the site administrator to set their personal AdSense code.


The Database

Now, let's setup a basic database schema for this module. (Note, this was executed on MySql 5.0.22)


CREATE TABLE IF NOT EXISTS gadsense_blocks (
   bid INT AUTO_INCREMENT PRIMARY KEY,
   width INT,
   height INT,
   type VARCHAR(32)
);



The above would either be executed directly on the database server or embedded in a Drupal module .install file to create the table the first time the module is installed.

The above table is very simple with an auto-incrementing bid, the width and height of our target ad, and a simple text field we'll use to store whether our ad is a text or image ad (or both).


The Core Module Hooks

As I said above, I'm going to assume the reader has built a basic Drupal module before and can understand the below without explanation.


function gadsense_help($section = 'admin/help#gadsense') {
   switch ($section) {
   case 'admin/modules#description':
      return t('Creates an area for Google AdSense support.');
   }
}


function gadsense_perm() {
   return array('administer adsense');
}


function gadsense_menu($may_cache) {
   $items = array();

   $items[] = array(
      'path' => 'admin/settings/gadsense/list',
      'title' => t('Google AdSense Ads'),
      'callback' => 'list_ads_page',
      'access' => user_access('administer adsense'),
      'type' => MENU_CALLBACK,
   );

   $items[] = array(
      'path' => 'admin/settings/gadsense/add',
      'title' => t('Google AdSense Ads'),
      'callback' => 'create_ads_page',
      'access' => user_access('administer adsense'),
      'type' => MENU_CALLBACK,
   );

   return $items;
}




The Administrator Pages

Now that we've got our core module created, we can get to work! We're going to create two pages for basic administration. The first page, the main admin page, will list all the blocks we've created so far and offer a link to create a new one.


function list_ads_page() {
   $result = db_query('SELECT * FROM {gadsense_blocks} ORDER BY width + " x " + height ASC');
   $rows = array();
   while ($field = db_fetch_object($result)) {
      $rows[] = array($field->bid, $field->width, $field->height, $field->type);
   }
   if (count($rows) == 0) {
      $rows[] = array(array('data' => t('No ad blocks have been defined.'), 'colspan' => '6'));
   }

   $header = array(t('id'), t('width'), t('height'), t('type'));

   $output = theme('table', $header, $rows);
   $output .= '<br /><br />';
   $output .= l("Add a New Block", "admin/settings/gadsense/add");

   return $output;
}



This will form the page that you see here (by default):



The second page will perform the first half of our Drupal "magic". We're going to build the page to create our blocks. First we need to draw the form. Again, I'm going to assume you're competent with Drupal module building and just supply the code:


function create_ads_page() {
   $form = array();

   $sizes = array('120x600', '160x600', '728x90', '468x60', '300x250');
   $types = array('text', 'image', 'text/image');

   $form['ad_size'] = array('#type' => 'select', '#title' => 'Ad size', '#options' => $sizes);
   $form['ad_type'] = array('#type' => 'select', '#title' => 'Ad type', '#options' => $types);

   $form['submit'] = array('#type' => 'submit', '#value' => 'Submit');

   return drupal_get_form('create_ad', $form);
}



Which will show the following page:




When submitted, the following code is executed.


function create_ad_submit($form_id, $form_values) {
   $ad_sizes = array('120x600', '160x600', '728x90', '468x60', '300x250');
   $width = 0;
   $height = 0;
   $type = '';

   //check for valid sizes
   foreach ($ad_sizes as $key => $value) {
      if ($form_values['ad_size'] == $key) {
         $dimensions = explode('x', $value);
         $width = $dimensions[0];
         $height = $dimensions[1];
      }
   }

   if (intval($form_values['ad_type']) <= 2) {
      $types = array('text', 'image', 'text/image');
      $type = $types[$form_values['ad_type']];
   }

   if ($width == 0 || $height == 0 || $type == '') {
      drupal_not_found();
   }
   else {
      db_query("
      INSERT INTO {gadsense_blocks}
         (width, height, type)
      VALUES
         (%d, %d, '%s')",
      $width, $height, $type);

      drupal_set_message('Ad block created');
      drupal_goto('admin/settings/gadsense/list');
   }
}



After splitting the ad size selection into $width and $height variables and grabbing the ad $type, we insert a new record into our gadsense_blocks table. As shown above, this will create give it a unique bid value, which we'll reference later.

I'll create a few different blocks, and now our main gadsense page will be populated. Like this:



Now, the last thing we need to do is implement the block hook for both the list and view operations.


function gadsense_block($op='list', $delta=0) {
   if ($op == "list") {
      $result = db_query('
   SELECT
      *
   FROM {gadsense_blocks}
   ORDER BY width + " x " + height ASC');

      $rows = array();
      while ($field = db_fetch_object($result)) {
         $block[$field->bid]["info"] = t('Google AdSense - '.$field->width.'x'.$field->height);
      }

      return $block;
   }
   else if ($op == 'view') {
      $result = db_fetch_object(db_query('
   SELECT
      *
   FROM {gadsense_blocks}
   WHERE bid = %d',
   $delta));

      if ($result->bid > 0) {
         $block['subject'] = 'Advertisement';
         $block['content'] =
   '
   <script>
   <!--
      google_ad_client = "'.variable_get('google_adsense_code', '').'";
      google_ad_width = "'.$result->width.'";
      google_ad_height = "'.$result->height.'";
      google_ad_format = "'.$result->width.'x'.$result->height.'_as";
      google_ad_type = "'.$result->type.'";
   //-->
   </script>
   <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
   </script>
   ';

    }

   if ($block)
     return $block;
   }
}



In the list operation, we select the gadsense blocks from out of the database and use them to populate the global block list. This is the "magic" behind our module.

Normally modules use hardcoded integers for indexes in the block hook, but as long as they are unique, Drupal couldn't care less what the index values actually are. Since we use the auto incrementing primary key column from our MySql database, we know the values will be unique.

Now, our /admin/block list will contain blocks that mirror our gadsense list:



The other operation we implement in our block hook is the view operation. This is what draws the block content - in our case, a Google AdSense ad.

The unique bid value that we used to index our block in the list operation is handed to us in the view operation. Then we just lookup the information about the ad's width, height and type and output the javascript that is required to call Google's script.

So, if we check the box to add the 468x60 ad block that we created, we'll see that it appears like this:




The Enhancements...

The finished version of the module that I created has numerous enhancements that you can easily add yourself, such as the ability to edit the block settings, delete a block, clone a block, change the AdSense tracking code, add an AdSense channel, etc.

Additionally, you can tie in to any setting that Google offers on the AdSense platform. Specifically, my module offers a color wheel to set the text color, border color, and other layout specific features.


The Google AdSense module is just one simple use for this concept. Dynamic blocks can be used in millions of situations such as allowing users to create their own blocks for display or share with their friends, index the blocks using the current date and show Holiday specific blocks, automatically import affiliate links and create dynamic blocks and many others. Once you start experimenting with it, I'm sure you'll come up with all sorts of unique ideas!


Reflection on ASP.NET Auto-Compiled Classes

October 12, 2007 • 8:16AM • permalink
I came across a unique situation yesterday that took awhile to figure out, but I thought it was a really cool concept!

The basic idea is that I have an ASP.NET website that references a DLL. The DLL contains an interface that other classes can implement, with the general idea of allowing external classes (external to the DLL) to act as "plug-ins". The logical location to place these classes is in the App_Code folder, since it will auto-compile the classes and make them available globally, but that's when I ran into a problem...

The DLL also contains a static class to populate a static collection of the classes, so that they can be referenced by name. Since the classes act as "plug-ins", they should be able to be modified at any time, as well as allow for new classes to be dropped into the App_Code folder. The only way to deal with a situation like this is with Reflection.

So, I included a reference to System.Reflection and tried loading the type information for one using Type.GetType(). That failed miserably as the return value was null. I thought for a minute and then wrapped the class placed in App_Code in a unique namespace. I went back to my call to Type.GetType() and tried referencing the class using this namespace. Again, a NullReferenceException.

How did I get around this issue? The solution is actually VERY VERY simple! You just need to get a reference to the Assembly that the App_Code folder gets compiled into by using a call to Assembly.Load("App_Code"). After that, you can use the returned assembly reference in order to get the class type. So, if I have a class named AdamWidget in my App_Code folder that implements the IWidget interface from my DLL. The code in the foreign DLL to load a Type instance for that class could be:


Assembly asm = Assembly.Load("App_Code");
Type module_type = asm.GetType("AdamWidget");
if (module_type.GetInterface("IWidget") != null)
{
   DoSomething();
}




That's all there is to it! Now our web application can import (through the DLL) any class that implements IWidget in our App_Code folder!

Please also note that I discovered later that you can also reference the same dynamic assembly with a call to Assembly.Load("__code").





page 1 of 4
1 2 3 4 next>>  


Highest Rated Blog Entries





Tags

query driver c plus plus Regular Expressions web development MySql API c technology Introduction c sharp Javascript functional programming Google AdSense Adrianne script generation testing type development Remote Desktop SQL Windows VB anime convention AnimeConPics network Generic Method Demand Media internals AnimeDates operator Adam Drupal interview PC protocol CosplayWar help T-SQL hack csharp AlternativeNicheNetwork new site concurrency math Immutable String IIS Google programming Win32 API

Links