Saturday, 27 October 2012

C# Get Started

C# Language Fundamentals

Topics
Overview of a C# Program: In addition to the basic elements that comprise a C# program, a developer needs to be aware of other .NET features such as commenting options and recommended naming conventions.
  • Primitives: Primitives are the basic data types defined by the FCL to represent numbers, characters, and dates.
  • Operators: C# uses traditional operator syntax to perform arithmetic and conditional operations.
  • Program Flow Statements: Program flow can be controlled using if and switch statements for selection; and while, do, for, and foreach clauses for iteration.
  • String: The string class supports the expected string operations: concatenation, extracting substrings, searching for instances of a character pattern, and both case sensitive and insensitive comparisons.
  • Enums: An enumeration is a convenient way to assign descriptions that can be used to reference an underlying set of values.
  • Using Arrays: Single- or multi-dimensional arrays of any type can be created in C#. After an array is created, the System.Array class can be used to sort and copy the array.
  • Reference and Value Types: All types in .NET are either a value or reference type. It is important to understand the differences and how they can affect a program's performance.

2.1. The Layout of a C# Program

Figure 2-1 illustrates some of the basic features of a C# program.
Figure 2-1. Basic elements of a C# program


The code in Figure 2-1 consists of a class MyApp that contains the program logic and a class Apparel that contains the data. The program creates an instance of Apparel and assigns it to myApparel. This object is then used to print the values of the class members FabType and Price to the console. The important features to note include the following:
  1. The using statement specifies the namespace System. Recall from Chapter 1, "Introduction to .NET and C#," that the .NET class libraries are organized into namespaces and that the System namespace contains all of the simple data types. The using statement tells the compiler to search this namespace when resolving references, making it unnecessary to use fully qualified names. For example, you can refer to label rather than System.Web.UI.WebControls.Label.
  2. All programming logic and data must be contained within a type definition. All program logic and data must be embedded in a class, structure, enum, interface, or delegate. Unlike Visual Basic, for instance, C# has no global variable that exists outside the scope of a type. Access to types and type members is strictly controlled by access modifiers. In this example, the access modifier public permits external classes—such as MyApp—to access the two members of the Apparel class.
  3. A Main() method is required for every executable C# application. This method serves as the entry point to the application; it must always have the static modifier and the M must be capitalized. Overloaded forms of Main()define a return type and accept a parameter list as input.
    Return an integer value:
    static int Main()
    
    {
    
       return 0; // must return an integer value
    
    }
    
    

    Receive a list of command-line arguments as a parameter and return an integer value:
    static int Main(string[] args)
    
    {
    
       // loop through arguments
    
       foreach(string myArg in args)
    
          Console.WriteLine(myArg);
    
       return 0;
    
    }
    
    

    The parameter is a string array containing the contents of the command line used to invoke the program. For example, this command line executes the program MyApparel and passes it two parameter values:
    C:\> MyApparel 5 6
    
    
Core Note
The contents of the command line are passed as an argument to the Main() method. The System.Environment.CommandLine property also exposes the command line's contents.

General C# Programming Notes

Case Sensitivity
All variable and keywords are distinguished by case sensitivity. Replace class with Class in Figure 2-1 and the code will not compile.
Naming Conventions
The ECMA standard provides naming convention guidelines to be followed in your C# code. In addition to promoting consistency, following a strict naming policy can minimize errors related to case sensitivity that often result from undisciplined naming schemes. Table 2-1 summarizes some of the more important recommendations.
Table 2-1. C# Naming Conventions
Type
Case
Notes and Examples
Class
Pascal
  • Use noun or noun phrases.
  • Try to avoid starting with I because this is reserved for interfaces.
  • Do not use underscores.
Constant
Pascal
public const double GramToPound = 454.0 ;
Enum Type
Pascal
  • Use Pascal case for the enum value names.
  • Use singular name for enums.
public enum WarmColor { Orange, Yellow, Brown}
Event
Pascal
  • The method that handles events should have the suffix EventHandler.
  • Event argument classes should have the suffix EventArgs.
Exception
Pascal
  • Has suffix Exception.
Interface
Pascal
  • Has prefix of I.
IDisposable
Local Variable
Camel
  • Variables with public access modifier use Pascal
int myIndex.
Method
Pascal
  • Use verb or verb phrases for name.
Namespace
Pascal
  • Do not have a namespace and class with the same name.
  • Use prefixes to avoid namespaces having the same name. For example, use a company name to categorize namespaces developed by that company.
Acme.GraphicsLib
Property
Pascal
  • Use noun or noun phrase.
Parameter
Camel
  • Use meaningful names that describe the parameter's purpose.


Note that the case of a name may be based on two capitalization schemes:
  1. Pascal. The first character of each word is capitalized (for example, MyClassAdder).
  2. Camel. The first character of each word, except the first, is capitalized (for example, myClassAdder).
The rule of thumb is to use Pascal capitalization everywhere except with parameters and local variables.
Commenting a C# Program
The C# compiler supports three types of embedded comments: an XML version and the two single-line (//) and multi-line (/* */) comments familiar to most programmers:
//   for a single line 

/*   for one or more lines

                      */

/// <remarks> XML comment describing a class </remarks>


An XML comment begins with three slashes (///) and usually contains XML tags that document a particular aspect of the code such as a structure, a class, or class member. The C# parser can expand the XML tags to provide additional information and export them to an external file for further processing.

Table 2-2. XML Documentation Tags
Tag
Description
<example>
Text illustrating an example of using a particular program feature goes between the beginning and ending tags.
<exception cref="Excep">
cref attribute contains name of exception.
///<exceptioncref="NoParmException">

</exception>

<include file="myXML">
file attribute is set to name of another XML file that is to be included in the XML documentation produced by this source code.
<param name="parm1">
name attribute contains the name of the parameter.
<permission cref= "">
Most of the time this is set to the following:
///<permissioncref="System.Security.Permis-

sionSet"> </permission>

<remarks>
Provides additional information about a type not found in the <summary> section.
<returns>
Place a textual description of what is returned from a method or property between the beginning and ending tags.
<seealso cref="price">
The cref attribute is set to the name of an associated type, field, method, or other type member.
<summary>
Contains a class description; is used by IntelliSense in VisualStudio.NET.


The value of the XML comments lies in the fact that they can be exported to a separate XML file and then processed using standard XML parsing techniques. You must instruct the compiler to generate this file because it is not done by default.
The following line compiles the source code consoleapp.cs and creates an XML file consoleXML:
C:\> csc consoleapp.cs /doc:consoleXML.xml

C# Language Fundamentals

Topics
Overview of a C# Program: In addition to the basic elements that comprise a C# program, a developer needs to be aware of other .NET features such as commenting options and recommended naming conventions.
  • Primitives: Primitives are the basic data types defined by the FCL to represent numbers, characters, and dates.
  • Operators: C# uses traditional operator syntax to perform arithmetic and conditional operations.
  • Program Flow Statements: Program flow can be controlled using if and switch statements for selection; and while, do, for, and foreach clauses for iteration.
  • String: The string class supports the expected string operations: concatenation, extracting substrings, searching for instances of a character pattern, and both case sensitive and insensitive comparisons.
  • Enums: An enumeration is a convenient way to assign descriptions that can be used to reference an underlying set of values.
  • Using Arrays: Single- or multi-dimensional arrays of any type can be created in C#. After an array is created, the System.Array class can be used to sort and copy the array.
  • Reference and Value Types: All types in .NET are either a value or reference type. It is important to understand the differences and how they can affect a program's performance.

Thursday, 25 October 2012

SQL XML .NET Data Provider


SQL XML .NET Data Provider

SqlXmlCommand belongs to Microsoft.Data.SqlXml namespace, which is not part of .NET framework. The extra functionality SqlXmlCommand provides are: you can send a XPATH query instead of a SELECT SQL query to database to retrieve data, and submit changes to database using a diffgram XML document.
When you provide a XPATH to the command, it converts it to a “FOR XML” SQL query. When you submit a diffgram, the command generates a batch of SQL queries wrapped in a transaction. In both cases the command needs to know the schema of the table to be able to generate those SQL queries, so you need to provide the command with a XSD file:
' Retrieve data using XPATH
Dim cmd As New SqlXmlCommand(“Orders[CustomerID=’GROSR’]”, strConn)
cmd.SchemaPath = “C:\MySchema.xsd”
cmd.CommandType = SqlXmlCommandType.XPath
Dim rdr As XmlReader = cmd.ExecuteXmlReader()
mds.ReadXml(rdr)

' Do some changes

' Write the changed dataset into a DiffGram
mds.WriteXml(“C:\MyDiffGram.xml”XmlWriteMode.DiffGram)

' Submit the DiffGram
cmd = New SqlXmlCommand(strConn)
cmd.SchemaPath = “C:\MySchema.xsd”
cmd.CommandType = SqlXmlCommandType.DiffGram
cmd.CommandStream = New FileStream(“C:\MyDiffGram.xml”, FileMode.Open, FileAccess.Read)
cmd.ExecuteNonQuery