Tuesday, February 20, 2007

Unsafe Code in C#

C# .net hides most of memory management, which makes it much easier for the developer. Thanks for the Garbage Collector and the use of references. But to make the language powerful enough in some cases in which we need direct access to the memory, unsafe code was invented.

Commonly while programming in the .net framework we don?t need to use unsafe code, but in some cases there is no way not to, such as the following:

* Real-time applications, we might need to use pointers to enhance performance in such applications.
* External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C.
* Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory.

Unsafe code is mostly about pointers which have the following advantages and disadvantages.

Advantages of Unsafe Code in C#:

* Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
* Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of its functions need pointer parameters. Although this can be done by writing the DLLImport declaration in a way that avoids pointers, but in some cases it?s just much simpler to use pointer.
* Memory Addresses, there is no way to know the memory address of some data without using pointers.

Disadvantages of Unsafe Code in C#:

* Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#.
* Harder to use, you need be more careful and logical while using pointers, miss using pointers might lead to the following:
o Overwrite other variables.
o Stack overflow.
o Access areas of memory that doesn?t contain any data as they do.
o Overwrite some information of the code for the .net runtime, which will surely lead your application to crash.
* Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably.
* Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your security police don?t allow non type-safety code, then the .net framework will refuse to execute your application.

After we knew all the risks that might face us while using pointer and all the advantages those pointers introduces us of performance and flexibility, let us find now how to use them. The keyword unsafe is used while dealing with pointer, the name reflects the risks that you might face while using it. Let?s see where to place it. We can declare a whole class as unsafe:

unsafe class Class1
{
//you can use pointers here!
}

Or only some class members can be declared as unsafe:

class Class1
{
//pointer
unsafe int * ptr;
unsafe void MyMethod()
{
//you can use pointers here
}
}

The same applies to other members such as the constructor and the properties.

To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:

static void Main()
{
//can't use pointers here

unsafe
{
//you can declare and use pointer here

}

//can't use pointers here
}

You can?t declare local pointers in a ?safe? method in the same way we used in declaring global pointers, we have to put them in an unsafe block.

static void Main()
{
unsafe int * ptri; //Wrong
}

If you got too excited and tried to use unsafe then when you compile the code just by using

csc test.cs

You will experience the following error:

error CS0227: Unsafe code may only appear if compiling with /unsafe

For compiling unsafe code use the /unsafe

csc test.cs /unsafe

In VS.net go to the project property page and in ?configuration properties>build? set Allow Unsafe Code Blocks to True.

After we knew how to declare a block as unsafe we should now learn how to declare and use pointers in it.

Declaring pointers

To declare a pointer of any type all what you have to do is to put ?*? after the type name such as

int * ptri;

double * ptrd;

NOTE: If you used to use pointer in C or C++ then be careful that in C# int * ptri, i; ?*? applies to the type itself not the variable so ?i? is a pointer here as well, same as arrays.
void Pointers

If you want to declare a pointer, but you do not wish to specify a type for it, you can declare it as void.

void *ptrVoid;

The main use of this is if you need to call an API function than require void* parameters. Within the C# language, there isn?t a great deal that you can do using void pointers.
Using pointers

Using pointers can be demonstrated in the following example:

static void Main()
{

int var1 = 5;

unsafe
{
int * ptr1, ptr2;
ptr1 = &var1;
ptr2 = ptr1;
*ptr2 = 20;
}

Console.WriteLine(var1);
}

The operator ?&? means ?address of?, ptr1 will hold the address of var1, ptr2 = ptr1 will assign the address of var1, which ptr1 was holding, to ptr2. Using ?*? before the pointer name means ?the content of the address?, so 20 will be written where ptr2 points.

Now var1 value is 20.
sizeof operator

As the name says, sizeof operator will return the number of bytes occupied of the given data type

unsafe
{
Console.WriteLine("sbyte: {0}", sizeof(sbyte));
Console.WriteLine("byte: {0}", sizeof(byte));
Console.WriteLine("short: {0}", sizeof(short));
Console.WriteLine("ushort: {0}", sizeof(ushort));
Console.WriteLine("int: {0}", sizeof(int));
Console.WriteLine("uint: {0}", sizeof(uint));
Console.WriteLine("long: {0}", sizeof(long));
Console.WriteLine("ulong: {0}", sizeof(ulong));
Console.WriteLine("char: {0}", sizeof(char));
Console.WriteLine("float: {0}", sizeof(float));
Console.WriteLine("double: {0}", sizeof(double));
Console.WriteLine("decimal: {0}", sizeof(decimal));
Console.WriteLine("bool: {0}", sizeof(bool));

//did I miss something?!
}

The output will be:

sbyte: 1

byte: 1

short: 2

ushort: 2

int: 4

uint: 4

long: 8

ulong: 8

char: 2

float: 4

double: 8

decimal: 16

bool: 1

Great, we don?t have to remember the size of every data type anymore!
Casting Pointers

A pointer actually stores an integer that represents a memory address, and it?s not surprising to know that you can explicitly convert any pointer to or from any integer type. The following code is totally legal.

int x = 10;
int *px;

px = &x;
uint y = (uint) px;
int *py = (int*) y;

A good reason for casting pointers to integer types is in order to display them. Console.Write() and Console.WriteLine() methods do not have any overloads to take pointers. Casting a pointer to an integer type will solve the problem.

Console.WriteLine(?The Address is: ? + (uint) px);

As I mentioned before, it?s totally legal to cast a pointer to any integer type. But does that really mean that we can use any integer type for casting, what about overflows? On a 32-bit machine we can use uint, long and ulong where an address runs from zero to about 4 billion. And on a 64-bit machine we can only use ulong. Note that casting the pointer to other integer types is very likely to cause and overflow error. The real problem is that checked keyword doesn?t apply to conversions involving pointers. For such conversions, exceptions wont be raised when an overflow occur, even in a checked context. When you are using pointers the .net framework will assume that you know what you?re doing and you?ll be happy with the overflows!

You can explicitly convert between pointers pointing to different types. For example:

byte aByte = 8;
byte *pByte = &aByte;
double *pDouble = (double*) pByte;

This is perfectly legal code, but think twice if you are trying something like that. In the above example, the double value pointed to by pDouble will actually contain a byte (which is 8), combined by an area of memory contained a double, which surely won?t give a meaningful value. However, you might want to convert between types in order to implement a union, or you might want to cast pointers to other types into pointers to sbyte in order to examine individual bytes of memory.
Pointers Arithmetic

It?s possible to use the operators +, -, +=, -=, ++ and -- with pointers, with a long or ulong on the right-hand side of the operator. While it?s not permitted to do any operation on a void pointer.

For example, suppose you have a pointer to an int, and you want to add 1 to it. The compiler will assume that you want to access the following int in the memory, and so will actually increase the value by 4 bytes, the size of int. If the pointer was pointing to a double, adding 1 will increase its value by 8 bytes the size of a double.

The general rule is that adding a number X to a pointer to type T with a value P gives the result P + X *sizeof(T).

Let?s have a look at the following example:

uint u = 3;
byte b = 8;
double d = 12.5;
uint *pU = &u;
byte *pB = &b;
double *pD = &d;

Console.WriteLine("Before Operations");
Console.WriteLine("Value of pU:" + (uint) pU);
Console.WriteLine("Value of pB:" + (uint) pB);
onsole.WriteLine("Value of pD:" + (uint) pD);


pU += 5;
pB -= 3;
pD++;

Console.WriteLine("\nAfter Operations");
Console.WriteLine("Value of pU:" + (uint) pU);
Console.WriteLine("Value of pB:" + (uint) pB);
Console.WriteLine("Value of pD:" + (uint) pD);

The result is:


Before Operations
Value of pU:1242784
Value of pB:1242780
Value of pD:1242772


After Operations
Value of pU:1242804
Value of pB:1242777
Value of pD:1242780

5 * 4 = 20, where added to pU.

3 * 1 = 3, where subtracted from pB.

1 * 8 = 8, where added to pD.

We can also subtract one pointer from another pointer, provided both pointers point to the same date type. This will result a long whose value is given by the difference between the pointers values divided by the size of the type that they represent:

double *pD1 = (double*) 12345632;
double *pD2 = (double*) 12345600;
long L = pD1 ? pD2; //gives 4 =32/8(sizeof(double))

Note that the way of initializing pointers in the example is totally valid.
Pointers to Structs and Class members

Pointers can point to structs the same way we used before as long as they don?t contain any reference types. The compiler will result an error if you had any pointer pointing to a struct containing a reference type.

Let?s have an example,

Suppose we had the following struct:

struct MyStruct
{
public long X;
public double D;
}

Declaring a pointer to it will be:

MyStruct *pMyStruct;

Initializing it:

MyStruct myStruct = new MyStruct();
pMyStruct = & myStruct;

To access the members:

(*pMyStruct).X = 18;
(*pMyStruct).D = 163.26;

The syntax is a bit complex, isn?t it?

That?s why C# defines another operator that allows us to access members of structs through pointers with a simpler syntax. The operator ?Pointer member access operator? looks like an arrow, it?s a dash followed by a greater than sign: ->

pMyStruct->X = 18;
pMyStruct->D = 163.26;

That looks better!

Fields within the struct can also be directly accessed through pointer of their type:

long *pL = &(myStruct.X);
double *pD = &(myStruct.D);

Classes and pointers is a different story. We already know that we can?t have a pointer pointing to a class, where it?s a reference type for sure. The Garbage Collector doesn?t keep any information about pointers, it?s only interested in references, so creating pointers to classes could cause the Garbage Collector to not work probably.

On the other hand, class members could be value types, and it?s possible to create pointers to them. But this requires a special syntax. Remember that class members are embedded in a class, which sets in the heap. That means that they are still under the control of the Garbage Collector, which can at any time decide to move the class instance to a new location. The Garbage Collector knows about the reference, and will update its value, but again it?s not interested in the pointers around, and they will still be pointing to the old location.

To avoid the risk of this problem, the compiler will result an error if you tried to create pointers pointing to class members in the same way we are using up to now.

The way around this problem is by using the keyword ?fixed?. It marks out a block of code bounded by braces, and notifies the Garbage Collector that there may be pointers pointing to members of certain class instances, which must not be moved.

Let?s have an example,

Suppose the following class:


class MyClass
{
public long X;
public double D;
}

Declaring pointers to its members in the regular way is a compile-time error:

MyClass myClass = new MyClass();

long *pX = &(myClass.X); //compile-time error.

To create pointers pointing to class members by using fixed keyword:

fixed (long *pX = &(myClass.X))
{

// use *pX here only.
}

The variable *pX is scoped within the fixed block only, and tells the garbage collector that not to move ?myClass? while the code inside the fixed block.
stackalloc

The keyword "stackalloc" commands the .net runtime to allocate a certain amount of memory on the stack. It requires two things to do so, the type (value types only) and the number of variables you?re allocating the stack for. For example if you want to allocate enough memory to store 4 floats, you can write the following:

float *ptrFloat = stackalloc float [4];

Or to allocate enough memory to store 50 shorts:

short *ptrShort = stackalloc short [50];

stackalloc simply allocates memory, it doesn?t initialize it to any value. The advantage of stackalloc is the ultra-high performance, and it?s up to you to initialize the memory locations that were allocated.

A very useful place of stackalloc could be creating an array directly in the stack. While C# had made using arrays very simple and easy, it still suffers from the disadvantage that these arrays are actually objects instantiated from System.Array and they are stored on the heap with all of the overhead that involves.

To create an array in the stack:

int size;
size = 6; //we can get this value at run-time as well.
int *int_ary = stackalloc int [size];

To access the array members, it?s very obvious to use *(int_ary + i), where ?i ?is the index. But it won?t be surprising to know that it?s also possible to use int_ary[i].

*( int_ary + 0) = 5; //or *int_ary = 5;
*( int_ary + 1) = 9; //accessing member #1
*( int_ary + 2) = 16;

int_ary[3] = 19; //another way to access members
int_ary[4] = 7;
int_ary[5] = 10;

In a usual array, accessing a member outside the array bounds will cause an exception. But when using stackalloc, you?re simply accessing an address somewhere on the stack; writing on it could cause to corrupt a variable value, or worst, a return address from a method currently being executed.

int[] ary = new int[6];
ary[10] = 5;//exception thrown

int *ary = stackalloc int [6];
ary[10] = 5;// the address (ary + 10 * sizeof(int)) had 5 assigned to it.

This takes us to the beginning to the article; using pointer comes with a cost. You have to be very certain of what you?re doing, any small error could cause very strange and hard to debug run-time bugs.

Reading and Writing XML Files in C#

Typically, you use an XmlTextWriter if you need to write XML as raw data without the overhead of a DOM. The XmlTextWriter is an implementation of the XmlWriter class that provides the API which writes XML to file, stream, or a TextWriter. This class provides numerous validation and checking rules to ensure that the XML being written is well formed. When certain violations occur, exceptions are thrown and these exceptions should be handled. The XmlTextWriter has different constructors, each of which specifies a different type of the location to which to write the XML data. This sample uses the constructor that writes XML to a file. In particular, the following sample code constructs an XmlTextWriter with a string representing the file location for the newbooks.xml file.

XmlTextWriter myXmlTextWriter = new XmlTextWriter ("newbooks.xml", null);

C# Code:
myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
myXmlTextWriter.WriteComment("This file represents another fragment of a book store inventory database");
myXmlTextWriter.WriteStartElement("bookstore");
myXmlTextWriter.WriteStartElement("book", null);
myXmlTextWriter.WriteAttributeString("genre","autobiography");
myXmlTextWriter.WriteAttributeString("publicationdate","1979");
myXmlTextWriter.WriteAttributeString("ISBN","0-7356-0562-9");
myXmlTextWriter.WriteElementString("title", null, "The Autobiography of Mark Twain");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name", "Mark");
myXmlTextWriter.WriteElementString("last-name", "Twain");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "7.99");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();

//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();

In creating this element, the preceding sample code also shows how, for each XML node type, there is corresponding XML write method. For example, writing an element calls the WriteElementString method and writing an attribute calls the WriteAttributeString method. For nested levels, you use the WriteStartElement / WriteEndElement pair and, for more complex attribute creation, you can use the WriteStartAttribute / WriteEndAttribute pair.

When writing XML, notice how the sample code writes the XML declaration with the version "1.0" using the WriteStartDocument method. If you want the writer to check that the document is well formed (XML declaration first, DOCTYPE in prolog, only one root level element, and so on), you must call this optional WriteStartDocument method before calling any other write method. Next, the code calls the WriteDocType method to writes the document type with the name "bookstore". The third parameter in the call to the WriteDocType specifies that the writer is to write SYSTEM "books.dtd". By writing this, the XML file indicates that there is an external DTD to validate against.

Finally, the sample code calls the Flush method to persist the XML data to a file before calling the Close method. (While this sample only really requires the Close method, there are occasions where the XML generated needs to be persisted and the writer reused.)

To check the output from the XmlTextWriter, perform a round trip test by reading in the generated file with an XmlTextReader to validate that the XML is well formed.
Reading Xml Files :

XmlReader class is the API that provides XML parsing, the XmlTextReader is the implementation designed to handle byte streams.

Typically, you use the XmlTextReader if you need to access the XML as raw data without the overhead of a DOM. Not having to access the DOM results in a faster way to reading XML. For example, an XML document could have a header section used for routing the document for processing elsewhere. The XmlTextReader has different constructors to specify the location of the XML data. This sample loads XML from the books.xml file, as shown in the following code.
XmlTextReader reader = new XmlTextReader ("books.xml");
Once loaded, the XmlTextReader moves across the XML data by using the Read method sequentially retrieving the next record from the document. The Read method returns false if there are no more records.
while (reader.Read())
{
// Do some work here on the data
...
}


To process the XML data, each record has a node type that can be determined from the NodeType property. After the NodeType enumeration returns the node type, the sample tests the node type to see whether it is either an element or document type. If the node is either one of these two types, the sample processes the node using the Name and Value properties to display details about the node. The Name property returns the node name (for instance, the element and attribute names, while the Value property returns the node value (node text) of the current node (record).
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read attributes
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
break;
case XmlNodeType.DocumentType: // The node is a DocumentType
Console.WriteLine(NodeType + "<" + reader.Name + ">" + reader.Value);
break;
...
}
}

The XmlNodeType returned depends on the XmlReader class being used. For example, the XmlTextReader class never returns an XmlNodeType that is a Document, DocumentFragment, Entity, EndEntity and Notation node. See the .NET Framework Class Library for details on what XmlNodeType are returned by each XmlReader class.

Reading and Writing files using Microsoft .NET class libraries

Writing Text Files :

Text files are the most common type of files. You can make text files in every editor, notepad is preferably used to make text files. The extension of the text file is .txt . Lets see what Microsoft .net class libraries provide us for writing and reading text files. Lets first make a simple interface that lets us enter some data in the multi-line textbox.
Button Click Code:

After making the interface let see some of the code. All the code in this example will be written in the Button click event handler since we want the file to be written when the button is clicked.
// Don't forget to import System.IO namespace

private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.Create(Server.MapPath("test.txt"));
StreamWriter sw = new StreamWriter(fs);
sw.Write(TextBox1.Text);
sw.Close();
fs.Close();
}

As you can see the code is really simple. Lets examine the code and see what's going on.

1. First of all don't forget to import the System.IO namespace.
2. Make the object of FileStream class. The FileStream class is your best option when you don't care about the internal structure of the files with which you're working.
3. Next we make the object of the StreamWriter class. You can think of StreamWriter class as an additional layer of functionality on top of the FileStream class.
4. File.Create method makes a new file. The Server.MapPath means that file will be created in the virtual folder of IIS which will be located at C:\inetpub\wwwroot\YourProjectFolder\
5. Next we write the Text from the TextBox to the file using the StreamWriter Write method.
6. Finally and the most important step is to close the FileStream object explicitly using the Close method.

There are many other ways of writing text to files. One of the way is to use the TextWriter class. For more information about the TextWriter class visit this link Reading Text Files :

We have seen how we can write the Text Files lets see how we can read from the text files. Reading is also as simple as writing the text files. Lets look at the reading code below:
private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.OpenRead(Server.MapPath("test.txt"));
StreamReader sr = new StreamReader(fs);

while(sr.Peek() > -1)
{
Response.Write(sr.ReadLine());
}
sr.Close();
fs.Close();
}

Lets see what the code does:

1. First we made the FileStream object and tells it to open the file "test.txt".
2. We make the StreamReader object and tell it what FileStream to read.
3. The while loop checks the end of the file when the end of the file is reached sr.Peek() returns '-1' and the loop breaks.
4. Finally we close the StreamReader and FileStream objects.

Oracle connection strings

Oracle ODBC connection strings
Open connection to Oracle database using ODBC
"Driver= {Microsoft ODBCforOracle};Server=Your_Oracle_Server.world;Uid=Your_Username;Pwd=Your_Password;"
Oracle OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to Oracle database with standard security:
1. "Provider=MSDAORA;Data Source= Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;"
2. "Provider= OraOLEDB.Oracle;Your_Oracle_Database;UserId=Your_Username;Password=Your_Password;"

Open trusted connection to Oracle database
"Provider= OraOLEDB.Oracle;DataSource=Your_Oracle_Database;OSAuthent=1;"

MySQL connection strings

MySQL ODBC connection strings
Open connection to local MySQL database using MySQL ODBC 3.51 Driver
"Provider=MSDASQL; DRIVER={MySQL ODBC 3.51Driver}; SERVER= localhost; DATABASE=Your_MySQL_Database; UID= Your_Username; PASSWORD=Your_Password; OPTION=3"
MySQL OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to MySQL database:
"Provider=MySQLProv;Data Source=Your_MySQL_Database;User Id=Your_Username; Password=Your_Password;"

MS Access connection strings

MS Access ODBC connection strings
Standard Security:
"Driver= {MicrosoftAccessDriver(*.mdb)};DBQ=C:\App1\Your_Database_Name.mdb;Uid=Your_Username;Pwd=Your_Password;"

Workgroup:
"Driver={Microsoft Access Driver (*.mdb)}; Dbq=C:\App1\Your_Database_Name.mdb; SystemDB=C:\App1\Your_Database_Name.mdw;"

Exclusive "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\App1\Your_Database_Name.mdb; Exclusive=1; Uid=Your_Username; Pwd=Your_Password;"
MS Access OLE DB & OleDbConnection (.NET framework) connection strings
Open connection to Access database:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; User Id=admin; Password="

Open connection to Access database using Workgroup (System database):
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:System Database=c:\App1\Your_System_Database_Name.mdw"

Open connection to password protected Access database:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb; Jet OLEDB:Database Password=Your_Password"

Open connection to Access database located on a network share:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\Server_Name\Share_Name\Share_Path\Your_Database_Name.mdb"

Open connection to Access database located on a remote server:
"Provider=MS Remote; Remote Server=http://Your-Remote-Server-IP; Remote Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\Your_Database_Name.mdb"

SQL Server connection strings

SQL ODBC connection strings
Standard Security:< br> "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Uid=Your_Username;Pwd=Your_Password;"

Trusted connection:< br> "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=yes;"
SQL OLE DB connection strings
Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"

Trusted connection:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
SQL OleDbConnection .NET strings
Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"

Trusted connection:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
SQL SqlConnection .NET strings
Standard Security:
1. "Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" < br>2. "Server=Your_Server_Name;Database=Your_Database_Name;UserID=Your_Username;Password=Your_Password;Trusted_Connection=False"

Trusted connection:
1. "Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
2."Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=True;"

Sunday, February 18, 2007

Database Design and Various Useful Definition

What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.

Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables. See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Candidate key, Alternate key, Composite key

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.

Hackers attack key Net traffic computers

Hackers briefly overwhelmed at least three of the 13 computers that help manage global computer traffic on Tuesday in one of the most significant attacks against the Internet since 2002.

Experts said the unusually powerful attacks lasted as long as 12 hours but passed largely unnoticed by most computer users, a testament to the resiliency of the Internet. Behind the scenes, computer scientists worldwide raced to cope with enormous volumes of data that threatened to saturate some of the Internet's most vital pipelines.

The Homeland Security Department confirmed it was monitoring what it called "anomalous" Internet traffic.



"There is no credible intelligence to suggest an imminent threat to the homeland or our computing systems at this time," the department said in a statement.

The motive for the attacks was unclear, said Duane Wessels, a researcher at the Cooperative Association for Internet Data Analysis at the San Diego Supercomputing Centre. "Maybe to show off or just be disruptive; it doesn't seem to be extortion or anything like that," Wessels said.

Other experts said the hackers appeared to disguise their origin, but vast amounts of rogue data in the attacks were traced to South Korea.

The attacks appeared to target UltraDNS, the company that operates servers managing traffic for Web sites ending in "org" and some other suffixes, experts said. Officials with NeuStar Inc., which owns UltraDNS, confirmed only that it had observed an unusual increase in traffic.

Among the targeted "root" servers that manage global Internet traffic were ones operated by the Defence Department and the Internet's primary oversight body.

"There was what appears to be some form of attack during the night hours here in California and into the morning," said John Crain, chief technical officer for the Internet Corporation for Assigned Names and Numbers. He said the attack was continuing and so was the hunt for its origin.

"I don't think anybody has the full picture," Crain said. "We're looking at the data."

Crain said Tuesday's attack was less serious than attacks against the same 13 "root" servers in October 2002 because technology innovations in recent years have increasingly distributed their workloads to other computers around the globe.

Net watchdog proposes '.xxx' porn domain

The Internet's key oversight agency has revived a proposal it earlier rejected to create an online red-light district, after adding stronger provisions to prohibit child pornography and require labelling of websites with sexually explicit materials.

The use of the proposed ".xxx" domain name would remain voluntary, but any porn sites that choose to use it instead of the more popular ".com" would be subject to the new terms issued by the Internet Corporation for Assigned Names and Numbers.

The idea of a separate ".xxx" domain has generated significant opposition from conservative groups and even some pornography websites.



But ICANN officials said they initially rejected the proposal in May not because of the opposition but because of concerns that the agency might be put in a difficult position of having to enforce all of the world's laws governing pornography. They noted that various nations' speech-related laws sometimes conflict with one another.

The new proposal does not directly address any potential conflicts in laws, but it calls for the company backing it, ICM Registry Inc of Jupiter, Florida, to hire independent organisations to monitor porn sites' compliance with the new rules.

ICANN, the agency in Marina del Rey, California, designated by the US government to oversee domain name policies, opened the proposal to public comment but did not indicate when it would rule.

If approved, ICM would be required to help develop mechanisms for promoting child safety and preventing child pornography, "including practices that appeal to paedophiles or suggest the presence of child pornography on the site."

Porn sites would have to participate in a self-descriptive labelling system, likely one from the Internet Content Rating Association. Under it, websites add tags based on such criteria as the presence of nudity and whether it is in an artistic or educational context, such as for sites on breast feeding. Relatively few sites now participate, although major browsers have mechanisms for reading the tags.

ICM also would have to develop automated tools to check for compliance and give users ways to report violations.

ICM believes the domain would help the $12 billion online porn industry clean up its act, as those using it must abide by rules designed to bar such trickery as spamming and malicious scripts.

Anti-porn advocates, however, countered that sites would be free to keep their current ".com" address, in effect making porn more easily accessible by creating yet another channel to house it.

Many porn sites also objected, fearing that an ".xxx' domain would pave the way for governments or even private industry to filter speech that is protected in the United States by the First Amendment.

The Essentials of Google Search

Choosing search terms

Choosing the right search terms is the key to finding the information you need.

Start with the obvious – if you're looking for general information on Hawaii, try
Hawaii.




But it's often advisable to use multiple search terms; if you're planning a Hawaiian vacation, you'll do better with vacation Hawaii than with either vacation or Hawaii by themselves. And vacation Hawaii golf may produce even better (or, depending on your perspective, worse) results.

vacation Hawaii golf


You might also ask yourself if your search terms are sufficiently specific. It's better to search on luxury hotels Maui than on tropical island hotels. But choose your search terms carefully; Google looks for the search terms you chose, so luxury hotels Maui will probably deliver better results than really nice places to spend the night in Maui.




Capitalization

Google searches are NOT case sensitive. All letters, regardless of how you type them, will be understood as lower case. For example, searches for george washington, George Washington, and gEoRgE wAsHiNgToN will all return the same results.




Automatic "and" queries

By default, Google only returns pages that include all of your search terms. There is no need to include "and" between terms. Keep in mind that the order in which the terms are typed will affect the search results. To restrict a search further, just include more terms. For example, to plan a vacation to Hawaii, simply type vacation hawaii.

vacation Hawaii



Automatic exclusion of common words

Google ignores common words and characters such as "where" and "how", as well as certain single digits and single letters, because they tend to slow down your search without improving the results. Google will indicate if a common word has been excluded by displaying details on the results page below the search box.

If a common word is essential to getting the results you want, you can include it by putting a "+" sign in front of it. (Be sure to include a space before the "+" sign.)

Another method for doing this is conducting a phrase search, which simply means putting quotation marks around two or more words. Common words in a phrase search (e.g., "where are you") are included in the search.

For example, to search for Star Wars, Episode I, use:

Star Wars Episode +I

~ OR ~

"Star Wars Episode I"

Word variations (stemming)

Google now uses stemming technology. Thus, when appropriate, it will search not only for your search terms, but also for words that are similar to some or all of those terms. If you search for pet lemur dietary needs, Google will also search for pet lemur diet needs, and other related variations of your terms. Any variants of your terms that were searched for will be highlighted in the snippet of text accompanying each result.




Phrase searches

Sometimes you'll only want results that include an exact phrase. In this case, simply put quotation marks around your search terms.


Phrase searches are particularly effective if you're searching for proper names ("George Washington"), lyrics ("the long and winding road"), or other famous phrases ("This was their finest hour").


"the long and winding road"

Negative terms

If your search term has more than one meaning (bass, for example, could refer to fishing or music) you can focus your search by putting a minus sign ("-") in front of words related to the meaning you want to avoid.

For example, here's how you'd find pages about bass-heavy lakes, but not bass-heavy music:

bass -music
Note: when you include a negative term in your search, be sure to include a space before the minus sign.




And finally... "I'm Feeling Lucky"

After you've entered your search terms, you might want to try the "I'm Feeling Lucky" button, which takes you straight to the most relevant website that Google found for your query. You won't see the search results page at all, but if you did, the "I'm Feeling Lucky" site would be listed on top.

For example, if you're looking for the Stanford University homepage, just enter Stanford and click "I'm Feeling Lucky" instead of the Google Search button. Google will take you directly to "www.stanford.edu."

Database Programming SQL Server

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the result sets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.

What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?

USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder.Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED().

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)
INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

SQL Server architecture

What is a transaction and what are ACID properties?



A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.

Explain different isolation levels ?



An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?




Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What's the maximum size of a row ?



8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations



Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.

Explain the architecture of SQL Server



This is a very important question and you better be able to answer it if consider yourself a DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.

What is lock escalation?



Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?



DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP



Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more information.

What are constraints? Explain different types of constraints.



Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?



Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

How to execute an application in a remote application domain

Application domain is a construct in the CLR that is the unit of isolation for an application. Application domains provide a secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability.



Make a file CallingAssembly.cs containing following code



using System;

using System.Reflection;

using System.Runtime.Remoting;
public class CallingAssembly

{

public static void Main(String[] argv)

{

AppDomainSetup objADS = new AppDomainSetup();

objADS.ApplicationBase = "file:///" + Environment.CurrentDirectory;

AppDomain objAD = AppDomain.CreateDomain("RemoteDomainExample", null, objADS);

objAD.ExecuteAssembly("CalledAssembly.exe");

AppDomain.Unload(objAD);

}

}



Two Application domains interact with each other through Remoting. AppDomain class is drived from MarshalByRefObject, which Enables access to objects across application domain boundaries in applications that support remoting. CreateDomain creates a new application domain with the given name using the assembly binding information and supplied evidence. ExecuteAssembly methos of AppDomain, Executes the assembly contained in the specified file in that domain.



Make a file CalledAssembly.cs containing following code



using System;

using System.Threading;

public class CalledAssembly

{

public static void Main(String[] argv)

{

Console.WriteLine("Called Assembly Application Domain: " + Thread.GetDomain().FriendlyName);

Console.WriteLine("Assembly Called");

}

}

Fading Effect in ASP.NET Page

Just put this code within HEAD tag of your page

What are Delegates?

In your Visual Basic.NET journey, you have definitely encountered a well used but little understood phenomenon called a delegate. You use them everyday, but might not know it. In this article, we will take a look at what a delegate is and how it will help you to develop better software.

A delegate can be defined as a type safe function pointer. It encapsulates the memory address of a function in your code. Whenever you create or use an event in code, you are using a delegate. When the event is thrown, the framework examines the delegate behind the event and then calls the function that the delegate points to. As we will see later, delegates can be combined to form groups of functions that can be called together.

Let's first take a quick look at how to define and invoke a delegate. First we declare our delegate in our form class:

Private Delegate Sub MyDelSub()Then we use the delegate by simply declaring a variable of the delegate and assigning the sub or function to run when called. First the sub to be called:

Private Sub WriteToDebug() Debug.WriteLine( "Delegate Wrote To Debug Window" )End SubYou will notice also that it matches our declaration of MyDelSub; it's a sub routine with no parameters. And then our test code:

Dim del As MyDelSubdel = New MyDelSub(AddressOf WriteToDebug)del.Invoke()When we invoke the delegate, the WriteToDebug sub is run. Visual Basic hides most of the implementation of delegates when you use events, which are based off invoking a delegate. This is the equivalent of the above delegate invoke also.

Private Event MyEvent() 'declare it in the class'to use it, add a handler and raise the event.AddHandler MyEvent, AddressOf WriteToDebugRaiseEvent MyEvent()If delegates stopped at this point, they would be useless since events are less work and do the same thing. Let's get into some of the more advanced features of delegates. We will start with multicast delegates.

Transfer Record in Excel Through the SQL Server 2000

PRINT 'Begin CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
PRINT ''
GO

SET NOCOUNT ON
DECLARE @Conn int -- ADO Connection object to create XLS
, @hr int -- OLE return value
, @src varchar(255) -- OLE Error Source
, @desc varchar(255) -- OLE Error Description
, @Path varchar(255) -- Drive or UNC path for XLS
, @Connect varchar(255) -- OLE DB Connection string for Jet 4 Excel ISAM
, @WKS_Created bit -- Whether the XLS Worksheet exists
, @WKS_Name varchar(128) -- Name of the XLS Worksheet (table)
, @ServerName nvarchar(128) -- Linked Server name for XLS
, @DDL varchar(8000) -- Jet4 DDL for the XLS WKS table creation
, @SQL varchar(8000) -- INSERT INTO XLS T-SQL
, @Recs int -- Number of records added to XLS
, @Log bit -- Whether to log process detail

-- Init variables
SELECT @Recs = 0
-- %%% 1 = Verbose output detail, helps find problems, 0 = minimal output detail
, @Log = 1
-- %%% assign the UNC or path and name for the XLS file, requires Read/Write access
-- must be accessable from server via SQL Server service account
-- & SQL Server Agent service account, if scheduled
SET @Path = 'C:\TEMP\Test_'+CONVERT(varchar(10),GETDATE(),112)+'.xls'
-- assign the ADO connection string for the XLS creation
SET @Connect = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+@Path+';Extended Properties=Excel 8.0'
-- %%% assign the Linked Server name for the XLS population

SET @ServerName = 'EXCEL_TEST'

-- %%% Rename Table as required, this will also be the XLS Worksheet name
SET @WKS_Name = 'People'
-- %%% Table creation DDL, uses Jet4 syntax,
-- Text data type = varchar(255) when accessed from T-SQL
SET @DDL = 'CREATE TABLE '+@WKS_Name+' (SSN Text, Name Text, Phone Text)'
-- %%% T-SQL for table population, note the 4 part naming required by Jet4 OLE DB
-- INSERT INTO SELECT, INSERT INTO VALUES, and EXEC sp types are supported
-- Linked Server does not support SELECT INTO types
SET @SQL = 'INSERT INTO '+@ServerName+'...'+@WKS_Name+' (SSN, Name, Phone) '
SET @SQL = @SQL+'SELECT au_id AS SSN'
SET @SQL = @SQL+', LTRIM(RTRIM(ISNULL(au_fname,'''')+'' ''+ISNULL(au_lname,''''))) AS Name'
SET @SQL = @SQL+', phone AS Phone '
SET @SQL = @SQL+'FROM pubs.dbo.authors'

IF @Log = 1 PRINT 'Created OLE ADODB.Connection object'
-- Create the Conn object
EXEC @hr = sp_OACreate 'ADODB.Connection', @Conn OUT
IF @hr <> 0 -- have to use <> as OLE / ADO can return negative error numbers
BEGIN
-- Return OLE error
EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END

IF @Log = 1 PRINT char(9)+'Assigned ConnectionString property'
-- Set a the Conn object's ConnectionString property
-- Work-around for error using a variable parameter on the Open method
EXEC @hr = sp_OASetProperty @Conn, 'ConnectionString', @Connect
IF @hr <> 0
BEGIN
-- Return OLE error
EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END

IF @Log = 1 PRINT char(9)+'Open Connection to XLS, for file Create or Append'
-- Call the Open method to create the XLS if it does not exist, can't use parameters
EXEC @hr = sp_OAMethod @Conn, 'Open'
IF @hr <> 0
BEGIN
-- Return OLE error
EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END

-- %%% This section could be repeated for multiple Worksheets (Tables)
IF @Log = 1 PRINT char(9)+'Execute DDL to create '''+@WKS_Name+''' worksheet'
-- Call the Execute method to Create the work sheet with the @WKS_Name caption,
-- which is also used as a Table reference in T-SQL
-- Neat way to define column data types in Excel worksheet
-- Sometimes converting to text is the only work-around for Excel's General
-- Cell formatting, even though the Cell contains Text, Excel tries to format
-- it in a "Smart" way, I have even had to use the single quote appended as the
-- 1st character in T-SQL to force Excel to leave it alone
EXEC @hr = sp_OAMethod @Conn, 'Execute', NULL, @DDL, NULL, 129 -- adCmdText + adExecuteNoRecords
-- 0x80040E14 for table exists in ADO
IF @hr = 0x80040E14
-- kludge, skip 0x80042732 for ADO Optional parameters (NULL) in SQL7
OR @hr = 0x80042732
BEGIN
-- Trap these OLE Errors
IF @hr = 0x80040E14
BEGIN
PRINT char(9)+''''+@WKS_Name+''' Worksheet exists for append'
SET @WKS_Created = 0
END
SET @hr = 0 -- ignore these errors
END
IF @hr <> 0
BEGIN
-- Return OLE error
EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END

IF @Log = 1 PRINT 'Destroyed OLE ADODB.Connection object'
-- Destroy the Conn object, +++ important to not leak memory +++
EXEC @hr = sp_OADestroy @Conn
IF @hr <> 0
BEGIN
-- Return OLE error
EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END

-- Linked Server allows T-SQL to access the XLS worksheet (Table)
-- This must be performed after the ADO stuff as the XLS must exist
-- and contain the schema for the table, or worksheet
IF NOT EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
IF @Log = 1 PRINT 'Created Linked Server '''+@ServerName+''' and Login'
EXEC sp_addlinkedserver @server = @ServerName
, @srvproduct = 'Microsoft Excel Workbook'
, @provider = 'Microsoft.Jet.OLEDB.4.0'
, @datasrc = @Path
, @provstr = 'Excel 8.0'
-- no login name or password are required to connect to the Jet4 ISAM linked server
EXEC sp_addlinkedsrvlogin @ServerName, 'false'
END

-- Have to EXEC the SQL, otherwise the SQL is evaluated
-- for the linked server before it exists
EXEC (@SQL)
PRINT char(9)+'Populated '''+@WKS_Name+''' table with '+CONVERT(varchar,@@ROWCOUNT)+' Rows'

-- %%% Optional you may leave the Linked Server for other XLS operations
-- Remember that the Linked Server will not create the XLS, so remove it
-- When you are done with it, especially if you delete or move the file
IF EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
IF @Log = 1 PRINT 'Deleted Linked Server '''+@ServerName+''' and Login'
EXEC sp_dropserver @ServerName, 'droplogins'
END
GO

SET NOCOUNT OFF
PRINT ''
PRINT 'Finished CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
GO

Sql Server Documentation Query

select @@version
go

exec master..xp_msver
go

print ''
print '1.2 Miscelaneous'
print '---------------------------'
print ''

select convert(varchar(30),login_time,109) as 'Servidor inicializado em ' from master..sysprocesses where spid = 1

print 'Number of connections..: ' + convert(varchar(30),@@connections)
print 'Language...............: ' + convert(varchar(30),@@language)
print 'Language Id............: ' + convert(varchar(30),@@langid)
print 'Lock Timeout...........: ' + convert(varchar(30),@@LOCK_TIMEOUT)
print 'Maximum of connections.: ' + convert(varchar(30),@@MAX_CONNECTIONS)
print 'Server Name............: ' + convert(varchar(30),@@SERVERNAME)
print 'Instance...............: ' + convert(varchar(30),@@SERVICENAME)
print ''
print 'CPU Busy...........: ' + convert(varchar(30),@@CPU_BUSY/1000)
print 'CPU Idle...........: ' + convert(varchar(30),@@IDLE/1000)
print 'IO Busy............: ' + convert(varchar(30),@@IO_BUSY/1000)
print 'Packets received...: ' + convert(varchar(30),@@PACK_RECEIVED)
print 'Packets sent.......: ' + convert(varchar(30),@@PACK_SENT)
print 'Packets w errors...: ' + convert(varchar(30),@@PACKET_ERRORS)
print 'TimeTicks..........: ' + convert(varchar(30),@@TIMETICKS)
print 'IO Errors..........: ' + convert(varchar(30),@@TOTAL_ERRORS)
print 'Total Read.........: ' + convert(varchar(30),@@TOTAL_READ)
print 'Total Write.........: ' + convert(varchar(30),@@TOTAL_WRITE)
go

Saturday, February 17, 2007

what is Ethical Hacker ?

An ethical hacker is a computer and network expert who attacks a security system on behalf of its owners, seeking vulnerabilities that a malicious hacker could exploit. To test a security system, ethical hackers use the same methods as their less principled counterparts, but report problems instead of taking advantage of them. Ethical hacking is also known as penetration testing, intrusion testing, and red teaming. An ethical hacker is sometimes called a white hat, a term that comes from old Western movies, where the "good guy" wore a white hat and the "bad guy" wore a black hat.

Thursday, February 15, 2007

Google Myths

1. Google Desktop indexes your files and uploads the index to Google's servers.

No. Google stores the index on your computer. If you enable a feature called "search across computers", Google will securely send copies of your indexed files to Google servers. The feature is disabled by default.

2. Gmail indexes your emails and makes them available for everyone.

No. Google indexes your messages so you can search them. This feature is now available in other webmail applications (Yahoo Mail, Windows Live Mail). Google doesn't make your messages or the indexes public.

3. Google doesn't delete my Gmail messages.

In order to keep your email safe, Google needs to have multiple backups of your data. "You may organize or delete your messages through your Gmail account. (...) Residual copies of deleted messages and accounts may take up to 60 days to be deleted from our active servers and may remain in our offline backup systems." (Gmail Privacy Policy)

4. Google doesn't improve search anymore to increase its earnings from ads.

You may not perceive too many changes in Google search, but Google tweaks its algorithms often to improve search results quality, removes spam sites and tries to add more fresh results. On the visible side, Google added search refinements, more direct answers, malware warnings and address recognition.

5. Search results should be ranked by people, not by algorithms.

Google uses the links from other pages the determine the importance of a page, and those links were placed by humans. Google also monitors user's clicks to determine if the search results are relevant.

6. Google is spyware.

"Spyware is software that reports on your activities or gathers personal information about you and sends it via the Internet to third parties without your knowledge or consent." If you use software like Google Toolbar or Google Desktop, some features may send personal information to Google, but most of them are either turned off by default or require your explicit approval. Google also uses cookies to save your preferences and records queries, clicks, usage patterns to deliver better results. The problem is not that they record it, it's what they do with it. And Google tries to protect it from third parties (like US Government).

7. Google Earth shows real-time images.

No, what you see "are photographs taken by satellites and aircraft sometime in the last three years".

8. Google is the best search engine that will ever be built.

Google is far from a search engine that "understands exactly what you mean and gives you back exactly what you want". But its goal is to reach that state. (Google's philosophy)

9. Google favors Wikipedia, Technorati, blogs.

Well, not exactly. These sites happen to have many backlinks, and oftentimes quality links. I know many people that link to Wikipedia to show an explanation for a concept or an acronym, link to Technorati to tag their blog posts or link to blogs because they are infectious.

10. Google will take over the world.

Those who control information, control the world. Hopefully Google will be a benevolent dictator

Google Pages You've Never Seen

Google Moms
A tribute to Googlers' moms.

Google AdSense for domains
AdSense for domains allows domain name registrars to fill the otherwise blank pages with AdSense ads.

Google Sets
Google Sets is the oldest Google product that never graduated Google Labs. Using Google Sets, you can create sets of items from a few examples.

Google Dance 2004
Also Google Dance 2005.

Get stock with Google
Google provides stock and mutual fund information since 2001.

Google doesn't sell search results
Google talks about the integrity of its results and answers this tricky question: "In a world where everything seems to be for sale, why can't advertisers buy better position in our search results?"

Google WiFi
Google provides free WiFi in Mountain View through Google Secure Access, a client that makes the WiFi connection more secure.

Google Newsletter
You knew Google has a blog, but you didn't know they have a newsletter called Google Friends. You can read the full archive.

Chad's journey to Jersey
One bike. One Googler. One really long ride.

Google Easter Eggs
A Java game with an Easter bunny.

Google Search Tips

A quote/ phrase search can be written with both quotations ["like this"] as well as a minus in-between words, [like-this].

Google didn’t always understand certain special characters like [#], but now they do; a search for [C#], for example, yields meaningful results (a few years ago, it didn’t). This doesn’t mean you can use just any character; e.g. entering [t.] and [t-] and [t^] will always return the same results.

Google allows 32 words within the search query (some years ago, only up to 10 were used, and Google ignored subsequent words). You rarely will need so many words in a single query – [just thinking of such a long query is a hard thing to do, as this query with twenty words shows] – however, it can come in handy for advanced searching... especially as a developer using the Google API.

You can find synonyms of words. E.g. when you search for [house] but you want to find “home” too, search for [~house]. To get to know which synonyms the Google database stores for individual words, simply use the minus operator to exclude synonym after synonym (they will always show as bold in the SERPs, the search engine result pages). Like this: [~house -house -home -housing -floor].

To see a really large page-count (possibly, the Google index size, though one can only speculate about that), search for [* *].
Google has a lesser known “numrange” operator which can be helpful. Using e.g. [2000..2005] (that’s two dots inbetween two numbers) will find 2000, 2001, 2002 and so on until 2005.

Google’s define-operator allows you to look up word definitions. For example, [define:css] yields “Short for Cascading Style Sheets” and many more explanations. You can trigger a somewhat “softer” version of the define-operator by entering “what is something”, e.g. [what is css].


Google has some exciting back-end AI to allow you to find just the facts upong entering simple questions or phrases like [when was Einstein born?] or [einstein birthday] (the answer to both of these queries is “Albert Einstein – Date of Birth: 14 March 1879”). This feature was introduced April this year and is called Google Q&A. (See some of the various working Q&A sample queries to get a feeling for what’s possible.)

Google allows you to find backlinks by using the link-operator, e.g. [link:blog.outer-court.com] for this blog. The new Google Blog Search supports this operator as well. In fact, when Google’s predecessor started out as Larry Page’s “BackRub” in the 1990s, finding backlinks was its only aim! However, not all backlinks are shown in Google today, at least not in web search. (It’s argued that Google does this on purpose to prevent reverse-engineering of its PageRank algorithm.)

Often when you enter a question mark at the end of the query, like when you type [why?], Google will advertise its pay-for-answer service Google Answers.
There a “sport” called Google Hacking. Basically, curious people try to find unsecure sites by entering specific, revealing phrases. A special web site called the Google Hacking Database is dedicated to listing these special queries.
Google searches for all of your words, whether or not you write a “+” before them (I often see people write queries [+like +this], but it’s not necessary). Unless, of course, you use Google’s or-operator. It’s an upper-case [OR] (lower-case won’t work and is simply searching for occurrences of the word “or”), and you can also use parentheses and the “|” character. [Hamlet (pizza | coke)] will find pages containing the word (or being linked to with the word) “Hamlet” and additionally containing at least one of the two other words, “pizza” or “coke”.
Not all Google services support the same syntax. Some services don’t allow everything Google web search allows you to enter (or at least, it won’t have any effect), and sometimes, you can even enter more than in web search (e.g. [insubject:test] in Google Groups). The easiest thing to find out about these operators is to simply use the advanced search and then check what ends up being written in the input box.

Sometimes, Google seems to understand “natural language” queries and shows you so-called “onebox” results. This happens for example when you enter [goog], [weather new york, ny], [new york ny] or [war of the worlds] (for this one, movie times, move rating and other information will show).
Not all Googles are the same! Depending on your location, Google will forward you to a different country-specific version of Google with potentially different results to the same query. A search for [site:stormfront.org] from the US will yield hundreds of thousands of results, whereas the same search from Germany (at least if you don’t change the default redirect to Google.de) returns... zilch. Yes, Google does at times agree to country-specific censorship, like in Germany, France (Google web search), or China (Google News).

Sometimes, Google warns you about its results, especially when they might seem like promoting hate sites (of course, only someone misunderstanding how Google works could think it’s them promoting hate sites). Enter [jew], and you will see a Google-sponsored link titled “Offensive Search Results” leading to this explanation.
For some search queries, Google uses its own ads to offer jobs. Try entering [work at Google] and take a look at the right-hand advertisement titled e.g. “Work at Google Europe” (it turns out, at the moment, Google Switzerland is hiring).
For some of the more popular “Googlebombed” results, like when you enter [failure] and the first hit is the biography of George W. Bush, Google displays explanatory ads titled “Why these results?”.

While Google doesn’t do real Natural Language Processing yet, this is the ultimate goal for them and other search engines. A little What-If Video [WMV] illustrates how this could be useful in the future.
Some say that whoever turns up first for the search query [president of the internet] is, well, the President of the internet. (I’m applying as well, and you can feel free to support me with this logo.)

Google doesn’t have “stop words” anymore. Stop words traditionally are words like [the], [or] and similar which search engines tended to ignore. Sometimes, when you enter e.g. [to be or not to be], Google even decides to show some phrase search results in the middle of the page (separated by a line and information that these are phrase search results).

There once was an easter-egg in the Google Calculator that made Google show “42” when you entered [The Answer to Life, the Universe, and Everything]. If I’m not mistaken, this feature has disappeared and now displays a more reasonable (but less funny) definition of the concept of Douglas Adams’ galactical joke. As I’ve been alerted in the forum, the easter egg only works lower-case.

You can use the wildcard operator in phrases. This is helpful for finding song texts – let’s say you forgot a word or two, but you remember the gist, as in ["love you twice as much * oh love * *"] – and similar tasks.
You can use the wildcard character without searching for anything specific at all, as in this phrase search: ["* * * * * * *"].

Even though www.googl.com is nothing but a “typosquatter” (someone reserving a domain name containing a popular misspelling) and search queries return very different results than Google, the site is still getting paid by Google – because it uses Google AdSense.

If you feel like restricting your search to university servers, you can write e.g. [c-tutorial site:.edu] to only search on the “edu” domain (you can also use Google Scholar). This works for country-domains like “de” or “it” as well.

Computer Networking

1. What are 10Base2, 10Base5 and 10BaseT Ethernet LANs
10Base2—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with a contiguous cable segment length of 100
meters and a maximum of 2 segments.
10Base5—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with 5 continuous segments not exceeding 100
meters per segment.
10BaseT—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling and twisted pair cabling.

2. Explain the difference between an unspecified passive open and a fully specified passive open
An unspecified passive open has the server waiting for a connection request from a client. A fully specified passive
open has the server waiting for a connection from a
specific client.


3. Explain the function of Transmission Control Block
A TCB is a complex data structure that contains a considerable amount of information about each connection.


4. Explain a Management Information Base (MIB)
A Management Information Base is part of every SNMP-managed device. Each SNMP agent has the MIB database that
contains information about the device's status, its
performance, connections, and configuration. The MIB is queried by SNMP.


5. Explain anonymous FTP and why would you use it
Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP
uses a login called anonymous or guest, with the
password usually requesting the user's ID for tracking purposes only. Anonymous FTP is used to enable a large number
of users to access files on the host without having
to go to the trouble of setting up logins for them all. Anonymous FTP systems usually have strict controls over the areas
an anonymous user can access.


6. Explain a pseudo tty
A pseudo tty or false terminal enables external machines to connect through Telnet or rlogin. Without a pseudo tty, no
connection can take place.


7. Explain REX
What advantage does REX offer other similar utilities


8. What does the Mount protocol do
The Mount protocol returns a file handle and the name of the file system in which a requested file resides. The message
is sent to the client from the server after reception
of a client's request.


9. Explain External Data Representation
External Data Representation is a method of encoding data within an RPC message, used to ensure that the data is not
system-dependent.
10. Explain the Network Time Protocol ?


11. BOOTP helps a diskless workstation boot. How does it get a message to the network looking for its IP address and the location of its operating system boot files
BOOTP sends a UDP message with a subnetwork broadcast address and waits for a reply from a server that gives it the IP address. The same message might contain the name of the machine that has the boot files on it. If the boot image location is not specified, the workstation sends another UDP message to query the server.


12. Explain a DNS resource record
A resource record is an entry in a name server's database. There are several types of resource records used, including name-to-address resolution information. Resource records are maintained as ASCII files.


13. What protocol is used by DNS name servers
DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP.


14. Explain the difference between interior and exterior neighbor gateways
Interior gateways connect LANs of one organization, whereas exterior gateways connect the organization to the outside world.


15. Explain the HELLO protocol used for
The HELLO protocol uses time instead of distance to determine optimal routing. It is an alternative to the Routing Information Protocol.


16. What are the advantages and disadvantages of the three types of routing tables
The three types of routing tables are fixed, dynamic, and fixed central. The fixed table must be manually modified every time there is a change. A dynamic table changes its information based on network traffic, reducing the amount of manual maintenance. A fixed central table lets a manager modify only one table, which is then read by other devices. The fixed central table reduces the need to update each machine's table, as with the fixed table. Usually a dynamic table causes the fewest problems for a network
administrator, although the table's contents can change without the administrator being aware of the change.


17. Explain a TCP connection table


18. Explain source route
It is a sequence of IP addresses identifying the route a datagram must follow. A source route may
optionally be included in an IP datagram header.


19. Explain RIP (Routing Information Protocol)
It is a simple protocol used to exchange information between the routers.


20. Explain SLIP (Serial Line Interface Protocol)
It is a very simple protocol used for transmission of IP datagrams across a serial line.

21. Explain Proxy ARP
It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.

22. Explain OSPF
It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions.

23. Explain Kerberos
It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files.

24. Explain a Multi-homed Host
It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host.

25. Explain NVT (Network Virtual Terminal)
It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session.
26. Explain Gateway-to-Gateway protocol
It is a protocol formerly used to exchange routing information between Internet core routers.

27. Explain BGP (Border Gateway Protocol)
It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol).
28. Explain autonomous system
It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol.

29. Explain EGP (Exterior Gateway Protocol)
It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached
within or via each autonomous system.

30. Explain IGP (Interior Gateway Protocol)
It is any routing protocol used within an autonomous system.

31. Explain Mail Gateway
It is a system that performs a protocol translation between different electronic mail delivery protocols.

32. Explain wide-mouth frog
Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol.

33. What are Digrams and Trigrams
The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion.
34. Explain silly window syndrome
It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time.
35. Explain region
When hierarchical routing is used, the routers are divided into what we call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions.
36. Explain multicast routing
Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing.
37. Explain traffic shaping
One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping.
38. Explain packet filter
Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.
39. Explain virtual path
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.
40. Explain virtual channel
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.
41. Explain logical link control
One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.
42. Why should you care about the OSI Reference Model
It provides a framework for discussing network operations and design.
43. Explain the difference between routable and non- routable protocols
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router
44. Explain MAU
In token Ring , hub is called Multistation Access Unit(MAU).
45. Explain 5-4-3 rule
In a Ethernet network, between any two points on the network, there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.
46. Explain the difference between TFTP and FTP application layer protocols
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.
The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offered by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.
47. Explain the range of addresses in the classes of internet addresses
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 - 247.255.255.255

48. Explain the minimum and maximum length of the header in the TCP segment and IP datagram
The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes.
49. Explain difference between ARP and RARP
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.
50. Explain ICMP
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.
51. What are the data units at different layers of the TCP / IP protocol suite
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and
finally transmitted as signals along the transmission media.

52. Explain Project 802
It is a project started by IEEE to set standards that enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN protocols.
It consists of the following:
802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.
802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.
Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.
53. Explain Bandwidth
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth.
54. Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits. baud rate = bit rate / N where N is no-of-bits represented by each signal shift.
55. Explain MAC address
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.

56. Explain attenuation
The degeneration of a signal over distance on a network cable is called attenuation.

57. Explain cladding
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.

58. Explain RAID
A method for providing fault tolerance by using multiple hard disk drives.

59. Explain NETBIOS and NETBEUI
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications. NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets.

60. Explain redirector
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.
61. Explain Beaconing
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
62. Explain terminal emulation, in which layer it comes
Telnet is also called as terminal emulation. It belongs to application layer.

63. Explain frame relay, in which layer it comes
Frame relay is a packet switching technology. It will operate in the data link layer.

64. What do you meant by "triple X" in Networks
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X"
65. Explain SAP
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.

66. Explain subnet
A generic term for section of a large networks usually separated by a bridge or router.

67. Explain Brouter
Hybrid devices that combine the features of both bridges and routers.

68. How Gateway is different from Routers
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats.

69. What are the different type of networking / internetworking devices
Repeater: Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.
Routers: They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:
They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.
70. Explain mesh network
A network in which there are multiple network links between computers to provide multiple paths for data to travel.
71. Explain passive topology
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.

72. What are the important topologies for networks
BUS topology:
In this each computer is directly connected to primary network cable in a single line.
Advantages:
Inexpensive, easy to install, simple to understand, easy to extend.
STAR topology:
In this all computers are connected using a central hub.
Advantages:
Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.
RING topology:
In this all computers are connected in loop.
Advantages:
All computers have equal access to network media, installation can be simple, and signal does not degrade as much as
in other topologies because each computer
regenerates it.

73. What are major types of networks and explain
Server-based network
Peer-to-peer network
Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources.
Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration

74. Explain Protocol Data Unit
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a
unnumbered frame (U - frame).
75. Explain difference between baseband and broadband transmission
In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.
76. What are the possible ways of data exchange
(i) Simplex (ii) Half-duplex (iii) Full-duplex.

77. What are the types of Transmission media
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
Guided Media:
These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept
and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
Unguided Media:
This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.
78. Explain point-to-point protocol
A communications protocol used to connect computers to remote networking services including Internet service providers.

79. What are the two types of transmission technology available
(i) Broadcast and (ii) point-to-point

80. Difference between the communication and transmission.
Transmission is a physical movement of information and concern issues like bit polarity, synchronization, clock etc. Communication means the meaning full exchange of information between two communication media.