Currently showing entries with the tag: Demand Media

page 1 of 1
1 

.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.


Mikomicon - September 7th - 9th

September 03, 2007 • 8:31AM • permalink
Mikomicon is next weekend at CSUN, in Northridge, California. It is an anime convention that is in its second year. Adrianne and I will be running a booth for a few of our websites.

While we still haven't finalized everything that we'll have there, we will have a few freebies to give away to everyone, as well as a few raffles for larger prizes. I believe it will be in the convention program as AnimeDates.com, but we'll have giveaways for AnimeConPics.com, WiimindMe.com, CosplayWar.com (coming soon), as well as a few giveaways from Demand Media.

We invite anyone in the area to come down and say hi! We will be setup in the Dealer's Room at Tables 3-5, or roaming around taking pictures of cosplayers!


.NET Interview Questions - Part 2

August 26, 2007 • 9:41PM • permalink
Part 1 can be found here.


Continuing where we left off...


3) What does the term "immutable string" mean?

Strings in C# are immutable, meaning that the string object cannot be modified once it has been instantiated. Take a look at the following:


string s1 = "Hello, my name is ";
s1 += "adam";



While it appears that the string 'adam' is simply being appended to the original string, a lot more work is taking place on the back end. Since the string s1 is immutable, it can't be changed. Implicitly, c# is creating a new buffer in memory that can hold both the "My name is " and "adam". Once this new buffer is filled (and a new string object is created) s1 is assigned the new reference and the old references eventually become garbage collected.

If you read my blog entry on the System.Diagnostics.Stopwatch class, you saw that this can have a huge effect on the performance of an application.

In the Stopwatch blog entry, I used the string.Concat method in the optimized test. While that method outperforms the standard += operator (and can be further optimized by using the overloaded version that allows passing in four string parameters), there is an even better way, for doing many append operations.


using System.Text;
//Place this at the top...



StringBuilder sb = new StringBuilder();
string letters = "abcdefghijklmnopqrstuvwxyz";
int iterations = 100000;

for (int i = 0; i < iterations; ++i)
   sb.Append(letters[i % 26]);



In my tests, the StringBuilder class' Append method was twice as fast as using string.Concat. This is because the StringBuilder class has preallocated a buffer of memory upon initialization, which the string.Concat object is still creating extra immutable string objects that aren't needed.


4) Describe the concept of lazy-initialization in OOP?

Lazy-initialization is best shown with a working example...

Let us take for instance that we have a class that represents a Building, perhaps for a game. In this Building class, we have various properties to represent the different rooms that you might find in the building.

For sake of this argument, let us also suppose that the general architecture of the game dictates that the Building class reference is going to be persisted in a database and not in static memory (maybe it's web-based). When we create the instance of the Building object, it would be a huge mistake to instantiate all the various rooms of the Building in the constructor.

There could be a Kitchen, a JanitorCloset, a SupplyRoom, a Gym, a Hallway or maybe even Bathroom[]. If only one of the above is used in the current execution, then we would waste a lot of processing on both the web server and possibly on either a cache server or a database server (or both), retrieving data for the rooms we don't need. This is a very common mistake that is made by developers that are new to OOP.


Lazy-initialization can help us improve our performance by only creating the objects as they are needed. Like in the following example:



public class Building
{
   private Room kitchen;
   private Room supply_room;

...


   public Room Kitchen
   {
      get {
         if (kitchen == null)
            kitchen = new Room(building_id, 'kitchen');

         return kitchen;
      }
   }


   public Room SupplyRoom
   {
      get {
         if (supply_room == null)
            supply_room= new Room(building_id, 'supply_room');

         return supply_room;
      }
   }
}



In the code above, the first time the Kitchen or SupplyRoom properties are used, their associated private fields will be null and will be instantiated through their respective Room constructors. If they aren't used in a given request, they won't be instantiated at all!


5) Write a Generic Method that takes one parameter of any type and returns the same type that is passed in.

This question really isn't fair, but we like to throw it out there anyways. We don't base any candidate on their ability to answer it (because although 1 person actually got close, nobody has ever answered such a simple question). This is actually one of the first questions we ask, mostly to set the bar. Most of the time we see a person writing a function that attempts to use Generics, which is better than some other things I've seen... (Note that this is a .NET 2.0 specific feature)

The solution is actually very simple:


using System.Collections.Generic;
//Place this at the top...




public T SomeFunc<T>(T obj)
{
   T new_object_copy = obj;
   return new_object_copy;
}



That's it! I only added the line T new_object_copy = obj to do something more interesting than just return the object.

We can now call this with virtually any type we want!


string s = SomeFunc<string>("hi");
int i = SomeFunc<int>(5);
my_class m = SomeFunc<my_class>(new my_class());



As a bonus, you can constrain the types of objects that you want to allow the function to operate on by adding a where clause:



public T SomeFunc<T>(T obj) where T : IList, IEnumerable
{
   T new_object_copy = obj;
   return new_object_copy;
}

List l = new List<string>();
List l2 = SomeFunc<List<string>>(l);
//This will work




string s = SomeFunc<string>("hi");
//This will no longer compile



Simple!

Maybe so, but we've yet to see somebody answer it correctly (and I've done literally fifty interviews in the last six months). We even joke around the office that if somebody can answer it correctly, they are an "instant hire". (Offer now null and void, since I've given the solution away.)




.NET Quickies

* What is the C# coalesce operator and how is it used?
The coalesce operator in C# is the ?? operator. It is used to do a conditional assignment to a variable, evaluating from left to right and stopping on the first non-null result. For example:

string a = null;
string b = "Yay!";
string c = a ?? b;
//The value in b will be assigned to c


* What is the size (in bytes) of the following data types on a 32-bit machine: byte, short, int, float and double?

byte = 1 byte
short = 2 bytes
int = 4 bytes
float = 4 bytes
double = 8 bytes


* What is the result of bit-shifting an integer (either to the right or the left)?
Bit-shifting an integer to the left will multiply the number by two for each bit shifted.
Bit-shifting an integer to the right will divide the number by two for each bit shifted.



I could talk about simple interview questions forever! I'm sure that I will have much more to write about on this topic in the future!


.NET Interview Questions - Part 1

August 07, 2007 • 9:52AM • permalink
With MANY open .NET development positions in the Media Department, I've had many opportunities to refine my interview process. Below is a summary of my experience, including some of the general .NET questions we ask most job candidates at Demand Media (and why). Since we are constantly refining the interview process and adding new questions and since this is going to be a rather long entry, I'll split it up into several separate posts.


General Interview Notes


First, a couple of general caveats:

1) I try to give the interviewee the benefit of the doubt. A lot of the time, the people I talk to have more years of experience than I've been alive, so I understand that a lot of them are intimidated by my youth.

2) Look up something about the company on the Internet. Of course nobody has time to redo their entire resume to cater to a specific company, but look up something about the company and try to tune your responses to items that might relate.

3) Most interviews I've been on included the question: "Do you have any questions for me?" That's your cue. Ask any intelligent question without appearing to be a snob, but make sure you ask something (besides your compulsory question about which snacks are kept in which kitchen.) A few stand-by questions I used to use are: "Will I be able to continue my personal education and learn here?", "How quickly do you adapt to new technologies and upgrades to existing technologies?", "What is the team dynamic like?" and "How much room is there for career growth at XXXXXXX Company?"

4) Your resume is your first impression. Use it as a way to highlight your strengths, not as a laundry list of items you "used once in school". There are two main items in particular I see all the time: C++ and .NET 3.5 - usually only by candidates who can't explain ANY intricate features of either.

5) An interview should be a learning process, as well. If you don't understand a question or an answer to a question, ask!

6) TURN OFF YOUR CELL PHONE!!! For many people I've encountered during my career (including me), a cell phone going off during an interview is an instant death sentence. You can start juggling keyboards after that - it's not going to matter...

And now finally...


.NET Questions


1) Describe the difference between a reference type variable and a value type variable?

This is a good question we use to get rid of the riff-raff right away. If you can't form some semblence of an answer to this question, we won't even consider you a candidate for a job.

While we look for many keywords, a simple description of the fact that a value type stores the actual value of the data and the reference type stores an address or pointer to the data usually suffices.

If you don't somehow relate the reference and value types to their storage location on the stack and the heap, that will definitely become question 1b.


2) Describe the process of using an integer variable (of any size) as a bitmap for boolean flags?

This is a process I brought with me to Demand (inherited from Intermix Media, where I propagated the idea as well), but I think it's fairly clear why this is a simple, but vital idea. (Although, I'm assuming below a basic knowledge of binary numbers and bitwise mathematics.)

The idea is that any number can be viewed as a series of bytes and then bits. First I'll describe the process, then I'll demonstrate it in both basic C/C++/C# code and then using .NET additions.

As you should already know, any number can be represented in binary form, which means any number can be represented as a sum of one or more powers of two. We can show this number a number of ways:

123 (decimal) OR

(100 * 1) + (10 * 2) + (1 * 3) OR

(10^2 * 1) + (10^1 * 2) + (10^0 * 3) OR

(64 * 1) + (32 * 1) + (16 * 1) + (8 * 1) * (4 * 0) + (2 * 1) + (1 * 1) OR

(2^6 * 1) + (2^5 * 1) + (2^4 * 1) + (2^3 * 1) * (2^2 * 0) + (2^1 * 1) + (2^0 * 1) OR

1111011 (binary)


If the above binary number is extended to represent a 32-bit int,it would look like:

00000000000000000000000001111011

with the leftmost bit being bit 31 and the rightmost bit being bit 0.

This allows us to see the above as a series of 32 switches or Boolean (True/False) flags that can be accessed (counting from 0 and from the right) by taking a bitwise AND of the number and the "on" value.

As you can see from the above representation, the fourth bit from the right is in the 2^3 position. So, if we take the bitwise AND of our value with 2^3 (8), we get the following:

= 123 & 8
= 8

Since the result (8) is the same as the flag (8), the integer (123) does contain the flag!


When adding flags into your integer, you instead use the bitwise OR. This is always used to switch flags on, so if the flag already exists in your number - it will have no effect, as shown in the following examples:

= 123 | 8
= 123


= 123 | 4
= 127


Finally, to remove a class you take the bitwise AND of the bitwise NOT of the value you're trying to remove. The bitwise NOT inverts the value, so the AND masks any other bits that are currently set, like:

= 127 & (~4)
= 123



The example I usually like to use is to build out the character classes in an RPG-like setting.

Simple C-style Example:


/* CC_ is for Character Class */

int CC_DWARF = 1;
int CC_FIGHTER = 2;
int CC_NINJA = 4;
int CC_SAMURAI = 8;
int CC_ELF = 16;
int CC_MAGICIAN = 32;
int CC_PALADIN = 64;
int CC_HOBBIT = 128;
int CC_PRIEST = 256;
int CC_DARKLORD = 1073741824;


int character_dwarf_fighter = CC_DWARF | CC_FIGHTER;
//value is 3


int character_samurai_elf = CC_SAMURAI | CC_ELF;
//value is 24


int super_crazy_bad_guy = CC_FIGHTER | CC_NINJA | CC_SAMURAI | CC_MAGICIAN | CC_DARKLORD;
//value is 1073741870



//let's remove the CC_DARKLORD class

int super_crazy_bad_guy2 = super_crazy_bad_guy;
super_crazy_bad_guy2 &= ~(CC_DARKLORD);
//value of super_crazy_bad_guy2 is now 46
//OR CC_FIGHTER | CC_NINJA | CC_SAMURAI | CC_MAGICIAN


//let's check super_crazy_bad_guy2 for CC_DARKLORD

if ((super_crazy_bad_guy2 & CC_DARKLORD) == CC_DARKLORD)
   Response.Write("This guy is nothing now!");
//this will print...



//let's check super_crazy_bad_guy2 for CC_DARKLORD

if ((super_crazy_bad_guy2 & CC_PRIEST) == CC_PRIEST)
   Response.Write("This guy is holier than I am!");
//this will NOT print...




Simple .NET/C#-style Example:


[Flags]
public enum CharacterClasses : int
{
   Dwarf = 1,
   Fighter = 2,
   Ninja = 4,
   Samurai = 8,
   Elf = 16,
   Magician = 32,
   Paladin = 64,
   Hobbit = 128,
   Priest = 256,
   DarkLord = 1073741824
};



CharacterClasses super_crazy_bad_guy = CharacterClasses.Fighter | CharacterClasses.Ninja | CharacterClasses.Samurai | CharacterClasses.Magician | CharacterClasses.DarkLord;
Response.Write(super_crazy_bad_guy.ToString());
//prints Fighter, Ninja, Samurai, Magician, DarkLord


super_crazy_bad_guy -= CharacterClasses.DarkLord;
Response.Write(super_crazy_bad_guy.ToString());
//prints Fighter, Ninja, Samurai, Magician


super_crazy_bad_guy |= CharacterClasses.Elf;
Response.Write(super_crazy_bad_guy.ToString());
//prints Fighter, Ninja, Samurai, Elf, Magician


if ((super_crazy_bad_guy &= CharacterClasses.Elf) != 0)
   Response.Write("An elf!");
   
//this will print



if ((super_crazy_bad_guy &= CharacterClasses.Paladin) != 0)
   Response.Write("A paladin!");
   
//this will NOT print





.NET Quickies

* What is the root class that all other .NET classes are derived from?
System.Object

* Name as many ways as you can think of to find a certain character in a string?
String.Contains, "Character Crawl" using any of (for/foreach, String.Chars, String.CharAt, String[], bit masking, plus many others), String.IndexOf, String.LastIndexOf, etc.

* What is a GUID?
Global Unique IDentifier - A 128-bit value that is statistically impossible to be duplicated in a closed environment. (Bonus points if you throw in a note about using it in a multi-server environment by setting the machinekey, generating on the SQL server, using a Key server, etc.)


More to come! Also, if anyone has any suggestions for questions that I should add into my interview process, please send me them!





page 1 of 1
1 




Tags

csharp Introduction parsing Adam Visual Basic SQL Server 2000 AdSense Google AdSense hack technology functional programming testing OOP books anime job tools AnimeConPics Generics lazy initialization enhancements RegEx new site MySql c sharp PHP Linux Microsoft IIS script generation math help debug interview Immutable String programming languages Win32 API SQL JSP c Stopwatch SQL Server 2005 Erlang ASP module software VB bitwise programming interface