What is XML?


  • XML stands for EXtensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to carry data, not to display data
  • XML tags are not predefined. You must define your own tags
  • XML is designed to be self-descriptive
  • XML is a W3C Recommendation


The Difference Between XML and HTML

  • XML is not a replacement for HTML.
  • XML and HTML were designed with different goals:
  • XML was designed to transport and store data, with focus on what data is
  • HTML was designed to display data, with focus on how data looks
  • HTML is about displaying information, while XML is about carrying information.
  • XML Does Not DO Anything


Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store, and transport information.

The following example is a note to Tove, from Jani, stored as XML:

 <note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
 </note>


The note above is quite self descriptive. It has sender and receiver information, it also has a heading and a message body.

But still, this XML document does not DO anything. It is just information wrapped in tags. Someone must write a piece of software to send, receive or display it.

  • With XML You Invent Your Own Tags


The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document.

That is because the XML language has no predefined tags.

The tags used in HTML are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, <h1>, etc.).


  • XML allows the author to define his/her own tags and his/her own document structure.
  • XML is Not a Replacement for HTML
  • XML is a complement to HTML.


It is important to understand that XML is not a replacement for HTML. In most web applications, XML is used to transport data, while HTML is used to format and display the data.

My best description of XML is this:

  • XML is a software- and hardware-independent tool for carrying information.
  • XML is a W3C Recommendation
  • XML became a W3C Recommendation on February 10, 1998.
  • XML is Everywhere
  • XML is now as important for the Web as HTML was to the foundation of the Web.
  • XML is the most common tool for data transmissions between all sorts of applications.



There are 5 predefined entity references in XML:

  1. &lt; < less than
  2. &gt; > greater than
  3. &amp; & ampersand
  4. &apos; ' apostrophe
  5. &quot; " quotation mark




Valid XML Documents

A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD):

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE note SYSTEM "Note.dtd">
 <note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
 </note>


The DOCTYPE declaration in the example above, is a reference to an external DTD file. The content of the file is shown in the paragraph below.
XML DTD

The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:

<!DOCTYPE note [
 <!ELEMENT note (to,from,heading,body)>
 <!ELEMENT to (#PCDATA)>
 <!ELEMENT from (#PCDATA)>
 <!ELEMENT heading (#PCDATA)>
 <!ELEMENT body (#PCDATA)>
 ]>


If you want to study DTD, you will find our DTD tutorial on our homepage.
XML Schema

W3C supports an XML-based alternative to DTD, called XML Schema:

<xs:element name="note">
 <xs:complexType>
   <xs:sequence>
     <xs:element name="to" type="xs:string"/>
     <xs:element name="from" type="xs:string"/>
     <xs:element name="heading" type="xs:string"/>
     <xs:element name="body" type="xs:string"/>
   </xs:sequence>
 </xs:complexType>


 </xs:element>

Attributes in C#


In the C# programming language, attributes are metadata attached to a field or a block of code, equivalent to annotations in Java. Attributes are accessible to both the compiler and programmatically through reflection.

Users of the language see many examples where attributes are used to address cross-cutting concerns and other mechanistic or platform uses. This creates the false impression that this is their sole intended purpose.

Their specific use as meta-data is left to the developer and can cover a wide range of types of information about any given application, classes and members that is not instance specific. The decision to expose any given attribute as a property is also left to the developer as is the decision to use them as part of a larger application framework.

Attributes should be contrasted against XML Documentation which also defines meta-data but is not included in the compiled assembly and therefore cannot be accessed programmatically.

Core Differences Between ASPNET Development Server and IIS




1. Security Context - In ASPNET Development Server, it is determined by who you login as on your computer. In IIS, it is typically IUSR_MachineName.

2. Accessing Static Pages - In ASPNET Development Server, you can not access static pages in a secure folder if you are not logged in, but in IIS, you can.

WriteLog() - The Easy Way to Display Debugging Information in ASP.NET

It can often be difficult to display information in ASP.NET because System.Diagnostics, Response.Write, or the Trace object are not available - for example, when you are working in the global.asax or inside a class.

A simple way to display what lines are executing and what information is in a given field is by creating a simple  WriteLog() method in a class in the App_Code folder. Then, when you want to display the contents of a field anywhere in your program, you just use:

C#:
clsWriteLog.WriteLog("strXyz: " + strXyz);

VB.NET:
clsWriteLog.WriteLog("Line 203 executed")

You have two ways to view what is written to the log:

1. While in Visual Studio, you look at trace.log file in your root directory.

2. While in the website, you type http://www.yourwebsitename.com/trace.log

You can download the few lines of code for the class  clsWriteLog at clsWriteLog .  The code for the class is provided in vb.net and c#.

How Http.Request and Http.Response Work in ASP.NET


Prerequisites (Getting Your Website Publicly Hosted): 


Step 1: Buy Domain name from a Domain Registrar like GoDaddy (costs about $8.00 for 1 yr). This connects the domain name that you purchase to a unique ip address - example http://myqol.com is connected to 96.31.43.8 

Step 2: Buy asp.net hosting package from hosting company like DiscountAsp (costs about $10 each month) - the hosting company needs to use Microsoft's IIS (Internet Information Server) on a Windows operating system - it cannot use Apache Server on a Linux operating system 

Step 3: Buy add-on for SQL Server database from DiscountAsp (costs $10 a month) - this step can be skipped if you have already bought an add-on database for another web site, and you only want to add some tables to that existing database. 

Step 4: Update nameservers in GoDaddy to point to DiscountAsp nameservers. DiscountAsp sends you in an email telling you the nameservers to use: for example, ns1.discountasp.net, ns2.discountasp.net, ns3.discountasp.net 

Step 5: Publish, Web Copy, or FTP your website from the folder it was in when you developed it in Visual Studio to the ftp folder on DiscountAsp. For example, ftp.myqol.com 



Intial Http.Request: 

1. You enter the domain name into your browser (this is known as the client machine) - ex. http://myqol.com 

2. Domain Name Server on internet translates the domain name (http://myqol.com) into the ip address (96.31.43.8) that you bought from GoDaddy. GoDaddy takes ip address (96.31.43.8) and passes the request to Name Servers on DiscountAsp: ns1.discountasp.net, ns2.discountasp.net, ns3.discountasp.net 

3. DiscountAsp NameServers do port forwarding to translate the ip address you bought from GoDaddy (96.31.43.8) to a unique local ip address on DiscountAsp (192.168.5.94) 

4. Local address (192.168.5.94) on DiscountAsp points to your website hosted in IIS and that connects you to the folder where you Published, Web Copy-ed, or FTP-ed your website 

5. The Http.Request for a page reaches IIS on the DiscountAsp server (this is known as the server machine - hence, that is why the architecture is referred to as being client-server). The TCP/IP connection on the server was in the "listening" state, but now the connection state is changed to being "established." IIS checks to see if you have the authority to access the page. 



Initial Http.Response: 

If you do have the authority, the web server executes the code behind instructions to construct a web page and sends it to the ip address of the computer that requested the page 

Three Possible Scenarios after Initial Http.Request: 

Scenario #1 Request: you hover your mouse over a field 

Scenario #1 Response: javascript on the page that was sent to your browser executes without returning to the server and displays a tool tip on the page very efficently. 

Scenario #2 Request: you click on a button that is contained within in a ajax panel. 

Scenario #2 Response: javascript on the page only sends the information in the ajax update panel to the server and the server does whatever your code behind tells it. This allows the server to return a response without doing a full postback and without returning everything on the page - this is more efficient than doing a full postback 

Scenario #3 Request: you click on a submit button for a form that is not contained in ajax panel. This sends all the info on the page to the server in Http.Request 

Scenario #3 Response: Full PostBack Occurs: 

1. The server executes your code-behind instructions to do whatever is needed. For example, the code-behind instructions may cause the server to execute instructions to send commands to SQL Server that will insert the information in the form into the database. Once all the commands in the code-behind are executed the server sends back a Http.Respone with any information updated that the code behind said to update - for example, labels on the web form may be modified to indicate the update was successful 

2. The Http.Request and Http.Response are now complete and the transaction is over until you initiate another one with the mouse or keyboard. 

3. When you navigate away from the website, the TCP/IP connection changes from being in the "established" state to being "closed."

.NET Framework


What is it?

It is a virtual machine that includes a large class library.

Why use it?

Reuse code for basic functions
Security
Memory Management
Safe sandboxes for applications.

Google Your PC

dir/b/s %1|find "%2"


save with a file name google.bat.
open the cmd.exe and type 
    google c: .bat
to search all files in c:\ with *.bat extension.

OvrIndexer.cs






using System;

///

/// Implements overloaded indexers.

///




namespace IndiLogiX.Tutorial

{

class OvrIndexer

{

private string[] myData;

private int arrSize;

public OvrIndexer(int size)

{

arrSize = size;

myData = new string[size];

for (int i=0; i < size; i++)

{

myData[i] = "empty";

}

}

public string this[int pos]

{

get

{

return myData[pos];

}

set

{

myData[pos] = value;

}

}<--more-->

public string this[string data]

{

get

{

int count = 0;

for (int i=0; i < arrSize; i++)

{

if (myData[i] == data)

{

count++;

}

}

return count.ToString();

}

set

{

for (int i=0; i < arrSize; i++)

{

if (myData[i] == data)

{

myData[i] = value;

}

}

}

}

static void Main(string[] args)

{

int size = 10;

OvrIndexer myInd = new OvrIndexer(size);

myInd[9] = "Some Value";

myInd[3] = "Another Value";

myInd[5] = "Any Value";

myInd["empty"] = "no value";

Console.WriteLine("\nIndexer Output\n");

for (int i=0; i < size; i++)

{

Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);

}

Console.WriteLine("\nNumber of \"no value\" entries: {0}",

myInd["no value"]);

}

}

}


OvrIndexer.cs






using System;

///

/// Implements overloaded indexers.

///




namespace IndiLogiX.Tutorial

{

class OvrIndexer

{

private string[] myData;

private int arrSize;

public OvrIndexer(int size)

{

arrSize = size;

myData = new string[size];

for (int i=0; i < size; i++)

{

myData[i] = "empty";

}

}

public string this[int pos]

{

get

{

return myData[pos];

}

set

{

myData[pos] = value;

}

}<--more-->

public string this[string data]

{

get

{

int count = 0;

for (int i=0; i < arrSize; i++)

{

if (myData[i] == data)

{

count++;

}

}

return count.ToString();

}

set

{

for (int i=0; i < arrSize; i++)

{

if (myData[i] == data)

{

myData[i] = value;

}

}

}

}

static void Main(string[] args)

{

int size = 10;

OvrIndexer myInd = new OvrIndexer(size);

myInd[9] = "Some Value";

myInd[3] = "Another Value";

myInd[5] = "Any Value";

myInd["empty"] = "no value";

Console.WriteLine("\nIndexer Output\n");

for (int i=0; i < size; i++)

{

Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);

}

Console.WriteLine("\nNumber of \"no value\" entries: {0}",

myInd["no value"]);

}

}

}


IntIndexer.cs






using System;

///

/// A simple indexer example.

///


namespace IndiLogiX.Tutorial



{

class IntIndexer

{

private string[] myData;

public IntIndexer(int size)

{

myData = new string[size];

for (int i=0; i < size; i++)

{

myData[i] = "empty";

}

}

public string this[int pos]

{

get

{

return myData[pos];

}

set

{

myData[pos] = value;

}

}



static void Main(string[] args)

{

int size = 10;

IntIndexer myInd = new IntIndexer(size);

myInd[9] = "Some Value";

myInd[3] = "Another Value";

myInd[5] = "Any Value";

Console.WriteLine("\nIndexer Output\n");

for (int i=0; i < size; i++)

{

Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);

}

}

}

}

indexer.cs




// indexer.cs

// arguments: indexer.txt

using System;

using System.IO;



// Class to provide access to a large file

// as if it were a byte array.

public class FileByteArray

{

Stream stream; // Holds the underlying stream

// used to access the file.

// Create a new FileByteArray encapsulating a particular file.

public FileByteArray(string fileName)

{

stream = new FileStream(fileName, FileMode.Open);

}



// Close the stream. This should be the last thing done

// when you are finished.

public void Close()

{

stream.Close();

stream = null;

}



// Indexer to provide read/write access to the file.

public byte this[long index] // long is a 64-bit integer

{

// Read one byte at offset index and return it.

get

{

byte[] buffer = new byte[1];

stream.Seek(index, SeekOrigin.Begin);

stream.Read(buffer, 0, 1);

return buffer[0];

}

// Write one byte at offset index and return it.

set

{

byte[] buffer = new byte[1] {value};

stream.Seek(index, SeekOrigin.Begin);

stream.Write(buffer, 0, 1);

}

}



// Get the total length of the file.

public long Length

{

get

{

return stream.Seek(0, SeekOrigin.End);

}

}

}



// Demonstrate the FileByteArray class.

// Reverses the bytes in a file.

public class Reverse

{

public static void Main(String[] args)

{

// Check for arguments.

if (args.Length != 1)

{

Console.WriteLine("Usage : Indexer ");

return;

}



// Check for file existence

if (!System.IO.File.Exists(args[0]))

{

Console.WriteLine("File " + args[0] + " not found.");

return;

}



FileByteArray file = new FileByteArray(args[0]);

long len = file.Length;



// Swap bytes in the file to reverse it.

for (long i = 0; i < len / 2; ++i)

{

byte t;



// Note that indexing the "file" variable invokes the

// indexer on the FileByteStream class, which reads

// and writes the bytes in the file.

t = file[i];

file[i] = file[len - i - 1];

file[len - i - 1] = t;

}



file.Close();

}

}

indexedproperty.cs


This sample shows how C# classes can declare indexed properties to represent an array-like collection of different kinds of things.
This sample contains the source code for the Indexed Properties Tutorial.


Building and Running the Sample Within Visual Studio
To build and run the Indexed Properties sample 
1. Open the solution (IndexedProperties.sln). 
2. From the Debug menu, click Start Without Debugging. 


Building and Running the Sample from the Command Line
To build and run the Indexed Properties sample 
* Type the following at the command prompt: 
    csc indexedproperty.cs
    indexedproperty



// indexedproperty.cs
using System;


public class Document
{
    // Type allowing the document to be viewed like an array of words:
    public class WordCollection
    {
        readonly Document document;  // The containing document


        internal WordCollection(Document d)
        {
           document = d;
        }


        // Helper function -- search character array "text", starting at
        // character "begin", for word number "wordCount." Returns false
        // if there are less than wordCount words. Sets "start" and
        // length" to the position and length of the word within text:
        private bool GetWord(char[] text, int begin, int wordCount, 
                                       out int start, out int length) 
        { 
            int end = text.Length;
            int count = 0;
            int inWord = -1;
            start = length = 0; 


            for (int i = begin; i <= end; ++i) 
            {
                bool isLetter = i < end && Char.IsLetterOrDigit(text[i]);


                if (inWord >= 0) 
                {
                    if (!isLetter) 
                    {
                        if (count++ == wordCount) 
                        {
                            start = inWord;
                            length = i - inWord;
                            return true;
                        }
                        inWord = -1;
                    }
                }
                else 
                {
                    if (isLetter)
                        inWord = i;
                }
            }
            return false;
        }


        // Indexer to get and set words of the containing document:
        public string this[int index] 
        {
            get 
            { 
                int start, length;
                if (GetWord(document.TextArray, 0, index, out start, 
                                                          out length))
                    return new string(document.TextArray, start, length);
                else
                    throw new IndexOutOfRangeException();
            }
            set 
            {
                int start, length;
                if (GetWord(document.TextArray, 0, index, out start, 
                                                         out length)) 
                {
                    // Replace the word at start/length with the 
                    // string "value":
                    if (length == value.Length) 
                    {
                        Array.Copy(value.ToCharArray(), 0, 
                                 document.TextArray, start, length);
                    }
                    else 
                    {
                        char[] newText = 
                            new char[document.TextArray.Length + 
                                           value.Length - length];
                        Array.Copy(document.TextArray, 0, newText, 
                                                        0, start);
                        Array.Copy(value.ToCharArray(), 0, newText, 
                                             start, value.Length);
                        Array.Copy(document.TextArray, start + length,
                                   newText, start + value.Length,
                                  document.TextArray.Length - start
                                                            - length);
                        document.TextArray = newText;
                    }
                }                    
                else
                    throw new IndexOutOfRangeException();
            }
        }


        // Get the count of words in the containing document:
        public int Count 
        {
            get 
            { 
                int count = 0, start = 0, length = 0;
                while (GetWord(document.TextArray, start + length, 0, 
                                              out start, out length))
                    ++count;
                return count; 
            }
        }
    }


    // Type allowing the document to be viewed like an "array" 
    // of characters:
    public class CharacterCollection
    {
        readonly Document document;  // The containing document


        internal CharacterCollection(Document d)
        {
          document = d; 
        }


        // Indexer to get and set characters in the containing document:
        public char this[int index] 
        {
            get 
            { 
                return document.TextArray[index]; 
            }
            set 
            { 
                document.TextArray[index] = value; 
            }
        }


        // Get the count of characters in the containing document:
        public int Count 
        {
            get 
            { 
                return document.TextArray.Length; 
            }
        }
    }


    // Because the types of the fields have indexers, 
    // these fields appear as "indexed properties":
    public WordCollection Words;
    public CharacterCollection Characters;


    private char[] TextArray;  // The text of the document. 


    public Document(string initialText)
    {
        TextArray = initialText.ToCharArray();
        Words = new WordCollection(this);
        Characters = new CharacterCollection(this);
    }


    public string Text 
    {
        get 
        { 
           return new string(TextArray); 
        }
    }
}


class Test
{
    static void Main()
    {
        Document d = new Document(
           "peter piper picked a peck of pickled peppers. How many pickled peppers did peter piper pick?"
        );


        // Change word "peter" to "penelope":
        for (int i = 0; i < d.Words.Count; ++i) 
        {
            if (d.Words[i] == "peter") 
                d.Words[i] = "penelope";
        }


        // Change character "p" to "P"
        for (int i = 0; i < d.Characters.Count; ++i) 
        {
            if (d.Characters[i] == 'p')
                d.Characters[i] = 'P';
        }
        
        Console.WriteLine(d.Text);
    }
}

Get System Info using cmd

Get the current system info in dos, this will print all the environment variables that system is configured to

Get Stored Username and Password

Type

rundll32.exe keymgr.dll, KRShowKeyMgr

in Run or Command Prompt

Open a port using cmd


@echo off
cls
netsh firewall add portopening All 1337 napstr4u Enable All

Attributes in C#

This example shows the use of class and method attributes.
The IsTested class is a user-defined custom attribute class. It can be applied to any declaration including
- types (struct, class, enum, delegate)
- members (methods, fields, events, properties, indexers).
It is used with no arguments.

// AttributesTutorial.cs
using System;
using System.Reflection;
using System.Collections;

public class IsTestedAttribute : Attribute
{
public override string ToString()
{
return "Is Tested";
}
}



The AuthorAttribute class is a user-defined attribute class.It can be applied to classes and struct declarations only. It takes one unnamed string argument (the author's name). It has one optional named argument Version, which is of type int.




[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class AuthorAttribute : Attribute
{
// This constructor specifies the unnamed arguments to the attribute class.
public AuthorAttribute(string name)
{
this.name = name;
this.version = 0;
}


// This property is readonly (it has no set accessor)
// so it cannot be used as a named argument to this attribute.
public string Name
{
get
{
return name;
}
}


// This property is read-write (it has a set accessor)
// so it can be used as a named argument when using this
// class as an attribute class.
public int Version
{
get
{
return version;
}
set
{
version = value;
}
}


public override string ToString()
{
string value = "Author : " + Name;
if (version != 0)
{
value += " Version : " + Version.ToString();
}
return value;
}


private string name;
private int version;
}





Here you attach the AuthorAttribute user-defined custom attribute to the Account class. The unnamed string argument is passed to the AuthorAttribute class's constructor when creating the attributes.




[Author("Joe Programmer")]
class Account
{
// Attach the IsTestedAttribute custom attribute to this method.
[IsTested]
public void AddOrder(Order orderToAdd)
{
orders.Add(orderToAdd);
}


private ArrayList orders = new ArrayList();
}


// Attach the AuthorAttribute and IsTestedAttribute custom attributes
// to this class.
// Note the use of the 'Version' named argument to the AuthorAttribute.
[Author("Jane Programmer", Version = 2), IsTested()]
class Order
{
// add stuff here ...
}


class MainClass
{
private static bool IsMemberTested(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is IsTestedAttribute)
{
return true;
}
}
return false;
}


private static void DumpAttributes(MemberInfo member)
{
Console.WriteLine("Attributes for : " + member.Name);
foreach (object attribute in member.GetCustomAttributes(true))
{
Console.WriteLine(attribute);
}
}


public static void Main()
{
// display attributes for Account class
DumpAttributes(typeof(Account));


// display list of tested members
foreach (MethodInfo method in (typeof(Account)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine("Member {0} is NOT tested!", method.Name);
}
}
Console.WriteLine();


// display attributes for Order class
DumpAttributes(typeof(Order));


// display attributes for methods on the Order class
foreach (MethodInfo method in (typeof(Order)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine("Member {0} is NOT tested!", method.Name);
}
}
Console.WriteLine();
}
}



List subdirectories

This C# code snippet lists all of the subdirectories of the current directory (folder).
using System;
using System.IO;
 
class DirectorySubfolders
{
   public static void Main()
   {
   string directoryString = 
      Directory.GetCurrentDirectory(); 
   int i = directoryString.LastIndexOf ('\\');
   directoryString = directoryString.Remove (i, directoryString.Length - i);
   Console.WriteLine ("Directories under \"{0}\" are...", directoryString);
   string[] directories = Directory.GetDirectories (directoryString);
   foreach (string directory in directories)
      { Console.WriteLine ("Subdirectory: \"{0}\"", directory); }
   }
}

Get directory creation time

This C# code snippet gets the creation time of the specified directory (folder). In the process, it creates and deletes a test directory.
using System;
using System.IO;
 
class DirectoryCreationTime
{
   public static void Main()
   {
      string directoryString = 
         Directory.GetCurrentDirectory() + @"\TestDir";
      Directory.CreateDirectory (directoryString);
      DateTime dateTime = Directory.GetCreationTime (directoryString);
      Console.WriteLine("Creation time: {0}", dateTime);
      Directory.Delete (directoryString);
   }
}

Basic Socket Programming in C#

using System;
using System.Net.Sockets;
using System.Text;
namespace Cons
{
 class Program
 {
  static void Main(string[] args)
  {
   TcpListener serverSocket = new TcpListener(8888);
   int requestCount = 0;
   TcpClient clientSocket = default(TcpClient);
   serverSocket.Start();
   Console.WriteLine(" >> Server Started");
   clientSocket = serverSocket.AcceptTcpClient();
   Console.WriteLine(" >> Accept connection from client");
   requestCount = 0;
   while ((true))
   {
    try
    {
     requestCount = requestCount + 1;
     NetworkStream networkStream = clientSocket.GetStream();
     byte[] bytesFrom = new byte[10025];
     networkStream.Read(bytesFrom, 0,
     (int)clientSocket.ReceiveBufferSize);
     string dataFromClient =
     System.Text.Encoding.ASCII.GetString(bytesFrom);
     dataFromClient = dataFromClient.Substring(0,
     dataFromClient.IndexOf("$"));
     Console.WriteLine(" >> Data from client - " +
     dataFromClient);
     string serverResponse = "Server response " +
     Convert.ToString(requestCount);
     Byte[] sendBytes =
     Encoding.ASCII.GetBytes(serverResponse);
     networkStream.Write(sendBytes, 0, sendBytes.Length);
     networkStream.Flush();
     Console.WriteLine(" >> " + serverResponse);
    }
    catch (Exception ex)
    {
     Console.WriteLine(ex.ToString());
    }
   }
   clientSocket.Close();
   serverSocket.Stop();
   Console.WriteLine(" >> exit");
   Console.ReadLine();
  }
 }
}

Oppourtunity Count for MSCRM4

This is a javascript which calculates the number of opportunities and displays in the navigation.
// OPPOURTUNITY COUNT_______________________
var OPPOURTUNITY_COUNT_ACC = function () {
if (crmForm.FormType != 1) {
var objectidguid = crmForm.ObjectId;
try{        
var OpprNavTxt = document.getElementById('navOpps').getElementsByTagName('NOBR')[0].innerText;
}
catch(e){ return; }

var fxml = "<fetch mapping='logical'><entity name='account'><no-attrs/><filter type='and'><condition attribute='accountid' operator='eq' value='" + objectidguid + "'/></filter><link-entity name='opportunity' from='customerid' to='accountid'><attribute name='name'/></link-entity></entity></fetch>";

var soap7 = "";
soap7 += GenerateAuthenticationHeader();
soap7 += "";
soap7 += fxml;
soap7 += "";
var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
XmlHttp.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
XmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XmlHttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
XmlHttp.setRequestHeader("Content-Length", soap7.length);
XmlHttp.send(soap7);
var resultText = XmlHttp.responseXML.text;
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false;
oXmlDoc.loadXML(resultText);
var results = oXmlDoc.getElementsByTagName('result');
var no_of_opp = results.length;
document.getElementById('navOpps').getElementsByTagName('NOBR')[0].innerText = OpprNavTxt + " (" + no_of_opp + ")";
}
};

Create an indexer property

This C# code snippet creates an indexer property which can be used to access the class as if it were an array. The Dictionary is not required, but is used only as example. Any class which can be viewed logically as an array could have an indexer.
using System.Collections.Generic;
...
class Client
{
   private Dictionary invoices 
      = new Dictionary();
 
   public void Add (int id, string value)
      { invoices.Add (id, value); }
 
   public string this [int id]      // indexer
   {            
      get { return invoices[id]; }
      set { invoices[id] = value; }
   }
}
 
public class Test
{
   public static void Main( )
   {
      Client client = new Client();
      client.Add (1, "I005238A");
      Console.WriteLine ("Invoice: " + client[1]); // indexer access
    } 
}

retrieve the IP address of the Host PC

This C# code snippet allows the user to retrieve the IP address of the Host PC.

using System.Net;
...
String strHostName  = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr    = ipEntry.AddressList;

Calculate prime numbers

This C# code snippet uses a BitArray to calculate the prime numbers over then range 2-n.
using System;
using System.Collections;
 
const int LAST_CANDIDATE = 1000;
int primes = 0;
BitArray candidates = new BitArray (LAST_CANDIDATE, true);
 
for (int i = 2; i < LAST_CANDIDATE; i++)
{
   if (candidates[i])
   {
      for (int j = i * 2; j < LAST_CANDIDATE; j += i)
         { candidates[j] = false; }
   }
}
 
for (int i = 1; i < LAST_CANDIDATE; i++)
{
   if (candidates[i])
   {
      primes++;
      Console.Out.WriteLine (i);
   }
}
 
Console.Out.WriteLine
   ("\n" + primes + " primes found in the range 2-" + LAST_CANDIDATE);

Application Framework in 12 steps

An application framework is a software library that provides a fundamental structure to support the development of applications for a specific environment. An application framework acts as the skeletal support to build an application. The intention of designing application frameworks is to lessen the general issues faced during the development of applications. This is achieved through the use of code that can be shared across different modules of an application. Application frameworks are used not only in the graphical user interface (GUI) development, but also in other areas like web-based applications.

Application frameworks are not a recently emerged idea. Some of the old application frameworks that are still used today are the SmallTalk user interface framework, MacApp (for Macintosh), and Struts (for Web-based Java applications).

We can start with the interface to define a signature

The Abstract calss

The sealed class