Pages

Wednesday, November 19, 2008

Select Statement

What do we use SQL commands for? A common use is to select data from the tables located in a database. Immediately, we see two keywords: we need to SELECT information FROM a table. (Note that a table is a container that resides in the database where the data is stored. . Hence we have the most basic SQL structure:
SELECT "column_name" FROM "table_name"
To illustrate the above example, assume that we have the following table:
Table Store_Information

store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
We shall use this table as an example throughout the tutorial (this table will appear in all sections). To select all the stores in this table, we key in,
SELECT store_name FROM Store_Information
Result:
store_name
Los Angeles
San Diego
Los Angeles
Boston
Multiple column names can be selected, as well as multiple table names

SQL Syntax

List of Normal Queries


Select Statement
SELECT "column_name" FROM "table_name"
Distinct
SELECT DISTINCT "column_name"
FROM "table_name"
Where
SELECT "column_name"
FROM "table_name"
WHERE "condition"
And/Or
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
In
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
Between
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
Like
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}
Order By
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]
Count
SELECT COUNT("column_name")
FROM "table_name"
Group By
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Having
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithematic function condition)
Create Table Statement
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
Drop Table Statement
DROP TABLE "table_name"
Truncate Table Statement
TRUNCATE TABLE "table_name"
Insert Into Statement
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)
Update Statement
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}
Delete From Statement
DELETE FROM "table_name"
WHERE {condition}

Thursday, October 16, 2008

UnInstalling MSI

Ordinary UnInstalling MSI anybody can do it from control panel
some times the MSI will not get uninstalled it throws some fatal error exception and we can't remove from add/remove programs. This happens mainly because of two reasons

1)By mistake removing the registry entries of that software from registry
2)Removing the physical files without uninstalling :)

Sol:-

For every .MSI we there will be something called product key registered in the registry

Mycomputer
|
|__hkey_local_machine
|
|__software
|
|__microsoft
|
|__windows
|
|__currentversion
|
|__uninstall


find the registry entries for that particular software check for the key

"MODIFYPATH" copy value it will be something like this





MsiExec.exe /I{265E7147-C7BA-4660-AF4D-1A1531F6E566}

change the it to

MsiExec.exe /x{265E7147-C7BA-4660-AF4D-1A1531F6E566} DISABLEROLLBACK=1

copy paste it in commadprompt

and run it. Uninstaller will start.


Tuesday, October 14, 2008

Basics on File operations

Introduction


I love to do utility programs in .Net. And this is one of them. As I was playing with JSplit (a free file splitter program), I wondered if I could do it in .Net. The framework supports file operations like reading files in bytes and creating them. It is indeed easy to do file operations in .Net Basics on File operations
The namespace System.IO provides classes for file operations. StreamReader is a class which provides methods to read a file in different modes. It allows the user to read file by number of characters, by line, by block and to the end of the file. There is another class FileStream which allows the user to read file by number of bytes. This is what we are going to use.




Getting Started

Lets begin by creating a windows application with a textbox, a numericupdown control, a label and three buttons. Add a openfileDialog control and add some code to extract the filename from the dialog and to put it in the textbox when the browse button is clicked.
if(openFileDialog1.ShowDialog()==DialogResult.OK) { txtFileName.Text=openFileDialog1.FileName;
Now change the Maximum value of the numericupdown control to 1. Change the backcolor of the label to black and forecolor to green (to give a matrix screen effect)

Set the text property of the buttons to "Calculate" and "Split".

Include the namespaces System.IO and System.Text in the Using section.

Calculate Method

In Calculate method we are going to calculate the number of parts the file will be splitted based on the file size and the split size specified by the user.

Double click on the calculate button to go to the Click event. Now initialize the class FileStream by passing the filename from the textbox and specifying file mode and file access parameters.

FileStream FR=new FileStream(txtFileName.Text,FileMode.Open, FileAccess.Read);

The number of parts is caculated by dividing the file size (in bytes) and user selected split size. This is made to display in the label.

int no_of_parts = Int32.Parse(FR.Length.ToString())/intByteSize;
int intmod=Int32.Parse(FR.Length.ToString())%intByteSize;

//Include the remaining bytes
if(intmod > 0)
no_of_parts=no_of_parts+1;


Split Method

In this method we are going to split the file in to user desired size and number of parts. We again use the FileStream class to read the file. But here we are going to read the file by number of bytes required for each part. So after reading a block of bytes required for a part we write it to a file by using FileStream but in the create file mode and write file access.

//Read the file by number of bytes and create part files for(int i=0;i { if(intmod>0 && i==no_of_parts-1) { by=new byte[intmod]; FR.Read(by,0,intmod); } else { by=new byte[intByteSize]; FR.Read(by,0,intByteSize); }

FileStream's WriteByte function is used to write the bytes to a file. Like this number of files are generated for the number of parts calculated. Each file is written with a dynamic name by appending some incrementing number to the file name.

foreach(byte b in by)
{
FW.WriteByte(b);
}


Batch File

The significance of a file splitter is the ability to reunite the file without the actual splitter application. For this, we create a batch file in the split function to reunite the files and create the actual file. This batch file contains statements to combine the part files and generate the actual file.

StringBuilder SB= new StringBuilder(); SB.Append("Copy /b " + tempfilenames + " \"" + filename + "\""); SW.Write(SB.ToString());


We use StringBuilder class to generate the statement for the batch file. The statement includes the command for uniting the files followed by the filenames. This command should be dynamically added to include the filenames. Now we write this statement to a file and save. The content of the batch file should look like the following statement.

Copy /b "test.pdf0" +"test.pdf1" +"test.pdf2" "test.pdf"



Conclusion
While using file operations we should ensure that the file is closed after the read/write process. Thats all folks!
sourcecode

Find and Replace

Find and Replace for multiline text



Many of us would have used "Find and Replace" option available in our IDE and in many of the text editors. This functionality finds a single line of text given and replaces with the given text in the current document as well as in the files under a given folder. But how would you find and replace a multiline text? In this article I have tried to explain that.


The project included in this article has a simple file reading operation. For the beginners first let me explain how to read files. You can skip this section if you are familiar with file operations.

File Operations

The first step is to include the System.IO namespace in the using directive.

using System.IO;

System.IO namespace has DirectoryInfo class which is used for typical operations such as copying, moving, renaming, creating, deleting and enumerating through directories and sub-directories. Files under a specific directory can be found using this class.

The following statement instantiates DirectoryInfo class with a folder path from the text box.

DirectoryInfo DI= new DirectoryInfo(txtFolder.Text);

To get the file information we use the following statement.

foreach(FileInfo FI in DI.GetFiles())

The GetFiles method of the DirectoryInfo class, returns an array of FileInfo object. The FileInfo class like DirectoryInfo has operations for reading, copying, moving, renaming, creating and deleting files.

Now we use a StreamReader object to read the file.

StreamReader SR= new StreamReader(FI.OpenRead());

We use the following statement to read a line and assign it to a string variable.

s=SR.ReadLine();

Search Operation

We read each line and store it in a temporary variable appending a new line character ("\r\n") at the end of the line.
This will differentiate each line for searching multiline text.

temp=temp+s+"\r\n";

Now to search the string we use IndexOf() method in the temporary variable with the search text as parameter.

pos=temp.IndexOf(txtFind.Text);

The above statement returns the position of the search text.
We use a list box to record the number of files that matches the search text and the occurence of the first position.

Replace Operation

For the replace functionality, we use Replace() method in the temporary variable with search string and string to replace as arguments.
temp=temp.Replace(txtFind.Text,txtReplace.Text);

To reflect this change in the actual file, we need to write it to the file. So we use StreamWriter object to write to the file.

StreamWriter SW= new StreamWriter(FI.OpenWrite());
SW.Write(temp);
SW.Close();
The source code for the project can be downloaded here.
For further reading and source code download

Monday, October 13, 2008

Cryptographically Random Password Generator

Introduction

Creating a password is easy. However, creating a strong password is not easy. Most passwords are simple variations of dictionary words, often with random numbers at the end of them or are simple substitutions (1s for I's, the "@" symbol for A's, and so forth). The problem with this scheme is that it is easily guessable by sophisticated password-guessing software. Such software, such as that by Access Data, can crack open passwords that follow such simplistic patterns, even if those passwords include multiple intentionally misspelled words, random numbers, and other common patterns.
The Problem

The problem with passwords is that they are not random. They're based on predictable patterns. They're easy to remember and, consequently, easy to crack. Some passwords need not be complex. The complexity of the password should be commensurate with a) the possible attack vectors, and b) the value of the data or resource protected by that password. For example, ATM pins are 4-digit. But they're reasonably secure because they're not subject to brute force attacks.

So, when do you need to use non-trivial, random passwords? It's important to use such passwords when employing the use of encryption on data that can potentially be analyzed and where a brute force attack can be waged on the password protecting that data. AES-256 is meaningless if the password can be cracked in ten minutes.
The Solution

Use a cryptographically random password in cases where security is essential. The Cryptographically Random Password Generator provides such a service. How does it work? The first step is to get a cryptographically random 32-bit integer. There's a Random class provided by Microsoft in the System namespace (that you'll use), but the level of entropy (randomness) is minimal if you rely only on that class. Instead, you'll use the RNGCryptoServiceProvider namespace, provided in System.Security.Cryptography:

byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
Int32 randomInt=BitConverter.ToInt32(randomBytes, 0);
return randomInt;

Good; you now have a 32-bit integer that is totally random. You safely can use this cryptographically random integer as a seed in the Random class. In fact, you'll generate a new random seed per iteration (per password character). Why? Because if you use the random value as the initial seed, the password entropy is still not cryptographically random. You've generated a random seed, but given that seed, the Random class's generated values are still pretty predictable. Hence, you generate a new seed every time you need a character, and Random uses that random seed.

So, why do you need Random if you have the RNGCryptoServiceProvider class? The answer is that you'll need to map a randomly generated value to an array. The array will hold a character set—a list of allowable characters in our password. By default, that list will include the letters a-z, A-Z, and also 0-9 and some special characters (ten of them). Hence, the list includes a total of 72 distinct characters. The main iteration loop that populates the final password string looks something like this:

for (int i = 0; i < len; i++)
{
// Get our cryptographically random 32-bit integer & use it
// as a seed in the Random class
// NOTE: The random value is generated PER ITERATION, meaning
// that the System.Random class is re-instantiated every
// iteration with a new, cryptographically random numeric seed.
int randInt32 = RandomInt32Value.GetRandomInt();
Random r = new Random(randInt32);

int nextInt=r.Next(possibleChars.Length);
char c = possibleChars[nextInt];
builder.Append(c);
}

The static method call to RandomInt32Value accomplishes the task of getting the random 32-bit integer because that class encapsulates the necessary calls to the RNGCryptoServiceProvider class. For utility's sake, the application provided includes the ability to set the password length and the set of possible characters, as in the screen shot below:

Finally, note that the application provides the capability of viewing the statistical frequency distribution of the generated password. Why would you need this? For testing sake, you could generate a 10,000 character password using the available characters (or, for simplicity, just certain characters, like 0-9). Theory suggests that, roughly speaking, the generated characters will have an equal chance of being selected in the final passphrase. For example, I generated a 10,000 character passphrase using the characters 0 through 9. The values selected were roughly equal in frequency (a good sign of randomness, meaning that the randomness algorithm does not show statistical favoritism).

Conclusion

Data that is meant to be secure and that relies on user-generated passwords to secure the data are at risk. You can use a secure password generation mechanism, like the Cryptographically Random Password Generator, to generate random passwords using a variable character set and a length of your choosing. Write your password down and put it in a secure location. Rest assured that if the medium that contains your data is lost, your data will nonetheless be secure because the encryption key will be impossible to break with today's technology (or even tomorrow's?).

Comments and feedback on this article and the application are welcome. If you have suggestions, please don't hesitate to let me know at your leisure.

About the Author

I am a software engineer based in Raleigh, NC. I have experience in C, C++, Java, C#, and other languages.

I am married and have a beautiful wife named Amanda. Absent of kids, we have three house cats.

In my spare time, I also write a blog on political topics and current events (www.gmgdesign.com/go).

Downloads

# RandPasswordGen_demo.zip - Executable
# RandPasswordGen_src.zip - Source code

Learn the ASP.NET Page Life Cycle

So you want to fully understand what is going behind the scenes when a ASP.NET page loads do you? In general, the life cycle of a ASP.NET page comprises of a series of steps like initialization, instantiation of controls, state management, the firing of event handler code, and the final stage of rendering.

Why learn the various stages of an ASP.NET page? Well if you are a control developer, you have to know the various stages of a page so you can code for the appropriate stage of a page. For example, if you want to perform validation checks on your custom control, you won’t get the desired results if you try and perform validation during the rendering stage!

If you are coming from a ASP.NET 1.1 background, be sure to note that ASP.NET 2.0’s page life cycle has been modified by giving you a finer control of the various stages.

The following are the various stages a page goes through:
Page Request

The request page is either parsed or compiled, or fetched from the cache.
Start

Page properties like the Request and Response are set. The type of request is determined, specifically whether it is a new Request or it is a PostBack. Culturing properties are also determined via the pages ICulture property.
Page Initialization

All the controls on the given page are initialized with a UniqueID (please don’t confused this with the ID property as the UnqiueID is a unique, hierarchicial identifier which includes the server control’s naming container). Theming is also applied at this stage.
Load

If the current request is a PostBack, the data from the viewstate and control state is loaded to the appropriate properties of the controls.
Validation

The Validate method of all the validator controls are fired, which in turn sets the Boolean property IsValid of the controls.
Postback Event Handling

If the current request is a PostBack, all event handlers are called.
Rendering

ViewState data is saved for all the controls that have enabled viewstate. The Render method for all the controls is fired which writes its output to the OutputStream via a text writer.
Unload

Once the page has been rendered and sent, the Page’s properties are unloaded (cleanup time).

So know you have a better understanding of the various stages of a ASP.NET pages life cycle, you should be aware that within each of the above stages there are events that you can hook into so that your code is fired at the exact time that you want it to.

Event Wire-up is another important concept to understand. So Event wire-up is where ASP.NET looks for methods that match a naming convention (e.g. Page_Load, Page_Init, etc) , and these methods are automatically fired at the appropriate event. There is a page level attribute AutoEventWireup that can be set to either true or false to enable this behaviour.

Below are some of the more popular events that you should understand as you will most likely be interested in them:
PreInit
# You can use this event to: Create /recreate dynamic controls
# Set a master page or theme dynamically
# Access profile properties
Init

Used to read or initialize your control properties.
InitComplete

Used when you need to access your properties after they have been initialized.
PreLoad

Used when you need to process things before the Load event has been fired.
Load

The Page’s OnLoad method and all of its child control’s OnLoad method are fired recursively. This event is used to set properties and make database connections
Control Events

Control specific events are handled at this stage. e.g. Click event’s for the button control.
LoadComplete

This stage is for when you need to access controls that have been properly loaded.
PreRender

Can be used to make any ‘last chance’ changes to the controls before they are rendered.
SaveStateComplete

This event is used for things that require view state to be saved, yet not making any changes to the controls themselves.
Render

The page object calls this method on all of the controls, so all the controls are written and sent to the browser.
Unload

All the controls UnLoad method are fired, followed by the pages UnLoad event (bottom-up). This stage is used for closing database connections, closing open files, etc.

It is import to understand that each server control has its very own life cycle, but they are fired recursively so things may not occur at the time you think they do (they occur in reverse order!). What this means is that some events fire from the bottom up like the Init event, while others load from the top-down like the Load event.
Summary

So we learned about the various stages of an ASP.NET page, and I also covered some popular events that you might want to override or program for in your applications. If you don’t understand what is happening at the correct stage, you will either throw an exception since you are trying to access something that is not available at this stage, or you will go through long bouts of debugging trying to figure out why are program is not behaving the way you expect it to.

C# Coding Techniques

The concepts of "What's C# code?" and "How we can write code?". To read this article you must have an overview of the .NET Framework and Visual Studio.NET (VS. NET) if possible.

Introduction

Before we discuss any of C# basics concepts you must understand what a computer program is?

A computer program is not that black box that you can't understand; when we go further in the book you will understand the whole story. Computer program is a series of lines of code that actually do 2 things.

1- Store data (in many different ways as we will learn later)
2- Manipulate this data ( in many different ways too)

For example, Microsoft Word is a complex huge program that manipulates text data, I mean you write a lines of text in the page and you can change the colors, bold the text, copy and paste the text in your documents and many other operations. Another example, Adobe Photoshop is a complex application (program) that works with photos and pictures. Here the photo will be the program's data and the program will manipulate this data using its operation. Actually you can think of this operation as the lines of code that we will write to manipulate this data.

Important Note: In the beginning you may think that programming is difficult and you also think that you don't understand anything. It's ok just wait until you finish the next 4 chapters and you will do fine because you will not grasp all the concepts in the same time.

C# Coding

As you learn another language French for example, you find it difficult in the beginning but when you go further and further you find that you are learning and life is easy. The same with C# writing code in the first will not be that easy but as you go further you will find yourself writing code without even looking for any reference. In this section and the next few you will learn many things about writing and organizing your code.

Keywords

Recall from chapter 1 when we said that every language consists of keywords and these keywords only understandable by the people who talk this language.

The same is here with C#, keywords are special words that have special meaning in the C# language and it's reserved by the language. Actually the last sentence means a lot but I'm afraid that you can't understand it now so I will take about it later.

Figure 2.1 display a table contains all the keywords in C#.

abstract event new struct
as explicit null switch
base extern object this
bool false operator throw
break finally out true
byte fixed override try
case float params typeof
catch for private uint
char foreach protected ulong
checked goto public unchecked
const if readonly unsafe
class implicit ref ushort
continue in return using
decimal int sbyte virtual
default interface sealed volatile
delegate internal short void
do is sizeof while
double lock stackalloc
else long static
enum namespace string


To explain what's a keyword let's go back to our language (English). Now when I write "Hello" actually it's a keyword in the English language and we tell it when we want to greet someone, so each of the keywords in figure 2.1 means something that you and the compiler will understand. So while we go further in the book you will learn more about these keywords and how to use them inside your code to form a program.

One of the VS. NET features is coloring the Keywords to the blue color so you can easily identify the keywords in C# code.

Identifiers

Identifiers are just names for your items; I mean for example, you are developing a program that contains an item which will add 2 numbers so you must give this item a number in your code so that name called identifier because it will identify your items.

I will give you many examples for identifiers later when appropriate. Now we must differentiate between Keywords and Identifiers. Keywords are special words reserved by the language and Identifiers are just names which you can use to call your items (I use the word 'items' because I suppose you don't know anything of C# building blocks like struct, class, method and like that) . So for example I can call my programming item "Michael" which is an item that can write to the screen "Hello I like programming in C#" so "Michael" here is an Identifier. I can't call this item "class", "int" or any of the words in Figure 2.1 because it's reserved by C# for special use.

When you name your items you must apply certain rules:

1. The first character in the name must start with a letter (uppercase or lowercase) or an underscore character "_" like the name "_myName".
2. The characters after the first one can be a digit, an underscore character, or a letter (uppercase or lowercase).

That's all what you need to know now about Keywords and Identifiers now.

C# Statements

Actually C# statement is the same as the English language complete sentence. This is the best and simplest analogy that illustrates what's a statement. Look at the following example:

I like Microsoft Products.

Anyone will read this sentence will understand that I like Microsoft Products but when I say:
I like

What? What do you like? This is what you may ask because it's not a complete sentence.

The same thing with C# statement, its form a complete instruction that C# compiler can understand so the next statement adds 2 numbers and stores it in the memory.

memory = 2 + 5;

Note that C# statements end with the semicolon ";"as the English sentence end with the full stop "." So you must put a semicolon as the end of each C# statement. In this last C# statement we told the compiler to put the result of adding these 2 numbers in the memory. Don't care about understanding the code right now because we have all the next chapters discussing C# coding.

You must know that C# programs consist of sequence of C# statements that execute in ascending order like the following example:

{
statement 1
statement 2
statement 3
}

The first statement (statement 1) will execute first then 2 and the end up with the last one (statement 3).

C# Building-Blocks

Whenever you write C# statement this statement will be part of a block called "Block of code" and actually it's much the same as paragraphs in English language which consists of a number of statements.

So they call it block because it's consists of related C# statements that will do the job that it's created for. C# Blocks may contain zero, one or many statements, these blocks must be delimited with curly brackets "{ }" like the following example:

{
int memory = 2 + 5;
Console.WriteLine(memory);
Console.WriteLine("so it's 7, right?");
}

This is a block of code that contains 3 statements, there are a number of important points that you must understand here:

1- int is a keyword and VS. NET colored it to the blue color so you can differentiate it.
2- There is a semicolon to end each of the 3 statements.
3- Each line contains only one statement.

You can have 2 statements in the same line and that's because C# compiler know that you end the statement with the ";". So you can write the last building block as following:

{
int memory =2 + 5;Console.WriteLine(memory);
Console.WriteLine("so it's 7,right?");
}

But by convention you have to write only one statement in the line so your code will appear in a better appearance and improve readability.

You can nest the blocks, I mean you can write one block inside the other look at the following block:

{
int memory = 2 + 5;
if(memory == 7)
{
Console.WriteLine("hi, I'm Michael");
}
}

Again don't look at the code and look at the blocks only, here we have 2 nested blocks of code. Just for now enough that you know that we can create blocks inside other blocks and later we will now how can that be useful.

Something important to note: When you write the left curly bracket "{" and write your code, then closing it with the right curly bracket "}" you will note that VS.NET will bold the whole block for a second and actually it's nothing more than a way to show you the contents of that block.

There are 3 more sections that will discuss code organization.

Commenting your code

While you are writing C# code you can write comments. A comment is just a text that you can write to explain or describe your code. For example, you have some block of code that add 2 numbers so you can use comments to describe the operation of this block of code like the following:

{
// This block of code will add 2 numbers and then put
// the result in the memory
int memory = 2 + 5;
}

Another feature of VS. NET is coloring the comments to green color text. You must know that you can write your comments using any language (English, French, or any other language) because C# compiler will ignore the comments. You can think of comments as something can live with C# code. In more complex blocks of code you will find that comments are very useful especially if you are reading other programmers code so their comments will help you understand many things.

There are 2 ways to write comments in C#. The first way is using the multi-line comments and the second way is using the single-line comments.

The multi-line comments begin with the characters "/*" and end with the characters "*/" as following:

/* this block of code will add 2 numbers
* and then put the result in the memory */

There are a few things that we must discuss here. This is a multi-line comment so you can press the Enter key after the opening characters "/*" and each time you press the enter key (for a new line) you will get a "*" character in the beginning of this new line.

The job of this character just to tell you that you have a new line in your comments, You can delete this character and complete writing your comments and when you finish you must close it with "*/" characters. When you close your multi-line comments VS. NET will bold all the text contained in your comments just to let you see how many lines and what's exactly the text that you wrote in your comments.

Important Note: In the multi-line comments you can write anything except the closing character "*/" because VS. NET will think that you want to close the comments.

So you can't write the following:

/* the only special character that you can't write
* Inside the multi-line comments is the "*/" character */

Here we wrote the closing characters as part of our multi-line comment so note that after the closing characters in the second line "*/" the text color is black and that's means it's anything but not a comment.

The single-line comments begin with the characters "//" and you can write your comments only at this line as the following:

// This block of code will add 2 numbers and then put
int memory = 2 + 5;

If you want to write more than one line in your comment then you must begin each line with "//" characters as following:

// This block of code will add 2 numbers and then put
// the result in the memory
int memory = 2 + 5;

You can write the single-line comment in the same line with your statement as the following:

int memory = 2 + 5; // this is a statement


There is a third way to comment your code but I prefer to not discuss it now. But you must know about it only. This kind of comments which you will find it In many kind of C# projects created by VS. NET begin by "///" characters:

///
/// The main entry point for the application.
///

You will find this kind of comments in C# projects created by VS. NET and it helps you to document your application.

Documentation is a help system developers create it so the application's users can learn how to use the application. So later we will give you overview of how to create documentation for your application using this kind of comment.

Some developers said that this is not a comment because you don't comment your code but you describe it. Anyway we will talk about it later.

Case-sensitivity and syntax errors

As we said before that C# is a case sensitive programming language, what that means? Let's see
In C# if you named an item "Michael" (with a capital "M") then it's not the same as "michael" and the C# compiler will not understand that Michael = michael and it will consider that they are 2 different items. So take care when giving names in your code.

In the program that write a line to the console.

using System;
namespace ConsoleApplication2
{
///
/// Summary description for Class1.
///
class Class1
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Hello, I'm Michael");
}
}
}

I think now you know more about this code, you know that the blue words are keywords and the green lines are comments but let's talk about case-sensitive here.

All the keywords are made up of small letters and if you try to delete it and type it with any capital letter then the word color will not be blue and when you compile your program you will get an error. Later you will learn what's the things that you will write it in capital letters and what's the things that you must write it in small letters (by now, you know that keywords must be written in small letters).

I said that if you type "michael" instead of "Michael" (the item named with a capital "M") then the compiler will generate an error. This error called a syntax error.

In English language if you typed "noote" instead of "note" then it's a spelling error so you can understand the syntax error as the same as the English spelling error which will make the reader confused and stop reading. With C# the compiler will generate an error telling you about it (the error message will depend on the situation).

Syntax error is not just typing "michael" instead of "Michael" but it's a violation for the programming language coding rule, I mean that syntax errors is more than just a case sensitive for example, the next example is a syntax error:

{
Console.WriteLine("Hello");

We said before that C# blocks must delimited by "{" and "}" and here in this example we didn't close this block so it's a syntax error.

To avoid opening and closing problem of the blocks you can do the next:

1. If you want to create a block of code then type the opening and closing curly brackets in the same line like the following

{ }

2. Then press the enter key 2 times so you will have something like the following

{
}

3. Now you can write your code without worrying about the opening and closing curly brackets.

Another example for the syntax errors:
{
Console.WriteLine("Hello")
}

In this example I didn't forget to close the block but I forget to put the semicolon at the end of the statement so it's also a syntax error and VS.NET will put a jagged line under the place of the syntax error (but sometimes I find that this jagged line confused because it may be in the next line of the error).

And there are many things that can make syntax errors occur but don't worry because we will learn about them. I explained syntax error here and before you learn more about C# for a couple of reason: the first reason is that the most common syntax error come from case-sensitive situation and the second because I want you to minimize your syntax error and focus on learning the language.

You must know that your program will not compile and executed until you fix all the syntax errors in the program. Actually VS. NET will help you tracking your syntax errors by providing an error message describing the error and also the jagged line that VS. NET will put under that line where the syntax error happened. Syntax errors also called compile-time error or compilation errors.

Next we will learn how we can organize our code as VS. NET does to improve readability.

Organizing code using Whitespace

To begin this section let's look at the following examples of a block of code
{
int x = 2 + 5 ; int y = x + 5;
Console.WriteLine(x); Console.WriteLine(y);
}

Now look at this one:
{
int x = 2 + 5;
int y = x + 5;
Console.WriteLine(x);
Console.WriteLine(y);
}

Both of these blocks will run and we will get the same result but the only difference between them is the Whitespaces inside our code.

Whitespaces are any white space inside your code like (space characters, tab characters, and carriage return characters (which is pressing the Enter key)). Programmers use Whitespace to make their code more readable and organized. In the 2 blocks above I used Whitespaces to write them but let's see the first one again:

{
int x = 2 + 5 ; int y = x + 5;
Console.WriteLine(x); Console.WriteLine(y);
}

Here there are many space characters between "2", "+" and '5". Also I wrote 2 statements in the second line.

Now let's look at the second block again:

{
int x = 2 + 5;
int y = x + 5;
Console.WriteLine(x);
Console.WriteLine(y);
}

It's organized block of code which contains 4 statements and there are 4 lines for them too. So use Whitespaces to organize your code and it make it more readable for you and for other developers.

We said that Whitespaces are (space, tab, carriage return characters) so if you look at the second (or the first) block of code you will find all of them. We used the tab character after the opening curly bracket "{"of the block to indent the body of the block then we used the enter key (carriage return) to move to the next line after writing the first statement and we used the space characters between the operators (=, +) and numbers (2, 5) to make our code look good.

As we said before that C# compiler ignores comments also C# compiler ignores Whitespaces and that's why both of blocks will run and get the same result so you can write the next block in 2 ways:

{int x = 2 + 5;}

Or you can write it as following:

{
int x = 2 + 5;
}

By convention, indent your block's body 1 tab character and take 1 space character between operators like (=, +, -, *) and numbers and take 1 carriage return character between statements.

VS. NET will help you indenting your blocks and if you want to see this do the next:

1. create a console application project and you will get the auto-generated code like this:

using System;
namespace testing
{
///
/// Summary description for Class1.
///
class Class1
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
}
}
}

If you look at this code you will find that it's organized using the Whitespaces we discussed specially the tab character. So to create a block of code put your mouse cursor to the right of the red curly bracket "}" (actually I colored it red to just identify which one and VS. NET will not color it to red) and then press the Enter key to get a new line. Note that when you press Enter you will not get to the beginning of the next line but you will begin under the red curly bracket (I will tell you why later).

2. Write the next line of code

static void Michael()

And then press Enter also note here that VS. NET will not begin at the first of the next line but it will begin under the static keyword.

3. Now type the opening curly bracket "{"and press the enter key. VS. NET will indent the body of the block (1 tab character only) when you press the enter key to move to the next line and your mouse cursor will be positioned in place of the red l letter in the following code:

static void Michael()
{
..
..

So as we said VS. NET will help you indent your blocks and that's will save your time trying to organize your blocks. The same thing happens if you have 2 or more nested blocks of code. Look at the following block:

{
int x = 5;
if(x == 5)
{
Console.WriteLine(x);
}
}

This is a block which is contains another block of code. Note that the first statement in the outer block is indented 1 tab and the inner block is indented 1 tab too but the statement inside the inner block indented 1 tab of the inner block and so on.

C# Coding Style Guide

1. About the C# Coding Style Guide

This document may be read as a guide to writing robust and reliable programs. It focuses on programs written in C#, but many of the rules and principles are useful even if you write in another programming language.
2. File Organization
2.1 C# Sourcefiles

Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer. Put every class in a separate file and name the file like the class name (with .cs as extension of course). This convention makes things much easier.
2.2 Directory Layout

Create a directory for every namespace. (For MyProject.TestSuite.TestTier use MyProject/TestSuite/TestTier as the path, do not use the namespace name with dots.) This makes it easier to map namespaces to the directory layout.
3. Indentation
3.1 Wrapping Lines

When an expression will not fit on a single line, break it up according to these general principles:
# Break after a comma.
# Break after an operator.
# Prefer higher-level breaks to lower-level breaks.
# Align the new line with the beginning of the expression at the same level on the previous line

Example of breaking up method calls:
longMethodCall(expr1, expr2,
expr3, expr4, expr5);

Examples of breaking an arithmetic expression:
PREFER:

var = a * b / (c - g + f) +
4 * z;

BAD STYLE – AVOID:

var = a * b / (c - g +
f) + 4 * z;

The first is preferred, since the break occurs outside the paranthesized expression (higher level rule). Note that you indent with tabs to the indentation level and then with spaces to the breaking position in our example this would be:


> var = a * b / (c - g + f) +
> ......4 * z;


Where '>' are tab chars and '.' are spaces. (the spaces after the tab char are the indent with of the tab). A good coding practice is to make the tab and space chars visible in the editor which is used.
3.2 White Spaces

An indentation standard using spaces never was achieved. Some people like 2 spaces, some prefer 4 and others die for 8, or even more spaces. Better use tabs. Tab characters have some advantages:
# Everyone can set their own preferred indentation level
# It is only 1 character and not 2, 4, 8 … therefore it will reduce typing (even with smartindenting you have to set the indentation manually sometimes, or take it back or whatever)
# If you want to increase the indentation (or decrease), mark one block and increase the indent level with Tab with Shift-Tab you decrease the indentation. This is true for almost any texteditor.

Here, we define the Tab as the standard indentation character.
Don't use spaces for indentation - use tabs!
4. Comments
4.1 Block Comments

Block comments should usually be avoided. For descriptions use of the /// comments to give C# standard descriptions is recommended. When you wish to use block comments you should use the following style :


/* Line 1
* Line 2
* Line 3
*/


As this will set off the block visually from code for the (human) reader. Alternatively you might use this oldfashioned C style for single line comments, even though it is not recommended. In case you use this style, a line break should follow the comment, as it is hard to see code preceeded by comments in the same line:


/* blah blah blah */

Block comments may be useful in rare cases, refer to the TechNote 'The fine Art of Commenting' for an example. Generally block comments are useful for comment out large sections of code.
4.2 Single Line Comments

You should use the // comment style to "comment out" code (SharpDevelop has a key for it, Alt+/) . It may be used for commenting sections of code too.

Single line comments must be indented to the indent level when they are used for code documentation. Commented out code should be commented out in the first line to enhance the visibility of commented out code.

A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.
4.3 Documentation Comments

In the .net framework, Microsoft has introduced a documentation generation system based on XML comments. These comments are formally single line C# comments containing XML tags. They follow this pattern for single line comments:


///
/// This class...
///

Multiline XML comments follow this pattern:


///
/// This exception gets thrown as soon as a
/// Bogus flag gets set.
///

All lines must be preceded by three slashes to be accepted as XML comment lines. Tags fall into two categories:
# Documentation items
# Formatting/ Referencing

The first category contains tags like ,
or . These represent items that represent the elements of a program's API which must be documented for the program to be useful to other programmers. These tags usually have attributes such as name or cref as demonstrated in the multiline example above. These attributes are checked by the compiler, so they should be valid. The latter category governs the layout of the documentation, using tags such as , or .
Documentation can then be generated using the 'documentation' item in the #develop 'build' menu. The documentation generated is in HTMLHelp format.
For a fuller explanation of XML comments see the Microsoft .net framework SDK documentation. For information on commenting best practice and further issues related to commenting, see the TechNote 'The fine Art of Commenting'.
5. Declarations
5.1 Number of Declarations per Line

One declaration per line is recommended since it encourages commenting1. In other words,


int level; // indentation level
int size; // size of table

Do not put more than one variable or variables of different types on the same line when declaring them. Example:


int a, b; //What is 'a'? What does 'b' stand for?

The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.
5.2 Initialization
Try to initialize local variables as soon as they are declared. For example:


string name = myObject.Name;

or


int val = time.Hours;

Note: If you initialize a dialog try to use the using statement:


using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
...
}

5.3 Class and Interface Declarations

When coding C# classes and interfaces, the following formatting rules should be followed:
# No space between a method name and the parenthesis " (" starting its parameter list.
# The opening brace "{" appears in the next line after the declaration statement
# The closing brace "}" starts a line by itself indented to match its corresponding opening brace.

For example:


Class MySample : MyClass, IMyInterface
{
int myInt;
public MySample(int myInt)
{
this.myInt = myInt ;
}
void Inc()
{
++myInt;
}
void EmptyMethod()
{
}
}

For a brace placement example look at section 10.1.
6. Statements
6.1 Simple Statements

Each line should contain only one statement.
6.2 Return Statements

A return statement should not use outer most parentheses. Don't use :


return (n * (n + 1) / 2);
use : return n * (n + 1) / 2;

6.3 If, if-else, if else-if else Statements

if, if-else and if else-if else statements should look like this:


if (condition) {
DoSomething();
...
}
if (condition) {
DoSomething();
...
} else {
DoSomethingOther();
...
}
if (condition) {
DoSomething();
...
} else if (condition) {
DoSomethingOther();
...
} else {
DoSomethingOtherAgain();
...
}

6.4 For / Foreach Statements
A for statement shoud have following form :


for (int i = 0; i < 5; ++i) {
...
}

or single lined (consider using a while statement instead) :


for (initialization; condition; update) ;
A foreach should look like :
foreach (int i in IntList) {
...
}

Note: Generally use brackets even if there is only one statement in the loop.
6.5 While/do-while Statements
A while statement should be written as follows:


while (condition) {
...
}

An empty while should have the following form:


while (condition) ;

A do-while statement should have the following form:


do {
...
} while (condition);

6.6 Switch Statements
A switch statement should be of following form:


switch (condition) {
case A:
...
break;
case B:
...
break;
default:
...
break;
}

6.7 Try-catch Statements

A try-catch statement should follow this form:


try {
...
} catch (Exception) {}
or
try {
...
} catch (Exception e) {
...
}
or
try {
...
} catch (Exception e) {
...
} finally {
...
}

7. White Space
7.1 Blank Lines

Blank lines improve readability. They set off blocks of code which are in themselves logically related. Two blank lines should always be used between:
# Logical sections of a source file
# Class and interface definitions (try one class/interface per file to prevent this case) One blank line should always be used between:
# Methods
# Properties
# Local variables in a method and its first statement
# Logical sections inside a method to improve readability Note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier.
7.2 Inter-term spacing
There should be a single space after a comma or a semicolon, for example:


TestMethod(a, b, c); don't use : TestMethod(a,b,c)

or


TestMethod( a, b, c );
Single spaces surround operators (except unary operators like increment or logical not), example:
a = b; // don't use a=b;
for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i)
// or
// for(int i=0;i<10;++i)

7.3 Table like formatting

A logical block of lines should be formatted as a table:


string name = "Mr. Ed";
int myValue = 5;
Test aTest = Test.TestYou;

Use spaces for the table like formatting and not tabs because the table formatting may look strange in special tab intent levels.
8. Naming Conventions
8.1 Capitalization Styles
8.1.1 Pascal Casing

This convention capitalizes the first character of each word (as in TestCounter).
8.1.2 Camel Casing

This convention capitalizes the first character of each word except the first one. E.g. testCounter.
8.1.3 Upper case

Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal Casing instead. For Example:


public class Math
{
public const PI = ...
public const E = ...
public const feigenBaumNumber = ...
}

8.2. Naming Guidelines

Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice.

Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early Windows programming, but now is obsolete or at least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.

And remember: a good variable name describes the semantic not the type.

An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button should be postfixed with their type name without abbreviations. For example:


System.Windows.Forms.Button cancelButton;
System.Windows.Forms.TextBox nameTextBox;

8.2.1 Class Naming Guidelines
# Class names must be nouns or noun phrases.
# UsePascal Casing see 8.1.1
# Do not use any class prefix
8.2.2 Interface Naming Guidelines
# Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
# Use Pascal Casing (see 8.1.1)
# Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)
8.2.3 Enum Naming Guidelines
# Use Pascal Casing for enum value names and enum type names
# Don’t prefix (or suffix) a enum type or enum values
# Use singular names for enums
# Use plural name for bit fields.
8.2.4 ReadOnly and Const Field Names
# Name static fields with nouns, noun phrases or abbreviations for nouns
# Use Pascal Casing (see 8.1.1)
8.2.5 Parameter/non const field Names
# Do use descriptive names, which should be enough to determine the variable meaning and it’s type. But prefer a name that’s based on the parameter’s meaning.
# Use Camel Casing (see 8.1.2)
8.2.6 Variable Names
# Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops. (see 10.2 for an example on more intelligent naming for global counters etc.)
# Use Camel Casing (see 8.1.2)
8.2.7 Method Names
# Name methods with verbs or verb phrases.
# Use Pascal Casing (see 8.1.2)
8.2.8 Property Names
# Name properties using nouns or noun phrases
# Use Pascal Casing (see 8.1.2)
# Consider naming a property with the same name as it’s type
8.2.9 Event Names
# Name event handlers with the EventHandler suffix.
# Use two parameters named sender and e
# Use Pascal Casing (see 8.1.1)
# Name event argument classes with the EventArgs suffix.
# Name event names that have a concept of pre and post using the present and past tense.
# Consider naming events using a verb.
8.2.10 Capitalization summary
Type Case Notes
Class / Struct Pascal Casing
Interface Pascal Casing Starts with I
Enum values Pascal Casing
Enum type Pascal Casing
Events Pascal Casing
Exception class Pascal Casing End with Exception
public Fields Pascal Casing
Methods Pascal Casing
Namespace Pascal Casing
Property Pascal Casing
Protected/private Fields Camel Casing
Parameters Camel Casing
9. Programming Practices
9.1 Visibility

Do not make any instance or class variable public, make them private. For private members prefer not using “private” as modifier just do write nothing. Private is the default case and every C# programmer should be aware of it.

Use properties instead. You may use public static fields (or const) as an exception to this rule, but it should not be the rule.
9.2 No 'magic' Numbers

Don’t use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded into your code in 50 lines scattered troughout your 25000 LOC) is error-prone and unproductive. Instead declare a const variable which contains the number :


public class MyMath
{
public const double PI = 3.14159...
}

10. Code Examples
10.1 Brace placement example


namespace ShowMeTheBracket
{
public enum Test {
TestMe,
TestYou
}
public class TestMeClass
{
Test test;
public Test Test {
get {
return test;
}
set {
test = value;
}
}
void DoSomething()
{
if (test == Test.TestMe) {
//...stuff gets done
} else {
//...other stuff gets done
}
}
}
}

Brackets should begin on a new line only after:
# Namespace declarations (note that this isnew in version 0.3 and was different in 0.2)
# Class/ Interface / Struct declarations
# Method Declarations
10.2 Variable naming example
instead of :


for (int i = 1; i < num; ++i) {
meetsCriteria[i] = true;
}
for (int i = 2; i < num / 2; ++i) {
int j = i + i;
while (j <= num) {
meetsCriteria[j] = false;
j += i;
}
}
for (int i = 0; i < num; ++i) {
if (meetsCriteria[i]) {
Console.WriteLine(i + " meets criteria");
}
}
try intelligent naming :
for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate)
{
isPrime[primeCandidate] = true;
}
for (int factor = 2; factor < num / 2; ++factor) {
int factorableNumber = factor + factor;
while (factorableNumber <= num) {
isPrime[factorableNumber] = false;
factorableNumber += factor;
}
}
for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate)
{
if (isPrime[primeCandidate]) {
Console.WriteLine(primeCandidate + " is prime.");
}
}

Note: Indexer variables generally should be called i, j, k etc. But in cases like this, it may make sense to reconsider this rule. In general, when the same counters or indexers are reused, give them meaningful names.

Typical DotNet Interviewer Topics

Overview of .Net
Common Language Runtime
New Languages * C#, VB.Net
ASP.Net including Basics of Web services
MyServices * Passport and Alerts
.Net Enterprise Servers
.Net Frame Work Overview of MSIL
Overview of Common Type system
JIT Compiler
.Net Framework Class Library
Assemblies
Namespaces
Attributes
.Net Tools * GACUTIL, ILDASM, SN, etc.,
Visual Studio .Net
IDE Changes from Visual Studion 6.0
Developing Applications using Visual Studio .Net
C# or VB.Net * Language Fundamentals * Delegates, Events and Indexers
Boxing and Unboxing
Collection Classes
Exception Handling
I/O
Threads and Synchronization
ADO.Net & XML
Differences between ADO & ADO.Net Architecture
ADO.Net Objects ( Connection, DataAdapters, DataReaders, DataSets etc.,)
XML Suppport in .Net
Serialization of ADO.Net objects to XML and vice-versa
Windows Forms * Introduction to Windows Forms * Creating Windows Forms/Walkthrough * Available Controls * Databinding with Windows Forms Controls * Event handling in Windows Forms * Menus, Toolsbars, SDI/MDI development * Building and Debugging Windows Forms Applications GDI+ * Introduction to GDI+ * GDI+ Classes
Windows Forms Control Authoring * Custom Control development * Composite Control Development Component Development * Developing Classlibraries * COM Interop Services * Consumption of Components in Clients * Debugging Components Packaging and Deploying Windows Applications
Web Forms Application Development * Differences between ASP & ASP.Net * INtroduction to Web Forms * Using Web Controls * Databinding with Web Controls
Session Management / Cookies Support
Web.Config
Building and Debugging Web Applications
XML Web Services
Introduction to Web Services
VSDISCO/WSDL/SOAP/UDDI
Developing Web Services using ASP.Net and Visual Studio.Net
Consuming Web Services
Building and Debugging Web Services
Web Controls
HTML Server
Controls Web Server Controls
Authorising Custom Controls
Packaging and Deploying ASP.Net applications
Remoting
Attribute Programming
.Net Framework Security Concepts
Serialization
COM+ Services development
Windows Services development
ATL Server and ISAPI Extensions

Creating a Dockable Panel-Controlmanager Using C#, Part 2

Goals of this Article

What you want to achieve in this article is to get a borderless Form to be moved around on the screen by capturing it with the mouse and dragging it around, and to be able to resize the form, the same way as a normal sizeable Form could be sized by dragging its edges.

Note: To understand the design and construction of this DockablePanel Controler, you need to follow the steps in Part one of this article series. So, if you haven't read Part One yet, please first read and download Part 1 of this article series.

This article will teach you how to work with the base class 'Control' to pass Mouse events from controls that are placed on a Form to the Panel's Mouse events in a manner that you will have the Panel's MouseMove event thrown independent if the Form is covered with lots of different controls or there is only one very big control set on the Form, which covers it totally. You will be able to have the MouseMove event thrown wherever and whenever the mouse hovers over the Panel, This will be done without any usage of hooking. The funny trick on this is that, for the user, all this events seems to be the Forms mouse events, because at every time he never sees the original Form the programmer has created at Designtime. Let me give you a short review to fully get the point.

In the first part of this article series, you created the DockableForm. Remember, this Form in reality is created as a borderless Form. The surface you see on the screen is the DockablePanel where all the Controls you had on the Form will be added now with this article.


(Full Size Image)

Figure 1: The DockableForm is fully covered with the DockablePanel control.

If you were to try to move the Form using the Mouse by dragging it around, nothing happens because:

1. A borderless Form has no Titlebar that you can use to move it around.
2.

3. You never will reach the Form with any mouse action because the Form's surface is totally covered by the Panel, and what you see as the Form's Titlebar is actually your GradientPanel class, which is used here to build the Headerbox of your new Control.

To achieve this, you need to implement two operations; you need to get the Panel moving and you need to be able to resize the panel using the mouse by dragging its borders during runtime, just as a normal resizable Form acts.

To move a normal Form around, you move the mouse cursor over the Titlebar, press the left mouse button down, and keep the left mouse button depressed while moving the mouse around. When the left mouse button is released, the Form is no longer captured so you can stop moving the form. All this works only when the mouse is over the title of the Form; in this case, this is represented by the HeaderBox of the DockablePanel.

So, the first thing, obviously, you need to do is to create the MouseUp, MouseDown, and MouseMove delegates for the HeaderBox. To do this, select the DockablePanel; in the Designer View, select the HeaderBox; in the Properties Window choose 'Events', and double-Click on the needed events. This will create the following code (add the #region markings so you keep a neat and tidy code).

#region Delegates
private void HeaderBox_MouseDown(object sender, MouseEventArgs e) {

}

private void HeaderBox_MouseUp(object sender, MouseEventArgs e) {

}

private void HeaderBox_MouseMove(object sender, MouseEventArgs e) {

}
#endregion

Now, you need to add code to these Delegates. To get the global Screen coordinates of your Mouse, you will use the API call ClientToScreen(), so add the necessary namespace on top of the DockablePanel codepage.

using DockingControls.WinAPI;
namespace DockingControls.Forms
{
. . . .

internal sealed partial class DockablePanel : UserControl{
. . . .
// we add to the Private Fields just after
private bool _isMouseDown = false;
// the following needed fields
private WinAPI.POINT _mousePos;
private int _lastX;
private int _lastY;

And in the MouseDown Delegate, you check whether the left Button was pressed when the MouseDown is fired.

private void HeaderBox_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
LeftMouseButtonPressed(e);
}
}

private void LeftMouseButtonPressed(MouseEventArgs e) {
// store the actual mouseposition
_mousePos.x = e.X;
_mousePos.y = e.Y;
// change it to global-Screen Coordinates so we have
// the real position of the mouse instead of
// its position in the header
APICall.ClientToScreen(HeaderBox.Handle, ref _mousePos);
// the internal notification that the mouse is just down
_isMouseDown = true;
// the global position of the DockablePanels Left-Top
// corner is the global Position of the mouse
// reduced by the position in the header, so we get
_lastX = _mousePos.x - e.X;
_lastY = _mousePos.y - e.Y;
}

This way, you get the start position of your DockableForm where it is placed on the screen, upon starting the Form move. The following picture demonstrates the coordinate calculations.


(Full Size Image)

Figure 2: Calculation of Global Screen Coordinates of the Panels Left Top Corner

In the MouseUp Delegate, you simply set the internal notification (_isMouseDown) to false because you have released the button; it is not pressed down any more. At the moment, there is nothing else to do with this delegate.

private void HeaderBox_MouseUp(object sender, MouseEventArgs e){
if (e.Button == MouseButtons.Left){
_isMouseDown = false;
}
}

With the MouseMove delegate, you need to check the value of the internal boolean (_isMouseDown) to determine whether the form should still move or not. If the mousebutton was released, _isMouseDown will be false, meaning you are no longer moving. This is done with the next code segment.

private void HeaderBox_MouseMove(object sender, MouseEventArgs e) {
if (_isMouseDown ){
MouseMoves(e);
}
}

private void MouseMoves(MouseEventArgs e){
WinAPI.POINT mousePos;
// we read the actual mouse position, which will change
// during moving
mousePos.x = (short)e.Location.X;
mousePos.y = (short)e.Location.Y;
// we calculate the global Position again
APICall.ClientToScreen(HeaderBox.Handle, ref mousePos);
// and the moving method itself
Moving(mousePos);
}

With the Moving procedure (which follows next), you need to ensure that you are attaching and detaching the panel to and from the carrier form, depending whether it is moved or docked. Basically, with this method you are using the difference between the previous position and the current position.

private WinAPI.POINT Moving(WinAPI.POINT mousePos){

if (_carrierAttached){
_carrierForm.Left += (mousePos.x - _mousePos.x);
_carrierForm.Top += (mousePos.y - _mousePos.y);
}else{
// if all is working well this only will happen
// in the first moment, when we are remove a docked panel
// from its docking position
this.Left += (mousePos.x - _mousePos.x);
this.Top += (mousePos.y - _mousePos.y);
}
_mousePos.x = mousePos.x;
_mousePos.y = mousePos.y;
return mousePos;
}

If you were to compile and run the project, you would be able to move the panel in the same way as you can move a form—through its Titlebar.

A Note before compiling the project: Remember that, back in Part 1 when you created the buttonstrip, you made them as visible. Now, because they are in the correct place, you should hide them because you want them hidden when the program starts.

Edit CreateAllElements in the DockingManager class, to look like the following, to hide the Buttonstrips when the program starts:

public void CreateAllElements() {
// Buttonstrips to hide the panels
LeftButtonStrip = CreateButtonStrip(DockStyle.Left,false );
RightButtonStrip = CreateButtonStrip(DockStyle.Right,false);
TopButtonStrip = CreateButtonStrip(DockStyle.Top, false);
BottomButtonStrip = CreateButtonStrip(DockStyle.Bottom,false);
}


Downloads
# DockingControlPart2.zip - DockingControls Part1+2 zip File

Creating a Dockable Panel-Controlmanager Using C#, Part 1 From Zero to the first Panel

Creating a Dockable Panel-Controlmanager Using C#, Part 1

Purpose: To make it easy to have panels which can be docked to the left, right, top, and bottom. It should be easy to add this control to the program and easy to understand how it works, so everybody who wants can adapt its features to his needs. The article is addressed to people who have already read and worked with a starter book about C# such as MS Visual C# 2005 Step by Step so maybe 'C# experts' will find it too overdone in explaining different parts.


Before you get started, you first have to discuss what you want to get and then, step by step, go down the road to achieve this goal. I did this because I need such a tool for my own programs and looking around I only saw much too simple things, which didn't fulfil my needs and much too complicated ones, which are a bit overcrowded for my needs and by that too complicated to what I want to get, and too difficult to adapt them to my needs.

The full construction cannot be done in one article, so this will be a serie of articles. It's adressed to everyone who wants to learn different techniques of programming skills using learning by doing. This first chapter will teach you the following: Attaching three different projects to each other. Creating and using different namespaces, designing an ownerdrawn control, Localisation of usercontrols, including localisation of the controls PropertyBrowser and Errormessages, localiced Discription of Items in the Propertybrowser, Hiding base class Properties in the Propertybrowser, Creating and usage of a TypeConverter, implementing of API calls to a C# program.

But now, start to create all the parts you need to have for an easy docking manager and during learning, you will know what you are doing.
General Design: Decisions

The general design was developed based on the idea to create user-defined panels that are all together connected with a new control named "DockingManager" that is needed to control the docking procedure. All these panels should be User controls, that means inherited from the class Control, by inheriting from the Control class, you have lots of possibilities to use existing other controls like a TabControl or a SplitControl for composing our own ideas. On the other side, for the usage of panels in applications, I would normally prefer to have Forms that I could use to add different controls on it.

But, normal Forms can't be used in a way that you can dock them wherever you want them to be docked. So, what you will try to achieve is a Form that is dockable, in all the ways you want them, but still useable as a Form. For getting this achieved, you will create a new type of Form that you will name DockableForm. The Class of this Form is derived of a Form.

Here is a picture to what you will achieve after some hours of work.

Figure 1: Your end result

As a first step, you have to create two Projects: one for building all the needed parts of our DockingManager and the other project to test the new elements on their workability. So at first, create an Project named DockingControlTestApp that is a standard windows application and a second project that you open in the same editor together with the Test-application. This is a Windows User control application. This you can nameDockingControls.

Right-click the DockingControlTestApp and select it as the Start project. Use this application now:

At first, you rename Form1 as MDIForm. Now in the Properties of that Form, you set IsMdiContainer to true.

Your Panels should basically have similar features as the IDE of Visual Studio 2005 used in C# has. So basically, there should be two possibilities where you could place a docking control:

1. Anywhere in the MDI Form
2. Sharing the same docking position with other panels

The following two figures show both these options:

Figure 2: Anywhere in the MDI Form

Figure 3: Sharing (in this case, the Top Position) Docking with another panel

The screenshot was done just when the mouse was on the Docking Button but not docked, so you can see the green Preview window too. It indicates where the window will be docked.

You also should be able to hide all docked windows and use them only when needed. To get this done, you would need tabs where you could re-open hidden windows again only by hovering over the tabs that contain the Caption of the particular Panel.

Figure 4: Tab registers to show hidden Panels again

It also should be possible to resize the Panels for personal needs and it should be possible to store a chosen combination of Panels and to reload them into the same place at the next program's start.
What Is not Part of This Project

The Visual studio IDE, and some of the other Docking managers I have seen, allow you to share the space for a window again and again. For example, you are sharing left docking for two windows and want to have a third window there. Three or more windows on one docking position (such as the Left) are only possible when the panels are drawn into the registerbutton. There, you can have as much as you want and the register itself can be docked on different places, as you see in Figure 1.

This was a short description of what we will get in the end.
Designing the Different Parts of the DockingManager

So, where do you begin? You want to have a control that allows you to position your panels and also hide them. So, you will need to have hidden strips where your Tab Buttons are placed to Show panels again, when they had been hidden.

So, do a simple start and construct these strips as parts of your DockingManager. Because you want to use existing controls for this, you will use MenuStrips here.


(Full Size Image)

Figure 5: MDIForm with four empty toolstrips created by DockingManager

In Figure 5, you can see a menustrip, a toolstrip, and a statusstrip, which are part of the Test Application and built at design time, Also, you notice four empty toolstrips (no buttons on them; they are created dynamically by the docking manager at runtime).

This is your first goal to achieve. You need these toolstrips. Each of them should only be shown when you have docked to a side (left, right, top, or bottom) and the docked panel has just been set to hidden. In this case, the panel is visible only when you hover over the button that represents the docked window. If you set the stick (pin) button of the panel to 'permanent viewable' and no other panel is invisible, this toolstrip and the panelbutton are invisible. But that's later. First, you need to have the docking manager to create these toolstrips.

Keep in mind that there might be existing menus, Toolstrips, and statusstrips already on the screen. To have control over the mechanics of your DockingManager, you now provide your Test application with a menustrip, two Toolstrips, and a statusstrip. The names of them stay as they are: menuStrip1, statusStrip1, toolStrip1, and toolStrip2.

In your DockingControls, you rename the userControl1 to DockingManager.

In this class, which is derived from User Control, you have to add four private fields for the Toolstrips; you will name them Buttonstrips. This should now look like:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Resources;

namespace DockingControls{
public partial class DockingManager : UserControl {
private ToolStrip LeftButtonStrip;
private ToolStrip RightButtonStrip;
private ToolStrip TopButtonStrip;
private ToolStrip BottomButtonStrip;

public DockingManager() {
InitializeComponent();
}
}
}

Note: I have added some of the necessary 'using namespace' declarations. Everybody who wants to follow this project should already know more or less why and when they are needed. I'm adding here all you will need for this control, independent of in which stage of the program you really will need them. For more detailed explanation on namespaces, see MS 'Help or MSDN.

And now, you can create your ButtonStrips itself. First, create the following function in the Dockingmanager to create the toolstrips:

public void CreateAllElements()
{
// For testing reasons we set the visibility to true
// in the DockingManager, it will be false as they are
// not to be seen when created
CreateButtonStrip(DockStyle.Left,true );
CreateButtonStrip(DockStyle.Right,true );
CreateButtonStrip(DockStyle.Top,true );
CreateButtonStrip(DockStyle.Bottom,true);
// here other needed elements will be created too
}

Hm... pretty easy. This reduces the problem on how to create a toolstrip and to place it in the correct position. So, you now only need to define this new Method CreateButtonStrip, which is creating one specific toolstrip. The enumeration DockStyle is the known enumeration used to dock controls in C#. This Method is defined like the following:

private void CreateButtonStrip(DockStyle pos, bool visible)
{
ToolStrip buttonStrip = CreateButtonStrip(pos);
if (buttonStrip != null)
{
buttonStrip.Visible = visible;
}
}

Sometimes, I need the Method without the possibility to hide them, so I decided to have two different methods with the same name, but different properties I did the original method, CreateButtonStrip(Dockstyle pos) (the following code segment), the easy way; this means that I dropped a control to a form, copied the code, and then adapted it to my needs.

private ToolStrip CreateButtonStrip(DockStyle pos )
{
ToolStrip buttonStrip = new ToolStrip();
buttonStrip.AutoSize = false;
buttonStrip.GripStyle = ToolStripGripStyle.Hidden;
if (pos == DockStyle.Left || pos == DockStyle.Right)
{
// we need a vertical toolstrip
buttonStrip.LayoutStyle = ToolStripLayoutStyle.
VerticalStackWithOverflow;
buttonStrip.TextDirection =
ToolStripTextDirection.Vertical90;
buttonStrip.Size = new Size(24, 309);
buttonStrip.Location = new Point(0, 49);
}
else
{
// Top or bottom are horizontal Toolstrips
buttonStrip.LayoutStyle = ToolStripLayoutStyle.
WHorizontalStackWithOverflow;
buttonStrip.TextDirection = ToolStripTextDirection.Horizontal;
buttonStrip.Size = new Size( 309,24);
buttonStrip.Location = new Point(0, 49);
}
buttonStrip.RenderMode = ToolStripRenderMode.ManagerRenderMode;
// lets sign the controls so we can access them easier
switch (pos )
{
case DockStyle.Left:
buttonStrip.Text = "Left";
buttonStrip.Name = "bsLeft";
break;
case DockStyle.Right :
buttonStrip.Text = "Right";
buttonStrip.Name = "bsRight";
break;
case DockStyle.Top :
buttonStrip.Text = "Top";
buttonStrip.Name = "bsTop";
break;
case DockStyle.Bottom :
buttonStrip.Text = "Bottom";
buttonStrip.Name = "bsBottom";
break;
}
if (Parent != null)
{
// now we are docking the control;
buttonStrip.Dock = pos;
Parent.Controls.Add(buttonStrip);
}
return buttonStrip;
}

Now, you will add some buttons to our strips on your testApplication so you will be able to differentiate between the controls added by the user and the toolstrips shown by the DockingManager.

Downloads
# DockingControlsPart1.zip - DockingControlsPart1.zip