C# Question Answers

Which class represents a hash algorithm used strictly for data integrity?
The MD5 Class

Which class grants a dynamically-generated FileIOPermission to the directory from which the code is executed?
The FileCodeGroup class

Which enumeration indicated whether an access rule is to allow or deny access?
The AccessControlType enumeration

What should you apply to a method for it to execute while an object is converted to a stream of bytes?
OnSerializing attribute to the method

Which class should you use to paint filled shapes and text in GDI+?
Brush

Which assembly attribute should you apply to indicate the keys used when compiling a strong-named assembly?
AssemblyKeyFile

Which property of the Process class returns the name of the computer on which the process is running?
MachineName property

Which method of the CodeGroup class will determine the policy for the code group based on the specified evidence?
Resolve method

Which two values of the ConfiguratinoUserLevel enumeration indicate a user-specific configuration?
PerUserRoaming and PerUserRomaingAndLocal values.

When should you use a queue?
When organizing elements according to the First In, First Out (FIFO) method

Which attribute should you apply to a parameter or return type to force marshalling into a specific COM data type?
MarshalAs attribute

Which method should you place a core code in a Windows Service?
OnStart

Which interface should you implement to enable sorting a class?
IComparable

Which command line tool allows users to modify security permissions, permission sets and code groups for an assembly?
Caspol.exe tool

Which method is used to run a thread?
Start

Which permission class controls access to managed types at runtime?
The ReflectionPermission class

Which property of the IPrincipal interface should you use to retrieve the underlying identity?
Identity

Which method should you invoke on the ThreadPool class to add a delegate?
QueueUserWorkItem

Which property of the Attachment class is used to the MIME type of an e-mail attachment?
ContentType

Which enumeration indicates the type of cultures installed on a local machine?
CultureTypes

How should you alter the name of an XML element generated from a field?
You should apply the XmlElement attribute and specify the new name.

Which property of the Process class returns all libraries loaded by the current process?
Modules

Which method of the LinkedList class should be invoked to add an object to the beginning?
AddFirst

Which method of CodeGroup class will duplicate a code group?
Copy

Which property of the AppDomain class should you use to access the startup path?
BaseDirectory

Which method of the AppDomain class will create an application domain?
CreateDomain

Which class represents the file instance on a computer’s file system?
FileInfo

Which class should you use to access information about all drives on a local system?
DriveInfo

Which enumeration specifies the text encoding when applying the DllImport attribute
Charset

What is an exception?
An exception is an abnormal condition at runtime resulting from an error or unexpected operation

Which method of the Assembly class should you invoke to retrieve the assembly instance that invoked the currently executing code?
GetCallingAssembly

How do you invoke the method(s) to which a delegate references?
Invoke the Invoke method, specifying the arguments required by the delegate

What should you apply to a class to indicate its objects can be converted into a contiguous stream of bytes?
Serializable

What is WQL?
WMI Query Language a subset of SQL, specifically designed to query managed WMI instances.

Which attribute should you apply to uniquely identify a COM interface or class in the registry?
GUID

Which class represents specific managed instances available through WMI (Windows Management Instrumentation)?
ManagementObject class

Which CharSet enumeration value is the default text encoding when using WindowsNT,Win2K,WinXP,Win2003 server?
CharSet.Unicode value

What should you apply to a field if its value is not required during deserialization?
OptionalField

Which CharSet enumeration value is the default text encoding when using Win9x, Windows Me?
Charset.Ansi

Which method of the FileStream class should be invoked when work is completed with a file’s contents?
Close


Which class should you use to retrieve methods of a dynamically loaded type at runtime?
MemberInfo

Which class represents an e-mail message?
MailMessage

Which interface should you implement when defining a class responsible for the format of serialized data types?
IFormatter

What object is required when invoking either the Write or Read of the GZipStream or DeflateStream classess?
Byte Array

When defining a CLR class, which two ways can you expose its methods to COM clients?
Apply Classinterface attribute or implement a custom class interface

Which method of the StreamWriter class should you invoke to clear all buffers and force data in the buffer to be written?
Flush

Which class represents an application domain?
AppDomain

Which element in the application configuration file should you use to specify BooleanSwitch or TraceSwitch objects?
Switches

When exposing managed methods to COM, what access modifier must you apply?
Public

Which class should you use inside a method to restrict access based upon an identity or role membership?
PrincipalPermission

Executing a Recursive Query

using System;
using System.Data;
using System.Data.SqlClient;

namespace ExecuteRecursiveQuery
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";

string sqlSelect =
"WITH DirectReports( " +
"ManagerID, EmployeeID, Title, FirstName, LastName, EmployeeLevel) AS " +
"(SELECT e.ManagerID, e.EmployeeID, e.Title, c.FirstName, c.LastName, " +
"0 AS EmployeeLevel " +
"FROM HumanResources.Employee e " +
"JOIN Person.Contact AS c ON e.ContactID = c.ContactID " +
"WHERE ManagerID IS NULL " +
"UNION ALL " +
"SELECT e.ManagerID, e.EmployeeID, e.Title, c.FirstName, c.LastName, " +
"EmployeeLevel + 1 " +
"FROM HumanResources.Employee e " +
"INNER JOIN DirectReports d ON e.ManagerID = d.EmployeeID " +
"JOIN Person.Contact AS c ON e.ContactID = c.ContactID) " +
"SELECT TOP 20 * " +
"FROM DirectReports";

// Fill the DataTable
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.Fill(dt);

Console.WriteLine("MgrID\tEmpID\tTitle\t\t\tLevel\tName");
foreach (DataRow row in dt.Rows)
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}, {5}",
row["ManagerID"],row["EmployeeID"],
row["Title"].ToString().PadRight(23).Substring(0,23),
row["EmployeeLevel"], row["LastName"], row["FirstName"]);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

ADO.NET 3.5

Follow these steps to use the O/R Designer to generate a simple C# object model:

Open Visual Studio and create a console application named LinqToSql.

Right-click the project in the Solution Explorer pane and select Add New Item…from the context menu to open the Add New Item dialog. Select the Linq to SQL file template in the Data category. Change the Name to MyDataClasses.dbml. Click the Add button to close the Add New Item dialog. The empty design surface for the new dbml file appears, representing the DataContext that you will configure next. LINQ to SQL files have the extension .dbml.

In Server Explorer, right-click on the Data Connections node and select Add Connection from the context menu to open the Add Connection dialog. Complete the dialog to create a connection to the AdventureWorks database on your SQL Server. Click OK to close the dialog and create the connection.

Expand the new data connection in the Data Connections node. Drag the Product (Production) table from the table subnode onto the O/R Designer design surface to create the entity class Product—the new class contains properties corresponding to columns in the Product table. Next, drag the ProductInventory (Production) table onto the design surface to create the entity class ProductInventory. Notice that an association (relationship) is automatically created between the two entities based on the database metadata. The design surface is shown in Figure A-21.

Build the project.

Open the Data Sources pane by selecting Data Show Data Sources from the main menu. Click the Add New Data Source link to open the Data Source Configuration Wizard dialog. Select Object as the data source type. Click Next.

Expand the LinqToSql node. Navigate to and select the Product class. Click Next. Click Finish to confirm that you want to add the Product entity class. The Product and its related ProductInventory classes are added to the Data Sources pane, as shown in Figure A-22.

Next, create the LINQ to SQL query to return data from the Product table using the Product entity class. The completed C# code for Program.cs is shown in the following example:

using System;
using System.Linq;

namespace LinqToSql
{

class Program
{
static void Main(string[] args)
{
MyDataClassesDataContext dc =
new MyDataClassesDataContext();

var products = from row in dc.Products
where row.ProductID < 100
select row;

foreach (Product p in products)
Console.WriteLine(p.ProductID + ": " + p.Name);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Serializing Data

using System;
using System.Data;
using System.Data.SqlClient;
// Namespaces used for serialization
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;

namespace SerializeData
{
class Program
{
static void Main(string[] args)
{
string fileName = @"..\..\..\SerializedDataSet";
Stream stream;

string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";

string sqlSelect = "SELECT * FROM Production.Product;" +
"SELECT * FROM Production.ProductInventory";

DataSet ds = new DataSet( );
SqlDataAdapter da;

// Fill the Header table in the DataSet
da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "Product");
da.TableMappings.Add("Table1", "ProductInventory");
da.FillSchema(ds, SchemaType.Mapped);
da.Fill(ds);

// Relate the Header and Order tables in the DataSet
DataRelation dr = new DataRelation("Product_ProductInventory",
ds.Tables["Product"].Columns["ProductID"],
ds.Tables["ProductInventory"].Columns["ProductID"]);
ds.Relations.Add(dr);

// Serialize using DataSet.WriteXml( )
using (stream = File.Open(fileName + "_1.xml", FileMode.Create,
FileAccess.Write))
{
ds.WriteXml(stream, XmlWriteMode.WriteSchema);
Console.WriteLine(
"DataSet serialized using DataSet.WriteXml( ) to {0}_1.xml",
fileName);
}

// Serialize using XmlSerializer
using (stream = File.Open(fileName + "_2.xml", FileMode.Create,
FileAccess.Write))
{
XmlSerializer xs = new XmlSerializer(typeof(DataSet));
xs.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using XmlSerializer to {0}_2.xml",
fileName);
}

// Serialize using SoapFormatter
using (stream = File.Open(fileName + ".soap", FileMode.Create,
FileAccess.Write))
{
SoapFormatter sf = new SoapFormatter( );
sf.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using SoapFormatter to {0}.soap",
fileName);
}

// Serialize using BinaryFormatter
using (stream = File.Open(fileName + ".bin", FileMode.Create,
FileAccess.Write))
{
BinaryFormatter bf = new BinaryFormatter( );
bf.Serialize(stream, ds);
Console.WriteLine(
"DataSet serialized using BinaryFormatter to {0}.bin",
fileName);
}

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}

Using an XML File to Save and Load a DataSet or a DataTable

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Text;

namespace SaveLoadDataSetXml
{
class Program
{
private const string fileName = @"..\..\..\ContactDataSet.xml";

static void Main(string[] args)
{
string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";

string sqlSelect = "SELECT ContactID, FirstName, LastName " +
"FROM Person.Contact WHERE ContactID BETWEEN 10 AND 13";

// Fill the DataSet using a DataAdapter
DataSet dsSource = new DataSet("ContactDataSet");
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "Contact");
da.FillSchema(dsSource, SchemaType.Source);
da.Fill(dsSource);

// Output the DataSet to the console
Console.WriteLine("---Source DataSet---");
foreach (DataRow row in dsSource.Tables["Contact"].Rows)
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}",
row["ContactID"], row["FirstName"], row["LastName"]);

// Write the XSD schema and data to a file.
FileStream fsOut =
new FileStream(fileName, FileMode.Create, FileAccess.Write);
// Create an XmlTextWriter using the file stream.
XmlTextWriter xtw = new XmlTextWriter(fsOut, Encoding.Unicode);
// Write the XML to the file.
dsSource.WriteXml(xtw, XmlWriteMode.WriteSchema);
xtw.Close();

Console.WriteLine("\nXML file written.");

// Read the XML file into a new DataSet
FileStream fsIn =
new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Create an XmlTextReader using the file stream.
XmlTextReader xtr = new XmlTextReader(fsIn);
DataSet dsDest = new DataSet();
dsDest.ReadXml(xtr, XmlReadMode.ReadSchema);

// Output the DataSet to the console.
Console.WriteLine("\nXML file loaded into DataSet.");
Console.WriteLine("\n---Destination DataSet---");
foreach (DataRow row in dsDest.Tables["Contact"].Rows)
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}",
row["ContactID"], row["FirstName"], row["LastName"]);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Use the WriteXmlSchema() and ReadXmlSchema() methods of the DataSet and DataTable classes to write and read just XSD schema information.