TechnoBase DBMS | Unix/Linux | Mainframes | MySQL | SQL Server
Microsoft .NET
The .NET environment ---- Assemblies ---- The .NET class framework -------- ADO.NET ASP.NET ---- ASP.NET configuration ---- Session state ---- Security C# ---- The C# language ---- File handling ---- Web services ---- Working with databases Javascript ---- Built-in objects ---- Event handling XML ---- SOAP ---- Web Services -------- WSDL Sharepoint ---- Webparts


THE .NET ENVIRONMENT

Microsoft .NET is an XML Web services platform that enables developers to create programs that transcend device boundaries and fully harness the connectivity of the Internet.

The .NET Framework is the infrastructure for the overall .NET Platform. The common language runtime (CLR) and class libraries (including Windows Forms, ADO.NET, and ASP.NET) combine together to provide services and solutions that can be easily integrated within and across a variety of systems. The .NET Framework provides a fully managed, protected, and feature-rich application execution environment, simplified development and deployment, and seamless integration with a wide variety of languages.

The Common Language Runtime (CLR)

The CLR is the runtime environment provided by the .NET framework, which manages the execution of code. The CLR provides features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services. The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used.

Managed code

Code that is developed with a language compiler that targets the CLR is called managed code. Managed code benefits from the various services provided by the CLR. To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries.

The Common Type System (CTS)

The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. The common type system performs the following functions
  • Establishes a framework that enables cross-language integration, type safety, and high performance code execution
  • Provides an object-oriented model that supports the complete implementation of many programming languages
  • Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other

    Configuring .NET applications

    .NET applications can be configured by using a configuration file in the same directory as the application, which has the same name as the application with a .CONFIG extension. e.g SampleApp.exe.config

    Back


    Assemblies

    An assembly is a logical unit of functionality that is made up of one or more files. One of the files will contain the assembly's manifest, which is the metadata that describes the assembly's identity, publicly exported types, files and dependencies. Assemblies typically are .EXE or .DLL files.

    Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping and security permissions for a .NET-based application.

    Types of assemblies

    The runtime supports two different kinds of assemblies - private and shared. Private assemblies are deployed with an application and are for the sole use of that application. They are normally present in the same directory as the application.
    Shared assemblies are specifically designed for use by multiple applications. Shared assemblies are present in the Global Assembly Cache (GAC) and can usually be found in the C:\WinNT\assembly directory.

    Installing a shared assembly in the GAC

    A shared assembly can be installed in the GAC by using a command-line utility called AL.exe, which has a /I[nstall]:filename command-line option for just this purpose, or using the GacUtil.exe tool that ships with the .NET Framework SDK.

    Probing

    Probing is the process by which the CLR locates an assembly, if no <codebase> is specified in the configuration files of the application. Probing is done using four criteria
  • Application base, which is the root location where the application is being executed.
  • Culture, which is the culture attribute of the assembly being referenced.
  • Name, which is the name of the referenced assembly.
  • Private binpath, which is the user-defined list of subdirectories under the root location. This location can be specified in the application configuration file and in managed code using the AppendPrivatePath property for an application domain. When specified in managed code, the managed code privatePath is probed first, followed by the path specified in the application configuration file.

    Culture of an assembly

    Assemblies are actually versioned using version numbers and culture information. For e.g there could be an assembly that is strictly for German, another assembly for Swiss German, another assembly for U.S. English, and so on. Cultures are identified via a string that contains a primary and a secondary tag. A culture string can be assigned to an assembly using AL.exe's /c[ulture]:[text] switch or the System.Reflection.AssemblyCultureAttribute assembly-level attribute. For e.g
    	// Set assembly's culture to Swiss German
    	[assembly:AssemblyCulture("de-ch")]
    Associating a version number with an assembly

    A version number can be added to an assembly by the following piece of code
    	using System.Reflection;
    	[assembly: AssemblyVersion("1.0.0.2")]
    	[assembly: AssemblyKeyFile("C:\\originator.key")]
    Forcing an application to use an assembly of a specific version number

    By default, applications use the version of the assembly with which they were built. But the application's configuration file can be modified to access a different version of an assembly.
    	<configuration>
    		 <runtime>
    		<assemblybinding xmlns="urn.schemas-microsoft-com:asm.v1">
    			  <dependentassembly>
    			<assemblyIdentity name="AppName" publicKeyToken="a7383je8383939" culture="" />
    			<bindingRedirect oldVersion="1.0.393.12322" newVersion="1.0.544.22272" />
    			  </dependentassembly>
    		</assemblybinding>
    		  </runtime>
    	</configuration>
    Disassembling

    The Ildasm.exe file is the MSIL Disassembler that is included with the .NET Framework SDK. The Ildasm.exe parses any .NET Framework .exe or .dll assembly, and shows the information in human-readable format. Ildasm.exe shows more than just the Microsoft intermediate language (MSIL) code — it also displays namespaces and types, including their interfaces. Ildasm.exe can be used to examine native .NET Framework assemblies, such as Mscorlib.dll, as well as .NET Framework assemblies provided by others.

    Back



    THE .NET CLASS FRAMEWORK

    The .NET Framework class library is a library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK. This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.

    The System.Object class

    Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate superclass of all classes in the .NET Framework; it is the root of the type hierarchy.

    System.Collections namespace

    Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

    Main classes
    ArrayList - Implements the IList interface using an array whose size is dynamically increased as required.
    BitArray - Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
    HashTable - Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
    Queue - Represents a first-in, first-out collection of objects.
    SortedList - Represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.
    Stack - Represents a simple last-in-first-out collection of objects.
    Interfaces:
    IList - Represents a collection of objects that can be individually accessed by index.
    Structures:
    DictionaryEntry - Defines a dictionary key-and-value pair that can be set or retrieved.

    System.Data.SqlClient namespace

    It is the SQL Server .NET Data Provider, which describes a collection of classes used to access a SQL Server database in the managed space.

    SqlCommand - Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited.
    SqlConnection - Represents an open connection to a SQL Server database. This class cannot be inherited.
    SqlDataAdapter - Represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database. This class cannot be inherited.
    SqlDataReader - Provides a means of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
    SqlException - The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited.
    SqlParameter - Represents a parameter to a SqlCommand, and optionally, its mapping to DataSet columns. This class cannot be inherited.
    SqlTransaction - Represents a Transact-SQL transaction to be made in a SQL Server database. This class cannot be inherited.

    System.DateTime Structure

    It represents an instant in time, represented as date and time.

    Fields
    MaxValue - Represents the largest possible value of DateTime. This field is read-only.
    MinValue - Represents the smallest possible value of DateTime. This field is read-only.
    Properties
    Date, Day, DayOfWeek, DayOfYear, Hour, Millisecond, Minute, Month, Now, Second, TimeOfDay , Today, Year
    UtcNow - Gets a DateTime that is the current local date and time on this computer expressed as the coordinated universal time (UTC).
    Methods
    Add, AddDays, AddHours, AddMilliseconds, AddMinutes, AddMonths, AddSeconds, AddYears, Compare, Subtract (Overloaded).

    System.Net.Sockets namespace

    Provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to tightly control access to the network. The TCPClient, TCPListener, and UDPClient classes encapsulate the details of creating TCP and UDP connections to the internet.

    Classes

    IPv6MulticastOption - Contains option values for joining an IPv6 multicast group.
    IrDAClient - Provides connection information, and creates client connection objects for opening and closing connections to a server.
    IrDADeviceInfo - Provides information about available servers and ports obtained by the client during a discovery query.
    IrDAListener - Places a socket in a listening state to monitor connections from a specified service or network address.
    LingerOption - Specifies whether a Socket will remain connected after a call to Close and the length of time it will remain connected, if data remains to be sent.
    MulticastOption - Contains IPAddress values used for joining and dropping multicast groups.
    NetworkStream - Provides the underlying stream of data for network access.
    Socket - Implements the Berkeley sockets interface.
    SocketException - The exception that is thrown when a socket error occurs.
    TcpClient - Provides client connections for TCP network services.
    TcpListener - Listens for connections from TCP network clients.
    UdpClient - Provides UDP network services.

    Enumerations

    AddressFamily - Specifies the addressing scheme that an instance of the Socket class can use.
    IrDACharacterSet - Describes the character sets supported by the device.
    IrDAHints - Describes an enumeration of possible device types, such as Fax.
    ProtocolFamily - Specifies the type of protocol that an instance of the Socket class can use.
    ProtocolType - Specifies the protocols that the Socket class supports.
    SelectMode - Defines the polling modes for the Socket.Poll method.
    SocketFlags - Provides constant values for Socket messages.
    SocketOptionLevel - Defines socket option levels for the Socket.SetSocketOption and Socket.GetSocketOption methods.
    SocketOptionName - Defines Socket configuration option names for the Socket class.
    SocketShutdown - Defines constants used by the Socket.Shutdown method.
    SocketType - Specifies the type of socket an instance of the Socket class represents.


    ADO.NET

    ActiveX Data Objects for the .NET Framework (ADO.NET) is a set of classes that expose data access services to the .NET programmer. ADO.NET provides a rich set of components for creating distributed, data-sharing applications and is an integral part of the .NET Framework, providing access to relational data, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, or Internet browsers.

    ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources exposed via OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data.

    Key classes used in ADO.NET

    System.Data.OleDb namespace - OleDbDataReader, OleDbDataAdapter, OleDbConnection, OleDbCommand
    System.Data.SqlClient namespace - SqlDataReader, SqlDataAdapter, SqlConnection, SqlCommand
    System.Data namespace - Dataset, DataTable.

    The DataReader

    The ADO.NET DataReader can be used to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory.
    The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. The DataReader is a good choice when retrieving large amounts of data because the data is not cached in memory.

    Features of ADO.NET

  • The ADO.NET DataSet can hold multiple tables of data and also hold relationships between them.
  • The DataSet is well designed for working on the data without being connected to the database.
  • The DataAdapter allows the programmer to control how the changes to the dataset are transmitted to the database.
  • Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types.
  • Because components exchange ADO.NET datasets using XML, firewalls can allow datasets to pass.

    Data adapters

    Data adapters are an integral part of ADO.NET managed providers, which are the set of objects used to communicate between a data source and a dataset. Adapters are used to exchange data between a data source and a dataset. In many applications, this means reading data from a database into a dataset, and then writing changed data from the dataset back to the database. However, a data adapter can move data between any source and a dataset. For e.g there could be an adapter that moves data between a Microsoft Exchange server and a dataset.

    The two primary data adapters are
    - The OleDbDataAdapter object is suitable for use with any data source exposed by an OLE DB provider.
    - The SqlDataAdapter object is specific to SQL Server. Because it does not have to go through an OLE DB layer, it is faster than the OleDbDataAdapter.

    DataTable

    The DataTable class is a member of the System.Data namespace within the .NET Framework class library. A DataSet is made up of a collection of tables, relationships and constraints. In ADO.NET, DataTable objects are used to represent the tables in a DataSet. A DataTable represents one table of in-memory relational data; the data is local to the .NET-based application in which it resides, but can be populated from a data source such as SQL Server using a DataAdapter.

    A DataTable can be created and used independently, or can be used by other .NET Framework objects, most commonly as a member of a DataSet.

    A DataTable object can be created by using the DataTable constructor, or by passing constructor arguments to the Add method of the Tables property of the DataSet, which is a DataTableCollection.

    DataTable objects can also be created within a DataSet by using the Fill or FillSchema methods of the DataAdapter object, or from a pre-defined or inferred XML schema using the ReadXml, ReadXmlSchema, or InferXmlSchema methods of the DataSet.

    DataView

    A DataView is a .NET framework class used to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, one can expose the data in a table with different sort orders, and the data can be filtered by row state or based on a filter expression.

    Creating a DataView

    There are two ways to create a DataView - by the DataView constructor, or by creating a reference to the DefaultView property of the DataTable.
    Example to create a DataView using the DataView constructor:
    A RowFilter, Sort column, and DataViewRowState are supplied along with the DataTable.
    	DataView custDV = new DataView(custDS.Tables["Customers"],
    		"Country = 'USA'",
    		"ContactName",
    		DataViewRowState.CurrentRows);
    Code example to obtain a reference to the default DataView of a DataTable using the DefaultView property of the table:
    	DataView custDV = custDS.Tables["Customers"].DefaultView;
    The Fill method of the DataAdapter

    The Fill method is used to populate a DataSet with the results of the SelectCommand of the DataAdapter. Fill takes as its arguments a DataSet to be populated, and a DataTable object, or the name of the DataTable to be filled with the rows returned from the SelectCommand.
    	OleDbConnection nwindConn = new OleDbConnection
    		("Provider=SQLOLEDB;Data Source=localhost;" +
    			"Integrated Security=SSPI;Initial Catalog=northwind");
    	OleDbCommand selectCMD = new OleDbCommand
    			("SELECT CustomerID, CompanyName FROM Customers", nwindConn);
    	selectCMD.CommandTimeout = 30;
    	OleDbDataAdapter custDA = new OleDbDataAdapter();
    	custDA.SelectCommand = selectCMD;
    	DataSet custDS = new DataSet();
    	custDA.Fill(custDS, "Customers");
    Accessing data using a DataReader

    After creating an instance of the Command object, a DataReader is created by calling Command.ExecuteReader to retrieve rows from a data source.
    	SqlDataReader objReader = objCommand.ExecuteReader();
    The DataReader be closed after having finished using it since,
    - If the Command contains output parameters or return values, they will not be available until the DataReader is closed.
    - While a DataReader is open, the Connection is in use exclusively by that DataReader. It is not possible to execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.

    Handling SQL Server transactions in ADO.NET

    By using the SqlTransaction class. The SqlTransaction object can be used in association with an SQL Server connection as follows:
    	public void RunSqlTransaction(string myConnString)
    	 { SqlConnection myConnection = new SqlConnection(myConnString);
    		myConnection.Open();
    
    		SqlCommand myCommand = new SqlCommand();
    		SqlTransaction myTrans;
    
    		myTrans = myConnection.BeginTransaction();
    		myCommand.Connection = myConnection;
    		myCommand.Transaction = myTrans;
    		try
    		{ myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) 
    			VALUES (100, 'Description')";
    		  myCommand.ExecuteNonQuery();
    		  myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) 
    			VALUES (101, 'Description')";
    		  myCommand.ExecuteNonQuery();
    		  myTrans.Commit();
    		  Console.WriteLine("Both records are written to database.");
    		}
    		catch(Exception e)
    		{ myTrans.Rollback(); 
    		  Console.WriteLine("Error: {1}", e.Message);
    		  Console.WriteLine("Error reported by {1}.", e.Source);
    		  Console.WriteLine("Neither record was written to database.");
    		}
    		finally
    		{    myConnection.Close();
    		}
    	}
    The ExecuteScalar method

    The ExecuteScalar method is used to retrieve a single value (for e.g an aggregate value) from a database. The ExecuteScalar method executes the query, and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored.
    	public void CreateMySqlCommand(string myScalarQuery, SqlConnection myConnection) 
    	 {
    		SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
    		myCommand.Connection.Open();
    		myCommand.ExecuteScalar();
    		myConnection.Close();
    	 }
    Connecting to an Oracle database using ADO.NET

    For connecting to and accessing data from an Oracle DB, the ODBC .NET Data Provider that works with the ODBC Oracle7.x driver or higher can be used. For this MDAC 2.6 or later and ODBC.NET have to be installed. MDAC (Microsoft Data Access Component) 2.7 contains core component, including the Microsoft SQL server and Oracle OLE Database provider and ODBC driver
    	using Microsoft.Data.Odbc;
    	private void Form1_Load(object sender, System.EventArgs e)
    	{
    		try
    		{
    			OdbcConnection  myconnection = new OdbcConnection ("DSN=TrialDSN");
    			OdbcDataAdapter  myda = new OdbcDataAdapter ("Select * from EMP", myconnection);
    			DataSet ds= new DataSet();
    			myda.Fill(ds, "Table");
    			dataGrid1.DataSource = ds ;		
    		}
    		catch(Exception ex)
    		{
    			MessageBox.Show (ex.Message ); 
    		}
    	}
    ADO.NET and XML

    With ADO.NET, a DataSet can be filled from an XML stream or document. The XML stream or document can be used to supply to the DataSet either data, schema information, or both. The information supplied from the XML stream or document can be combined with existing data or schema information already present in the DataSet.
    ADO.NET also allows for the creation an XML representation of a DataSet, with or without its schema, in order to transport the DataSet across HTTP for use by another application or XML-enabled platform. In an XML representation of a DataSet, the data is written in XML and the schema, if it is included inline in the representation, is written using the XML Schema definition language (XSD). XML and XML Schema provide a convenient format for transferring the contents of a DataSet to and from remote clients.

    DiffGram

    When a DataSet is written as XML data, the rows in the DataSet are written in their current versions. However, the DataSet can also be written as a DiffGram so that both the current and the original values of the rows will be included.

    Converting (or transporting) the XML representations of DataSets

    The XML representation of the DataSet can be written to a file, a stream, an XmlWriter, or a string.
    To obtain the XML representation of the DataSet as a string, the GetXml method is used as shown in the following example.
    	string xmlDS = custDS.GetXml();
    GetXml returns the XML representation of the DataSet without schema information. To write the schema information from the DataSet (as XML Schema) to a string, GetXmlSchema is used.
    To write a DataSet to a file, stream, or XmlWriter, the WriteXml method is used. The first parameter passed to WriteXml is the destination of the XML output. For e.g the passed string can contain a file name, a System.IO.TextWriter object, and so on. An optional second parameter of an XmlWriteMode can be passed to specify how the XML output is to be written.
    The following list shows the options for XmlWriteMode.
    IgnoreSchema - Writes the current contents of the DataSet as XML data, without an XML Schema. This is the default.
    WriteSchema - Writes the current contents of the DataSet as XML data with the relational structure as inline XML Schema.
    DiffGram - Writes the entire DataSet as a DiffGram, including original and current values.

    Back



    ASP.NET

    ASP.NET is a programming framework built on the CLR that can be used on a server to build powerful web applications.

  • Enhanced Performance - ASP.NET is compiled CLR code running on the server. Unlike its interpreted predecessors, ASP.NET can take advantage of early binding, just-in-time compilation, native optimization, and caching services right out of the box
  • Tool Support - The ASP.NET framework is complemented by a rich toolbox and designer in the Visual Studio IDE. WYSIWYG editing, drag-and-drop server controls, and automatic deployment are a few of the features available
  • Power and Flexibility - Because ASP.NET is based on the CLR, it offers the power, flexibility and language independence of that entire platform. The .NET Framework class library, Messaging, and Data Access solutions are all seamlessly accessible from the Web
  • Simplicity - ASP.NET makes it easy to perform common tasks, from simple form submission and client authentication to deployment and site configuration. For e.g the ASP.NET page framework allows developers to build user interfaces that cleanly separate application logic from presentation code and to handle events in a simple, Visual Basic-like forms processing model. Additionally, the CLR simplifies development, with managed code services such as automatic reference counting and garbage collection.
  • Manageability - ASP.NET employs a text-based, hierarchical configuration system, which simplifies applying settings to the server environment and Web applications. Because configuration information is stored as plain text, new settings may be applied without the aid of local administration tools. This "zero local administration" philosophy extends to deploying ASP.NET Framework applications as well. An ASP.NET Framework application is deployed to a server simply by copying the necessary files to the server. No server restart is required, even to deploy or replace running compiled code.
  • Scalability and Availability - ASP.NET has been designed with scalability in mind, with features specifically tailored to improve performance in clustered and multiprocessor environments. Further, processes are closely monitored and managed by the ASP.NET runtime, so that if one misbehaves (leaks, deadlocks), a new process can be created in its place, which helps keep applications constantly available to handle requests.
  • Customizability and Extensibility - ASP.NET delivers a well-factored architecture that allows developers to "plug-in" their code at the appropriate level. In fact, it is possible to extend or replace any subcomponent of the ASP.NET runtime with a developer's custom-written component. Implementing custom authentication or state services is easier.
  • Security - With built in Windows authentication and per-application configuration, security of applications can be ensured.

    The Global.asax file

    The Global.asax file is located at the root of a particular Web application's virtual directory tree. it is responsible for handling higher-level application events such as Application_Start, Application_End, Session_Start, Session_End etc.
    ASP.NET automatically parses and compiles this file into a dynamic .NET Framework class - which extends the HttpApplication base class - the first time any resource or URL within the application namespace is activated or requested.

    Application events handled by the GLOBAL.ASAX file

    Application_Start - Fires when the application is started
    Session_Start - Fires when the session is started
    Application_BeginRequest - Fires at the beginning of each request
    Application_AuthenticateRequest - Fires upon attempting to authenticate the use
    Application_Error - Fires when an error occurs
    Session_End - Fires when the session ends
    Application_End - Fires when the application ends


    ASP.NET configuration

    ASP.NET configuration files are XML-based text files - each named web.config - that can appear in any directory on an ASP.NET web application server. Each web.config file applies configuration settings to the directory it is located in and to all virtual child directories beneath it. Settings in child directories can optionally override or modify settings specified in parent directories. The root configuration file - WinNT\Microsoft.NET\Framework\<version>\config\machine.config - provides default configuration settings for the entire machine. ASP.NET configures IIS to prevent direct browser access to web.config files to ensure that their values cannot become public (attempts to access them will cause ASP.NET to return 403: Access Forbidden).

    Configuration files

    At run time ASP.NET uses the web.config files to hierarchically compute a unique collection of settings for each incoming URL target request (these settings are calculated only once and then cached across subsequent requests; ASP.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change).

    For e.g the configuration settings for the URL http://myserver/myapplication/mydir/page.aspx would be computed by applying web.config file settings in the following order Base configuration settings for machine - C:\WinNT\Microsoft.NET\Framework\v.1.00\config\machine.config

    Overridden by the configuration settings for the site (or the root application) - C:\inetpub\wwwroot\web.config

    Overridden by application configuration settings - D:\MyApplication\web.config

    Overridden by subdirectory configuration settings - D:\MyApplication\MyDir\web.config

    Configuration settings that can be handled by the web.config file

    Appsettings - Contains custom application settings. This is a predefined configuration section provided by the .NET Framework.
    	<Appsettings>
    		<add key="connstring" value="Data Source=EMACHINES\TANTRA;Initial Catalog=esupplies;User ID=Kandas;Password=ustatesa;" />
    	</appSettings>
    Authentication - This section sets the authentication policies of the application. Possible modes are "Windows", "Forms", "Passport" and "None"
    	<authentication mode="Windows" />
    Authorization - This section sets the authorization policies of the application. You can allow or deny access to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous (unauthenticated) users.
    	<authorization>
            	<allow users="*" /> <!-- Allow all users -->
    	</authorization>
    Session State settings - By default ASP.NET uses cookies to identify which requests belong to a particular session. If cookies are not available, a session can be tracked by adding a session identifier to the URL. To disable cookies, set sessionState cookieless="true".
    	<sessionState 
    	mode="InProc",
    	stateConnectionString="tcpip=127.0.0.1:42424"
    	sqlConnectionString="data source=127.0.0.1;user id=sa;password="
    	cookieless="false" 
    	timeout="20"
    	/>
    Globalization - This section sets the globalization settings of the application.
    	<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
    Configuration Errors and fixes:

    i) config error on the line in the web config file, authentication mode="Windows" -- Virtual directory needs to be configured as an application
    ii) "XML page cannot be displayed" message (on an aspx file) -- Run the ASP.NET IIS Registration Tool (Aspnet_regiis -u and Aspnet_regiis -i ). Aspnet_regiis.exe is installed in the Microsoft.NET Framework folders.


    Cacheing

    The following caching techniques available in ASP.NET

  • Output caching, which caches the dynamic response generated by a request. Output caching is useful when the contents of an entire page can be cached.
  • Fragment caching, which caches portions of a response generated by a request.
  • Data caching, which caches arbitrary objects programmatically.

    Output caching on an ASP.NET web page

    The following directive activates output caching on the response
    	<%@ OutputCache Duration="60" VaryByParam="none"%>
    	
    Applications that want more control over the HTTP headers related to caching can use the functionality provided by the System.Web.HttpCachePolicy class.
    	Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    	Response.Cache.SetCacheability(HttpCacheability.Public);

    ASP.NET Session state

    Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing only the ASCII characters that are allowed in URLs. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and randomness so that a malicious user cannot use a new SessionID to calculate the SessionID of an existing session.
    The SessionID strings are communicated across client-server requests either by means of an HTTP cookie or a modified URL with the SessionID string embedded, depending on how the application settings are configured (in the web.config file).

    Session state management

    ASP.NET offers the following options for storing session state information
    Inproc - Session state is stored locally in the server
    StateServer - stored in a state service process either locally or remotely
    SqlServer - stored in a SQL Server DB
    Off - Session state is disabled

    .NET framework classes that deal with session state

    The SessionStateModule class in the System.Web.SessionState namespace provides session-state services for an application.
    The HttpSessionState class in the System.Web.SessionState namespace provides access to all session-state values, session-level settings and lifetime management methods.

    Session state variables

    The SessionState class exposes two state collections: Contents and StaticObjects. The Contents collection exposes all variable items that have been added to the session-state collection directly through code.
    	// C# code from within a page, a handler, or Global.asax.
    	Session["Message"] = "MyMsg";
    	Session["AppStartTime"] = DateTime.Now;
    The StaticObjects collection exposes all variable items that have been added to the session-state collection through <object runat="server"> tags with the scope of "Session" within the Global.asax file. For e.g
    	// Global.asax definition
    	<OBJECT RUNAT="SERVER" SCOPE="SESSION" ID="MyInfo" 	PROGID="Scripting.Dictionary"></OBJECT>
    Objects cannot be added to the StaticObjects collection from anywhere else within an ASP.NET application.

    ViewState

    ViewState is the mechanism ASP.NET uses to keep track of server control state values that do not otherwise post back as part of the HTTP form. For e.g the text shown by a Label or TextBox control is saved in ViewState by default. Developers can bind data or programmatically set the Label just once when the page first loads, and on subsequent postbacks, the label text will be repopulated automatically from ViewState. This often enables making less trips to the DB.

    ViewState is a hidden form field managed by the ASP.NET page framework. When ASP.NET executes a page, the ViewState values from the page and all of the controls are collected and formatted into a single encoded string, and then assigned to the value attribute of the hidden form field (specifically, <input type=hidden>). Since the hidden form field is part of the page sent to the client, the ViewState value is temporarily stored in the client's browser. If the client chooses to post the page back to the server, the ViewState string is posted back too.

    Upon postback, the ASP.NET page framework parses the ViewState string and populates the ViewState properties for the page and each of the controls. The controls, in turn, use the ViewState data to rehydrate themselves to their former state.

    The .ASPX page must have a server-side form tag (<form runat=server>) to use ViewState. A form field is required so the hidden field that contains the ViewState information can post back to the server. And, it must be a server-side form so the ASP.NET page framework can add the hidden field when the page is executed on the server.

    The page itself saves 20 or so bytes of information into ViewState, which it uses to distribute PostBack data and ViewState values to the correct controls upon postback. So, even if ViewState is disabled for the page or application, a few remaining bytes may be seen in ViewState.

    In cases where the page does not post back, ViewState can be eliminated from a page by omitting the server side <form> tag.


    Security in ASP.NET

    The two security functions needed to be performed in an ASP.NET application are - authentication and authorization.

    Authentication assures that the user is, in fact, who the user claims to be. The application obtains credentials (various forms of identification, such as name and password) from a user and validates those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity

    Authorization, on the other hand, limits access rights by granting or denying specific permissions to an authenticated identity.

    IIS-set authentication procedures

    ASP.NET works in conjunction with IIS to support authentication, using Basic, Digest, and Windows authentication. ASP.NET supports the Microsoft Passport authentication service, which provides single sign-on services and support for user profile services. ASP.NET also provides a robust service for applications that want to use forms-based authentication. Forms-based authentication uses cookies to authenticate users and allows the application to do its own credential verification.

    Types of authorization provided by ASP.NET

    ASP.NET provides two types of authorization services
  • Checks against ACLs or permissions on a resource to determine whether the authenticated user account can access the resources
  • URL authorization, which authorizes an identity for pieces of the Web space

    Code Access Security

    To help protect computer systems from malicious mobile code, to allow code from unknown origins to run safely, and to protect trusted code from intentionally or accidentally compromising security, the .NET Framework provides a security mechanism called code access security.

    Code access security allows code to be trusted to varying degrees, depending on where the code originates and on other aspects of the code's identity. Code access security also enforces the varying levels of trust on code, which minimizes the amount of code that must be fully trusted in order to run.

    Using code access security can reduce the likelihood that any code can be misused by malicious or error-filled code. It can reduce developer's liability because they can specify the set of operations their code should be allowed to perform as well as the operations the code should never be allowed to perform. Code access security can also help minimize the damage that can result from security vulnerabilities in developed code.

    All managed code that targets the CLR receives the benefits of code access security, even if that code does not make a single code access security call.

    Role-based security

    Business applications often provide access to data or resources based on credentials supplied by the user. Typically, such applications check the role of a user and provide access to resources based on that role. The CLR provides support for role-based authorization based on a Windows account or a custom identity.

    Principal

    A principal represents the identity and role of a user and acts on the user's behalf. Role-based security in the .NET Framework supports three kinds of principals:
    - Generic principals represent users and roles that exist independent of Windows users and roles.
    - Windows principals represent Windows users and their roles (or their Windows groups). A Windows principal can impersonate another user, which means the principal can access a resource on a user's behalf while presenting the identity that belongs to that user.
    - Custom principals can be defined by an application in any way that is needed for that particular application. They can extend the basic notion of the principal's identity and roles.

    Forms-based authentication

    Forms-based authentication is an ASP.NET authentication service that enables applications to provide their own logon UI and do their own credential verification. ASP.NET authenticates users, redirecting unauthenticated users to the logon page, and performing all the necessary cookie management. This sort of authentication is a popular technique used by many Web sites.

    An application has to be configured to use forms-based authentication by setting <authentication> to Forms, and denying access to anonymous users. The following example shows how this can be done in the Web.config file for the desired application
    	<configuration>
    	<system.web>
    	<authentication mode="Forms"/>
    	<authorization>
    		<deny users="?" />
    	</authorization>
    	</system.web>
    	</configuration>
    Windows authentication for Web Services

    The same technique used for .aspx web pages can be used to secure XML Web services using Windows authentication. To require authentication, Integrated Windows authentication is enabled for the application and Anonymous access is disabled in the IIS management console. To allow or deny specific users access to the web service, the ASP.NET configuration system is used or ACLs are set on the service file itself. For e.g
    	<configuration>
    	<system.web>
    	<authentication mode="Windows"/>
    	</system.web>
    	<location path="secureservice.asmx">
    	<system.web>
    	  <authorization>
    		<allow users="Administrator"/>
    		<allow users="DOMAIN\Bradley"/>
    		<deny roles="BUILTIN\Power Users"/>
    	  </authorization>
    	</system.web>
    	</location>
    	</configuration>

    Server Controls

    ASP.NET server controls are components that run on the server and encapsulate user-interface and other related functionality. They are used in ASP.NET pages and code-behind classes.

    Server controls may be needed for the following causes
  • to reuse an user interface across different pages without rewriting the code, we can create a server control encapsulating the UI.
  • to develop a compiled control that combines the functionality of two or more existing controls (like a control that encapsulates a textbox and a button)
  • to customize an existing control by overriding its properties, methods and events
  • to develop a custom-control by deriving from the base control classes

    ASP.NET server controls are identified within a page using declarative tags that contain a runat="server" attribute. An individual server control can be identified within a web page by using the id attribute. This id reference can be used to programmatically manipulate the control's object model at run-time.

    Event-handling in server controls

    Server controls can optionally expose and raise server events which can be handled by the programmer. This can be done by declaratively wiring an event to a control.
    Here is an example of wiring an onclick event to a button control.
    	<html>
    	<script language="VB" runat="server">
    	Sub EnterBtn_Click(Sender As Object, E As EventArgs)
    		Message.Text = "Hi " & HttpUtility.HtmlEncode(Name.Text) & ", welcome to ASP.NET!"
    	End Sub
    	</script>
    	<body>
    	<form action="controls3.aspx" runat=server>
    	Please enter your name: <asp:textbox id="Name" runat=server/> 
    	<asp:button text="Enter" Onclick="EnterBtn_Click" runat=server/>
    	<asp:label id="Message" runat=server/>
    	</form>
    	</body>
    	</html>
    Classifications of server controls

    System.Web.UI.HtmlControls - HTML server controls are HTML elements exposed to the server so you can program against them. HTML server controls expose an object model that maps very closely to the HTML elements that they render.
    System.Web.UI.WebControls - Web server controls are ASP.NET server controls with an abstract, strongly-typed object model. Web server controls include not only form-type controls such as buttons and text boxes, but also special-purpose controls such as a calendar. Web server controls are more abstract than HTML server controls, in that their object model does not necessarily reflect HTML syntax.

    Types of web server controls

    The following is a full list of all web server controls
    AdRotator, Button, Calendar, CheckBox, CheckBoxList, CompareValidator, CustomValidator, DataGrid, DataList, DropDownList, HyperLink, Image, ImageButton, Label, LinkButton, ListBox, Panel, PlaceHolder, RadioButton, RadioButtonList, RangeValidator, RegularExpressionValidator, Repeater, RequiredFieldValidator, Table, TableCell, TableRow, TextBox, ValidationSummary, XML


    User Controls

    User controls are included in a Web Forms page using a Register directive
    	<%@ Register TagPrefix="Acme" TagName="Message" Src="pagelet1.ascx" %>
    The TagPrefix determines a unique namespace for the user control (so that multiple user controls with the same name can be differentiated from each other). The TagName is the unique name for the user control. The Src attribute is the virtual path to the user control - for e.g "MyPagelet.ascx" or "/MyApp/Include/MyPagelet.ascx". After registering the user control, the user control tag can be placedin the Web Forms page just as an ordinary server control (including the runat="server" attribute):
    	<Acme:Message runat="server"/>
    Creating User controls programmatically

    User controls may be created programmatically using the LoadControl method of the System.Web.UI.Page class. The LoadControl method is used to load the user control, passing the virtual path to the user control's source file.
    	Control c1 = LoadControl("usercontrol1.ascx");
    	((UserControl1)c1).Category = "business";
    	Page.Controls.Add(c1);
    The type of the user control is determined by a ClassName attribute on the Control directive. For example, a user control saved with the file name "usercontrol1.ascx" is assigned the strong type "UserControl1" as follows:
    	<%@ Control ClassName="UserControl1" %>

    ASP.NET File Handling

    Checking the existence of a file

    This can be done by the Exists method of the System.IO.File class.
    	if (System.IO.File.Exists("C:\\temp\\data.txt"))
    	{ //do processing here
    	}
    Generic processing for postbacked pages

    In the GLOBAL.ASAX file:
    	protected void Application_BeginRequest(Object sender, EventArgs e) {
    		if(Request.RequestType == "POST")
    		{
    		string postBackData = Request.Form["__VIEWSTATE"];
    			if(postBackData.Length > 0)
    			{
    			Response.Write("A POSTBACK!!!!"); //do processing here
    			} 
    		}  
    	}

    Back



    C#

    Object-oriented programming

    Inheritance

    The ability of a class to invoke the members of a parent class by deriving or inheriting from it. Inheritance follows on from the concept of 'class' in that it provides a natural classification for kinds of objects and allows for the commonality of objects to be explicitly taken advantage of in modelling and constructing object systems. One reason to use inheritance is that it allows the re-use code from a previous project but gives the flexibility to slightly modify it if the old code doesn't do exactly what is required.
    	public class A
    	{
    	public void method1()
    		{ }
    	}
    	
    	public class B : A	//inherits class A
    	{
    	}
    Polymorphism

    Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Inheritance (or delegation) specifies slightly different or additional structure or behaviour for an object, and these more specific or additional attributes of an object of a base class (or type) when assuming or becoming an object of a derived class characterises object-oriented polymorphism.

    By another definition, A property of class¤ hierarchies whereby the result of calling a specific virtual member function of an object depends on the actual (run-time) type of the object, rather than on the (compile-time) type of the pointer or reference¤ through which the call is initiated.

    Implementing polymorphism in C#

    Polymorphism by definition means taking many forms. In C# it means the ability for classes to share the same methods (actions) but implement them differently. For instance, say a class is created called Shape and this class has a method called .draw() which draws the shape onto the UI. Then two subclasses are created, using inheritance, of this Shape class - Square and Circle. A square and circle are two entirely different shapes, yet both classes have the .draw() method. When the Square.draw() method is called it will draw a square on the UI and when the Circle.draw() method is called, it will draw a circle. So both classes can use the same methods but implement them differently.

    Copy constructor

    A copy constuctor is similar to the default constructor except that it can accept a single argument of reference to same class type. Copy constructors are used to copy objects of the class type.

    Interfaces

    An interface defines a contract. A class or struct that implements an interface must adhere to its contract. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

    Interfaces can contain methods, properties, events, and indexers. The interface itself does not provide implementations for the members that it defines. The interface merely specifies the members that must be supplied by classes or interfaces that implement the interface.

    Indexers

    Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessor take parameters.

    Delegate

    A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates in C# are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

    Structs

    Structs are similar to classes in that they represent data structures that can contain data members and function members. Unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data, the latter known as an object.
    Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. Key to these data structures is that they have few data members, that they do not require use of inheritance or referential identity, and that they can be conveniently implemented using value semantics where assignment copies the value instead of the reference.

    Operator overloading

    All unary and binary operators have predefined implementations that are automatically available in any expression. In addition to the predefined implementations, user-defined implementations can be introduced by including operator declarations in classes and structs and this is known as operator overloading.

    Differences between C# and C++

  • C# allows the usage of pointers but only in the unsafe mode
  • In C#, the long datatype is 64 bits. In C++, it is 32 bits
  • In C#, method parameters cannot have default values. Method overloading has to be used to achieve the same effect
  • C# does not support bit fields
  • In C#, programmers don't have control over when a destructor is called because destructors are called automatically by the garbage collector


    C# applications

    Entry point of a C# application

    Application startup occurs when the execution environment calls a designated method, which is referred to as the application's entry point. This entry point method is always named Main, and can have one of the following signatures
    	static void Main() {...}
    	static void Main(string[ ] args) {...}
    	static int Main() {...}
    	static int Main(string[ ] args) {...}
    Invoking the C# compiler from the command line

    The C# compiler can be invoked at the command line by typing the name of its executable file (csc.exe) on the command line.
    Here are some sample usages:
    Compiles File.cs producing File.exe: csc File.cs
    Compiles File.cs producing File.dll: csc /target:library File.cs
    Compiles File.cs and creates My.exe: csc /out:My.exe File.cs
    Compiles all of the C# files in the current directory, with optimizations on and defines the DEBUG symbol. The output is File2.exe: csc /define:DEBUG /optimize /out:File2.exe *.cs
    Compiles all of the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed: csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs
    Compiles all of the C# files in the current directory to Something.xyz (a DLL): csc /target:library /out:Something.xyz *.cs

    Unsafe code

    The core C# language does not allow the use of pointers as they may lead to "dangling" or unreferenced pointers; however in some cases, the usage of pointers becomes unavoidable as in interfacing with the underlying operating system, accessing a memory-mapped device, or implementing a time-critical algorithm. To address this need and provide access to pointers, C# provides the ability to write unsafe code.
    In unsafe code it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. In a sense, writing unsafe code is much like writing C code within a C# program.
    Unsafe code is in fact a “safe” feature from the perspective of both developers and users. Unsafe code must be clearly marked with the modifier unsafe, so developers can’t possibly use unsafe features accidentally, and the execution engine works to ensure that unsafe code cannot be executed in an untrusted environment.

    Namespaces

    C# programs are organized using namespaces. Namespaces are used both as an 'internal' organization system for a program, and as an 'external' organization system — a way of presenting program elements that are exposed to other programs.

    A namespace-declaration consists of the keyword namespace, followed by a namespace name and body, optionally followed by a semicolon. Namespaces are implicitly public and the declaration of a namespace cannot include any access modifiers.
    	namespace N1
    	{
    	   class A {}
    	   class B {}
    	}
    Namespaces can also be nested within each other.
    	namespace N1
    	{
    	   namespace N2
    	   {
    		  class A {}
    		  class B {}
    	   }
    	}

    Classes

    Modifiers

    C# provides the usage of the following access modifiers:
    public - access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.
    private - member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. Nested types in the same body can also access those private members.
    protected - member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
    internal - access modifier for types and type members. Internal members are accessible only within files in the same assembly.

    These are the other modifiers used in C#:
    abstract - can be used with classes, methods, and properties. The abstract modifier is to be used in a class declaration to indicate that a class is intended only to be a base class of other classes. The abstract modifier is used in a method or property declaration to indicate that the method or property does not contain implementation.
    const - The keyword const is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable cannot be modified. A constant declaration introduces one or more constants of a given type.
    event - Specifies an event.
    extern - used in a method declaration to indicate that the method is implemented externally. A common use of the extern modifier is with the DllImport attribute.
    override - used to modify a method or a property. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
    readonly - The readonly keyword is a modifier that can be used on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
    sealed - A sealed class cannot be inherited. It is an error to use a sealed class as a base class. The sealed modifier is used in a class declaration to prevent accidental inheritance of the class.
    static - used to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types.
    unsafe - The unsafe keyword denotes an unsafe context. Unsafe context is required for any operation involving pointers.
    unsafe is applied as a modifier in the declaration of callable members such as methods, properties, constructors, and extenders (but not static constructors).
    virtual - used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.
    When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
    By default, methods are non-virtual. You cannot override a non-virtual method.
    volatile - indicates that a field can be modified in the program by OS, the hardware, or a concurrently executing thread.

    Static and instance members:
    Static members belong to classes while instance members belong to instances of classes (objects).
    When a static member is referenced in a member-access of the form E.M, E must denote a type that has a member M. It is a compile-time error for E to denote an instance.
    When an instance member is referenced in a member-access of the form E.M, E must denote an instance of a type that has a member M. It is a compile-time error for E to denote a type.

    Back


    C# language

    Types

    There are two categories of types- value types and reference types. A third category of types, pointers, is available only in unsafe code. Value types include simple types (e.g., char, int, and float), enum types, and struct types. Reference types include class types, interface types, delegate types, and array types.

    Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter known as objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.

    Value types
    	Type		Range			Size
    
    	sbyte		-128 to 127		Signed 8-bit integer
    	byte		0 to 255		Unsigned 8-bit integer
    	short		-32,768 to 32,767	Signed 16-bit integer
    	ushort		0 to 65,535		Unsigned 16-bit integer
    	int		-2^31 to 2^31 -1	Signed 32-bit integer
    	uint		0 to 2 ^ 32		unsigned 32-bit integer
    	long		-2^63 to 2^63 - 1	Signed 64-bit integer
    	ulong		0 to 2^64		Unsigned 64-bit integer
    	bool		True or False 
    	decimal
    	float
    	double
    	char					A unicode character
    	string					A string of unicode characters
    	object
    Creating new value types

    Developers can define new value types through enum and struct declarations as below.
    	public enum Color
    	{
    	   Red, Blue, Green
    	}
    	
    	public struct Point 
    	{ 
    	   public int x, y; 
    	}
    Enum

    An enum is a value type that declares a related group of symbolic constants. Enums are used for 'multiple choice' scenarios, in which a runtime decision is made from a fixed number of choices that are known at compile-time.
    enum Color 
    	{
    	   Red,
    	   Blue,
    	   Green
    	}
    Creating new reference types

    Developers can define new reference types via class, interface, and delegate declarations as below.
    	public interface IBase
    	{
    	   void F();
    	}
    
    	public interface IDerived: IBase
    	{
    	   void G();
    	}
    
    	public class A
    	{
    	   protected virtual void H() {
    		  Console.WriteLine("A.H");
    	   }
    	}
    
    	public class B: A, IDerived 
    	{
    	   public void F() {
    		  Console.WriteLine("B.F, implementation of IDerived.F");
    	   }
    	   public void G() {
    		  Console.WriteLine("B.G, implementation of IDerived.G");
    	   }
    	   override protected void H() {
    		  Console.WriteLine("B.H, override of A.H");
    	   }
    	}
    
    	public delegate void EmptyDelegate();
    	
    Operators

    Equality ==, != Comparison >, >=, <, <= Arithmetic +, -, *, / modulo (remainder) % Boolean || (OR), && (AND)

    Boxing and unboxing

    Boxing and unboxing is a central concept in a C# type system. It provides a bridge between value-types and reference-types by permitting any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.

    Boxing conversion

    A boxing conversion permits any value-type to be implicitly converted to the type object or to any interface-type implemented by the value-type. Boxing a value of a value-type consists of allocating an object instance and copying the value-type value into that instance.
    For any value-type T, the boxing class would be declared as follows:
    	class T_Box
    	{ 
    		T value; 
    		T_Box(T t) {
    		value = t;
    		}
    	}
    Variables

    C# defines seven categories of variables: static variables, instance variables, array elements, value parameters, reference parameters, output parameters, and local variables.
    In the example,
    	class A
    	{
    	   public static int x;
    	   int y;
    	   void F(int[ ] v, int a, ref int b, out int c) {
    		  int i = 1;
    		  c = a + b++;
    	   }
    	}
    x is a static variable, y is an instance variable, v[0] is an array element, a is a value parameter, b is a reference parameter, c is an output parameter, and i is a local variable.

    Converting a string variable to an integer:
    There are two methods:
    Via the parse method of the Int32 class
    	String sNumber = "123";
    	int iNumber = Int32.Parse(sNumber);
    or via the Convert class:
    	String sNumber = "123";
    	int iNumber = Convert.ToInt32(sNumber);
    Definite assignment of variables in C#

    At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by static flow analysis, that the variable has been automatically initialized or has been the target of at least one assignment.


    Preprocessing directives

  • The #if, #elif, #else and #endif directives are used to create compound conditional directives.
  • #define enables the definition of a symbol, such that, by using the symbol as the expression passed to the #if directive, the expression will evaluate to true.
  • #undef enables the undefinition of a symbol, such that, by using the symbol as the expression in a #if directive, the expression will evaluate to false.
  • #error enables the generation of an error from a specific location in your code.
  • #line enables the modification of the compiler's line number and (optionally) the file name output for errors and warnings.
  • #warning enables the generation of a level one warning from a specific location in the code.
  • #region and #endregion enable the specification a block of code that can be expanded or collapsed when using the outlining feature of the Visual Studio Code Editor.


    Statements

    Selection -> if-else, switch
    Iteration -> do, for, foreach in, while
    Jump -> break, continue, goto, return
    Exception handling -> throw, try-catch, try-finally, try-catch-finally
    Others -> checked, unchecked, fixed, lock


    Using unsafe code for manual memory management in C#

    The garbage collector underlying C# may work by moving objects around in memory, but this motion is invisible to most C# developers. For developers who are generally content with automatic memory management but sometimes need fine-grained control or that extra bit of performance, C# provides the ability to write "unsafe" code. Such code can deal directly with pointer types and object addresses. However, C# requires the programmer to fix objects to temporarily prevent the garbage collector from moving them.

    This "unsafe" code feature is in fact a "safe" feature from the perspective of both developers and users. Unsafe code must be clearly marked in the code with the modifier unsafe, so developers can't possibly use unsafe language features accidentally, and the compiler and the execution engine work together to ensure that unsafe code cannot masquerade as safe code. These restrictions limit the use of unsafe code to situations in which the code is trusted.

    The example
    	using System;
    	class Test
    	{
    	static void WriteLocations(byte[] arr) {
    		unsafe {
    			fixed (byte* pArray = arr) {
    			byte* pElem = pArray;
    			for (int i = 0; i < arr.Length; i++) {
    				byte value = *pElem;
    				Console.WriteLine("arr[{0}] at 0x{1:X} is {2}", i , (uint)pElem, value);
    				pElem++;
    				}
    			}
    		}
    	}
    		static void Main() {
    			byte[] arr = new byte[] {1, 2, 3, 4, 5};
    			WriteLocations(arr);
    		}
    	}
    shows an unsafe block in a method named WriteLocations that fixes an array instance and uses pointer manipulation to iterate over the elements. The index, value, and location of each array element are written to the console. One possible example of output is:
    	arr[0] at 0x8E0360 is 1
    	arr[1] at 0x8E0361 is 2
    	arr[2] at 0x8E0362 is 3
    	arr[3] at 0x8E0363 is 4
    	arr[4] at 0x8E0364 is 5
    In-built methods

    String Operations
    	//split a string
    	char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
    	string text = "one\ttwo three:four,five six seven";
    	string[] words = text.Split(delimiterChars);
    
    	//Convert a String to a DateTime 
    	string date = "01/08/2008";
    	DateTime dt = Convert.ToDateTime(date);
    Parsing a querystring

    The following code parses a Querystring formatted string into a NameValueCollection.
    	NameValueCollection coll=Request.QueryString;	// Load NameValueCollection object
    	
    	String[] arr1 = coll.AllKeys;	// Get names of all keys into a string array
    	for (loop1 = 0; loop1 < arr1.Length; loop1++)
    	{
    		Response.Write("Key: " + arr1[loop1] + "<br>");
    		String[] arr2 = coll.GetValues(arr1[loop1]);
    		for (loop2 = 0; loop2 < arr2.Length; loop2++)
    		{
    		Response.Write("Value " + loop2 + ": " + arr2[loop2] + "<br>");
    		}
    	}

    Back


    File handling

    Reading and writing text files
    	namespace esdsconvert
    	{
    	class Program
    	{
    	static void Main(string[] args)
    	{
    	string sINFILE = "D:\\VAK\\DOC_MR_R13339308_bug_25469.txt";
    	string sOUTFILE = "D:\\VAK\\DOC_MR_R13339308_bug_25469_new.txt";
    	string sSeq;
    	char cZero = Convert.ToChar("0");
    	FileStream fs = new FileStream(sINFILE, FileMode.Open, FileAccess.Read);
    	FileStream fso = new FileStream(sOUTFILE, FileMode.Create, FileAccess.Write);
    	StreamReader sr = new StreamReader(fs);
    	StreamWriter sw = new StreamWriter(fso);
    	Console.WriteLine("Press Enter to Start Execution...");
    	sr.BaseStream.Seek(0, SeekOrigin.Begin);
    	string str = sr.ReadLine();
    	int iSeq = 1;
    	while (str != null)
    	{
    		sSeq = iSeq.ToString().PadLeft(18, cZero);
    		sw.WriteLine(sSeq + str);
    		iSeq += 1;
    		str = sr.ReadLine();
    	}
    	Console.ReadLine();
    	sr.Close();
    	fs.Close();
    	}
    	}
    	}
    Writing an XML file
    	using System.Xml;
    	using System.Xml.Schema;
    
    	public static void main()
    	{
    	writer = new XmlTextWriter("D:\\Folder\\file1.xml", System.Text.Encoding.UTF8);
    	writeXMLheaders(writer);
    	writer.WriteStartElement("order_number");
    	writer.WriteString("111");
    	writer.WriteStartElement("code");
    	writer.WriteString("ORD45");
    	writer.WriteEndElement();
    	writer.WriteStartElement("name");
    	writer.WriteString("Cartons");
    	writer.WriteEndElement();
    	writer.WriteStartElement("details");		
    	writer.WriteStartAttribute("bookingAgent");
    	writer.WriteString("1029");
    	writer.WriteEndAttribute();
    	writer.WriteEndElement();
    
    	writer.WriteEndElement();
    	closeXMLwriter(writer);	}
    
    	private static void writeXMLheaders(XmlTextWriter writer)
    	{
    		writer.WriteStartDocument(true);
    		writer.Formatting = Formatting.Indented;
    		writer.Indentation = 2;
    		writer.WriteStartElement("comtec");
    		writer.WriteStartAttribute("xsi:noNamespaceSchemaLocation");
    		writer.WriteString("comtec_cdms.xsd");
    		writer.WriteEndAttribute();
    		writer.WriteStartAttribute("xmlns:xsi");
    		writer.WriteString("http://www.w3.org/2001/XMLSchema-instance");
    		writer.WriteEndAttribute();
    		writer.WriteStartAttribute("version");
    		writer.WriteString("2008");
    		writer.WriteEndAttribute();	}
    
    
    	private static void closeXMLwriter(XmlTextWriter writer)
    	{
    		writer.WriteEndElement();
    		writer.WriteEndDocument();
    		writer.Close();	}
    Send an XML file to a message queue
    	XmlDocument doc = new XmlDocument();
    	XmlTextReader reader = new XmlTextReader("D:\\folder1\\file1.xml");
    	reader.WhitespaceHandling = WhitespaceHandling.None;
    	reader.MoveToContent();
    	reader.Read();
    	doc.Load(reader);
    
    	String QueuePath = "FormatName:DIRECT=OS:" + ConfigurationManager.AppSettings["QueueName"];
    	MessageQueue msgQ = new MessageQueue(QueuePath);
    
    	msgQ.Send(doc);
    The WebClient class

    For simple request and response transactions, the WebClient class provides the easiest method for uploading data to or downloading data from an Internet server. WebClient provides methods for uploading and downloading files, sending and receiving streams, and sending a data buffer to the server and receiving a response. WebClient uses the WebRequest and WebResponse classes to make the actual connections to the Internet resource, so any registered pluggable protocol is available for use. The following example requests a Web page and returns the results in a stream.
    	WebClient myClient = new WebClient();
    Stream response = myClient.OpenRead("http://www.contoso.com/index.htm");
    // The stream data is used here. response.Close();

    Back



    Web services

    Creating and consuming a Web Service
    	using System.Web.Services;
    	namespace WebService1
    	{
    		[WebService(Namespace = "http://localhost:1685/WebService1")]
    		[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    		[System.ComponentModel.ToolboxItem(false)]
    	public class Service1 : System.Web.Services.WebService
    		{
    			[WebMethod]
    			public int add(int a, int b)
    	        {
    				return (a + b);
            		}
    		}
    	}
    
    	namespace WebSvcConsumer1
    	{
    	    public partial class _Default : System.Web.UI.Page
    	    {
    	        WebSvcConsumer1.addSvc.Service1 SvcObj = new WebSvcConsumer1.addSvc.Service1();
    	        protected void Page_Load(object sender, EventArgs e) { }
    	        protected void Button1_Click(object sender, EventArgs e)
    	        	{
    	            int sum;
            		    sum = SvcObj.add(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text));
    	            TextBox3.Text = "Result = " + sum;
    	        	}
    	    }
    	}

    Working with databases

    Connecting to SQLServer
    	using System.Data.SqlClient;
    
    	private const string sConnstr = "server=(local)\\SQLEXPRESS;database=KRV_DB;Integrated Security=SSPI;";
    	private string sDepName, sDepNbr;
    	private decimal dAmt;
    
    	private void Form1_Load(object sender, EventArgs e)
    	{
    	SqlConnection SqlConn1 = new SqlConnection(sConnstr);
    	SqlConn1.Open();
    
    	SqlCommand SqlCmd1 = SqlConn1.CreateCommand();
    	SqlCmd1.CommandText = "select * from DPST_DETAIL";
    
    	SqlDataAdapter SqlDA1 = new SqlDataAdapter();
    	SqlDA1.SelectCommand = SqlCmd1;
    	DataSet DS1 = new DataSet();
    
    	int numberOfRows = SqlDA1.Fill(DS1, "DPST_DETAIL");
    
    	SqlConn1.Close();
    
    	DataTable DT1 = DS1.Tables["DPST_DETAIL"];
    	foreach (DataRow DR1 in DT1.Rows)
    		{
    		string sDepItem = Convert.ToString(DR1["DPST_NBR"]) + " " +  Convert.ToString(DR1["DPST_NAME"]);
    			lstDeposits.Items.Add(sDepItem);        }
    	lblTotDep.Text = Convert.ToString(lstDeposits.Items.Count);
    
    	int iDepID = Convert.ToInt32(DT1.Rows[0][0]);
    	sDepName = Convert.ToString(DT1.Rows[0][1]);
    	sDepNbr = Convert.ToString(DT1.Rows[0][2]);
    
    	/*Push data into text boxes for display*/
    	txtDepName.Text = sDepName;
    	txtDepNbr.Text = sDepNbr;
    
    	txtComp.Text = Convert.ToString(DT1.Rows[0][3]);
    	txtAmt.Text = Convert.ToString(DT1.Rows[0][6]);
    	}

    Back



    JAVASCRIPT

    JavaScript is a scripting language which is mainly used for enhancing the functionality of HTML-based webpages and is widely used in HTML to handle user events, do client-side verifications and provide dynamic features to webpages.

    Datatypes

    JavaScript is a loosely-typed language that doesn't require defining datatypes. It automatically changes the type of a variable depending on the data stored into the variable. The five different datatypes used are number, string, Boolean, function and object.

    Variables

    Variables are declared by using the var keyword.

    Local and Global Variables

    Variables can be local or global. Local variables are declared within a function and can be used only within that function. Global variables are declared outside a function (but within the SCRIPT tag) and can be shared by all functions.

    Statements

    Conditional statements - if, if..else and switch

    	var time = d.getHours()
    
    	if (time < 10) 
    	{
    		document.write("Good morning!")	}
    	else
    	{
    		document.write("Good day!")	}
    The following example uses the switch statement to create a redirection script based on the day of the week
    	<script language="JavaScript1.2">
    	var dateobj=new Date()
    	var today=dateobj.getDay()
    	switch(today){
    		case 1:
    			window.location="monday.htm"
    			break
    		case 2:
    			window.location="tuesday.htm"
    			break
    		......
    		case 7:
    			window.location="sunday.htm"
    			break
    			}
    	</script>

    Built-in objects

    JavaScript provides the following built-in object representations of corresponding HTML tags - window, frame, document, form, button, checkbox, hidden, fileUpload, password, radio, reset, select, submit, text, textarea, link, anchor, applet, image, plugin, area, history, location and navigator.

    The window, history, location and navigator objects do not have any corresponding html tags and the document object corresponds to the body tag.

    The window object

    This is the highest level JavaScript object which corresponds to the web browser window.

    Launching a new browser window

    The open method of the window object enables the launching of a new browser window. The following example shows the JavaScript code for launching a fresh window from a HTML link.
    	<A HREF= "#" OnClick="window.open('examples/sample.htm','Sample','toolbar=no,width=190,
    	height=190,left=500,top=200, status=no,scrollbars=no,resize=no');return false">

    The setTimeout method

    This method is used to call a function or evaluate an expression after a specified number of milliseconds. If an expression is to be evaluated, it must be quoted to prevent it being evaluated immediately. The use of this method does not halt the execution of any remaining scripts until the timeout has passed, it just schedules the expression or function for the specified time.

    The following example opens a new window and uses the setTimeout method to call the winClose() function which closes it after five seconds.
    	function winClose() {
    		 myWindow.close()
    	}
    
    	myWindow = window.open("", "tinyWindow", 'width=150, height=110')
    	myWindow.document.write("This window will close automatically after five seconds.")
    	self.setTimeout('winClose()', 5000)
    Redirecting a page to another page after a specific time

    The following code redirects the page after 5 seconds
    <script language="JavaScript">
    	setTimeout("top.location.href = 'http://www.somewhere.com/'",5000);
    	//--></script>

    The document object

    The document object represents the HTML document that is displayed in the browser window. The document object has various properties that refer to other objects which allow access to and modification of document content.

    Pre-loading of images

    One of the important uses of javascript is to pre-load images (load images in the background as the rest of the page loads). The browser will cache the images and then immediately display them wherever they are used on subsequent pages.
    	<SCRIPT LANGUAGE = JAVASCRIPT>
    	if (document.images)
    		{img1 = new Image();
    		 img2 = new Image();
    		 img1.src = "imageName1.gif";
    		 img2.src = "imageName2.gif";
    		}
    	</SCRIPT>

    The cookie object

    Writing a cookie

    The below makeCookie function writes a persistent cookie to the client machine
    	function getCookieExpireDate(noDays)
    	{
    		var today = new Date()
    		var expr = new Date(today.getTime()+noDays*24*60*60*1000)
    		return  expr.toGMTString()
    	}
    	function makeCookie(name, data, noDays){
    		var cookieStr = name + "="+ data
    		if (makeCookie.arguments.length > 2){
    			cookieStr += "; expires=" + getCookieExpireDate(noDays)
    		}
    		document.cookie = cookieStr
    	}
    Reading a cookie

    The below function reads the value stored in a cookie
    	function readCookie(cookieName)	
    	{
    		var searchName = cookieName + "="
    		var cookies = document.cookie
    		var start = cookies.indexOf(cookieName)
    		if (start == -1){ 		// cookie not found 
    			return "" }
    		start += searchName.length 	//start of the cookie data
    		var end = cookies.indexOf(";", start)
    		if (end == -1){
    			end = cookies.length	}
    		return cookies.substring(start, end)
    	}

    The form object

    Form is a property of the document object. It corresponds to an HTML input form constructed with the FORM tag.

    Properties of the form object:

  • action - This specifies the URL and CGI script file name the form is to be submitted to. It allows reading or changing the ACTION attribute of the HTML FORM tag.
  • elements - An array of fields and elements in the form.
  • encoding - This is a read or write string. It specifies the encoding method the form data is encoded in before being submitted to the server. It corresponds to the ENCTYPE attribute of the FORM tag. The default is "application/x-www-form-urlencoded". Other encoding includes text/plain or multipart/form-data.
  • length - The number of fields in the elements array. I.E. the length of the elements array.
  • method - This is a read or write string. It has the value "GET" or "POST".
  • name - The form name. Corresponds to the FORM Name attribute.
  • target - The name of the frame or window the form submission response is sent to by the server. Corresponds to the FORM TARGET attribute.

    Methods of the form object:

  • reset() - Used to reset the form elements to their default values.
  • submit() - Submits the form as though the submit button were pressed by the user.


    The navigator object

    The navigator object is the object representation of the client internet browser or web navigator program that is being used.

    The properties of the navigator object can be used to retrieve information about the client browser like the browser name, version etc.

    navigator.appName - Gives the name of the browser (application Name)
    navigator.appVersion - Gives the browser version (application Version)
    navigator.appCodeName - Gives the browser codename (application CodeName)
    navigator.platform - Gives the platform on which the browser is running
    navigator.userAgent - This property contains a string representing the value of the user-agent header sent by the client to the server in the http protocol.
    	<script language="JavaScript">
    	<!--var browser = navigator.appName;
    	var version = parseInt(navigator.appVersion);
    	document.write('Your browser is: ' + navigator.appName + ' ' + version + '<br>');
    	//--></script>

    Event handling

    The events which are handled include OnClick, OnFocus, OnBlur(losing focus), OnChange, OnSelect, OnLoad, OnUnload, OnReset, OnSubmit, OnMouseOver, OnMouseOut, OnError and OnAbort.

    Event Handlers

    Event handlers are JavaScript methods, i.e. functions of objects, that allow programmers to control what happens when events occur.

    The following is a list of the event handlers.
  • onAbort - The user aborts the loading of an image
  • onBlur - form element loses focus or when a window or frame loses focus.
  • onChange - select, text, or textarea field loses focus and its value has been modified.
  • onClick - object on a form is clicked.
  • onDblClick - user double-clicks a form element or a link.
  • onDragDrop - user drops an object (e.g. file) onto the browser window.
  • onError - loading of a document or image causes an error.
  • onFocus - window, frame, frameset or form element receives focus.
  • onKeyDown - user depresses a key.
  • onKeyPress - user presses or holds down a key.
  • onKeyUp - user releases a key.
  • onLoad - browser finishes loading a window or all of the frames within a frameset.
  • onMouseDown - user depresses a mouse button.
  • onMouseMove - user moves the cursor.
  • onMouseOut - cursor leaves an area or link.
  • onMouseOver - cursor moves over an object or area.
  • onMouseUp - user releases a mouse button.
  • onMove - user or script moves a window or frame.
  • onReset - user resets a form.
  • onResize - user or script resizes a window or frame.
  • onSelect - user selects some of the text within a text or textarea field.
  • onSubmit - user submits a form.
  • onUnload - user exits a document.

    onChange

    The onChange event is commonly used to redirect to different web pages depending on the option selected from a select element.
    	<SCRIPT LANGUAGE="JavaScript">
    	<!-- Start Hiding the Script
    
    	function jumpTo(URL_List){
    	   var URL = URL_List.options[URL_List.selectedIndex].value;
    	   window.location.href = URL;
    	}
    
    	// Stop Hiding script --->
    	</SCRIPT>
    
    
    	<FORM>
    	<SELECT NAME="site" onChange="jumpTo(this);">
    	<OPTION VALUE="http://www.umd.edu/">University of Maryland
    	<OPTION VALUE="http://www.annauniv.edu/">Anna University
    	<OPTION VALUE="http://http://www.ucsf.edu">Univ. of California, San Francisco
    	</SELECT>
    	</FORM>
    onResize

    The onResize even handler for the window object is used to execute specified code whenever a user or script resizes a window or frame. This allows programmers to query the size and position of window elements, dynamically reset SRC properties etc.

    The onResize event handler is used in the below code to reload the webpage on resizing the browser window.
    	<BODY onResize="location.reload()">
    onSubmit

    onSubmit is an event handler for the form object.

    The below code displays and alert message when the form is submitted
    	<FORM NAME="formName" onSubmit="alert('Form submitted')">
    	<INPUT TYPE="SUBMIT">
    	</FORM>
    The onSubmit event handler can be invoked in two instances, by the user pressing the submit button, or by another JavaScript submitting the form, e.g.
    	document.formName.submit();

    Back



    XML

    XML (Extensible Markup Language) is a universal format for data on the web that allows developers to easily describe and deliver rich, structured data from any application in a standard, consistent way.

    General structure of an XML file
    A simple XML file has the following structure:
    	<?xml version="1.0" standalone="yes"?>
    	<conversation>
    	  <greeting>Hello, world!</greeting>
    	  <response>That was a sample line.</response>
    	</conversation>

    Document Object Model (DOM)

    XML DOM is an object model that exposes the contents of an XML document. The W3C's Document Object Model (DOM) Level 1 Specification defines what a DOM should expose as properties, methods, and events. The XML DOM is used by creating an instance of an XML parser.

    Document Type Definition (DTD)

    The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements.
    A DTD can be declared inline within the XML document, or as an external reference.

    Building blocks of XML documents

    XML documents (and HTML documents) are made up by the following building blocks
  • Elements
  • Tags
  • Attributes
  • Entities
  • PCDATA
  • CDATA

    Elements

    Elements are the main building blocks of both XML and HTML documents. Examples of HTML elements are "body" and "table". Examples of XML elements could be "my-schedule" and "date". Elements can contain text, other elements, or be empty. Examples of empty HTML elements are "hr", "br" and "img".

    Tags

    Tags are used to markup elements. A starting tag like <element_name> mark up the beginning of an element, and an ending tag like </element_name> mark up the end of an element.
    	<body>body text in between</body>
    	<message>some message in between</message>
    Attributes

    Attributes provide extra information about elements. Attributes are placed inside the start tag of an element. Attributes come in name/value pairs. The following "img" element has an additional information about a source file
    	<img src="computer.gif" />
    The name of the element is 'img'. The name of the attribute is 'src'. The value of the attribute is 'computer.gif'. Since the element itself is empty it is closed by a ' /'.

    PCDATA

    PCDATA means parsed character data. Think of character data as the text found between the start tag and the end tag of an XML element. PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded.

    CDATA

    CDATA also means character data. CDATA is text that will not be parsed by a parser. Tags inside the text will not be treated as markup and entities will not be expanded.

    Entities

    Entities as variables used to define common text. Entity references are references to entities. A common example is the HTML entity reference: "&nbsp;" that is used to insert an extra space in an HTML document. Entities are expanded when a document is parsed by an XML parser. The following entities are predefined in XML: &lt (less than), &gt (greater than), &amp(ampersand), &quot (quotes), &apos (apostrophe)

    Inclusion of a DTD in an XML document

    The DTD is either contained in a <!DOCTYPE> tag, contained in an external file and referenced from a <!DOCTYPE> tag, or both. For e.g an XML document could contain the following tag
    	<!DOCTYPE Book [
    		<!ELEMENT Book (Title, Chapter+)>
    		<!ATTLIST Book Author CDATA #REQUIRED>
    		<!ELEMENT Title (#PCDATA)>
    		<!ELEMENT Chapter (#PCDATA)>
    		<!ATTLIST Chapter id ID #REQUIRED>
    	]>
    Declaring XML elements in a DTD

    An element declaration in a DTD has the following syntax:
    	<!ELEMENT element-name category>
    		or
    	<!ELEMENT element-name (element-content)>

    Empty elements

    Empty elements are declared with the category keyword EMPTY.
    	<!ELEMENT element-name EMPTY>
    
    	example:<!ELEMENT br EMPTY>
    	XML example:<br />
    Elements with only character data

    Elements with only character data are declared with #PCDATA inside parentheses.
    	<!ELEMENT element-name (#PCDATA)>
    
    	example:<!ELEMENT from (#PCDATA)>
    Elements with any contents

    Elements declared with the category keyword ANY, can contain any combination of parsable data.
    	<!ELEMENT element-name ANY>
    
    	example:<!ELEMENT note ANY>
    Elements with children (sequences)

    Elements with one or more children are defined with the name of the children elements inside parentheses.
    	<!ELEMENT element-name 
    	 (child-element-name)>
    	or
    	<!ELEMENT element-name 
    	 (child-element-name,child-element-name,.....)>
    
    	example:<!ELEMENT note (to,from,heading,body)>
    When children are declared in a sequence separated by commas, the children must appear in the same sequence in the document. In a full declaration, the children must also be declared, and the children can also have children. The full declaration of the "note" element will be
    	<!ELEMENT note (to,from,heading,body)>
    	<!ELEMENT to      (#PCDATA)>
    	<!ELEMENT from    (#PCDATA)>
    	<!ELEMENT heading (#PCDATA)>
    	<!ELEMENT body    (#PCDATA)>
    Declaring only one occurrence of the same element

    	<!ELEMENT element-name (child-name)>
    
    	example:<!ELEMENT note (message)>
    The example declaration above declares that the child element message must occur once, and only once inside the "note" element.

    Declaring minimum one occurrence of the same element

    	<!ELEMENT element-name (child-name+)>
    
    	example:<!ELEMENT note (message+)>
    The + sign in the example above declares that the child element message must occur one or more times inside the "note" element.

    Declaring zero or more occurrences of the same element

    		<!ELEMENT element-name (child-name*)>
    
    		example:<!ELEMENT note (message*)>
    The * sign in the example above declares that the child element message can occur zero or more times inside the "note" element.

    Declaring zero or one occurrences of the same element

    		<!ELEMENT element-name (child-name?)>
    
    		example:<!ELEMENT note (message?)>
    The ? sign in the example above declares that the child element message can occur zero or one times inside the "note" element.

    Declaring either/or content

    		example:<!ELEMENT note (to,from,header,(message|body))>
    The example above declares that the "note" element must contain a "to" element, a "from" element, a "header" element, and either a "message" or a "body" element.

    Declaring mixed content
    		example:<!ELEMENT note (#PCDATA|to|from|header|message)*>
    The example above declares that the "note" element can contain parsed character data and any number of "to", "from", "header", and/or "message" elements.


    XML Schemas

    XML can be typed (has an associated schema) or untyped. AN XML schema can be created using XSD (XML schema definition), which is a formal language that defines the structure and constraints of typed xml data.


    SOAP

    SOAP (Simple Object Access Protocol) is a lightweight XML-based protocol for the exchange of information in a decentralized, distributed environments. SOAP consists of three parts - an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined data types, and a convention for representing remote procedure calls and responses. SOAP can potentially be used in combination with a variety of other protocols.

    Comparison of SOAP and RPC

    RPC is a programming model that allows developers to work with method calls. SOAP allows for any programming model and is not tied to RPC.

    RPC uses request/response.SOAP allows for any number of message exchange patterns (MEPs), of which request/response is just one. Other examples include solicit/response (the reverse of request/reponse), notifications, and long running peer-to-peer conversations.

    RPC requires a translation of the method signature into SOAP messsages. Due to the popularity of RPC, SOAP outlines a convention for using RPC with SOAP.

    The fundamental styles of SOAP messaging

    There are two fundamental styles of SOAP messaging: document and RPC. Document style indicates that the body simply contains an XML document whose format the sender and the receiver must agree upon. RPC style, on the other hand, indicates that the body contains an XML representation of a method call.


    Web services

    XML Web services

  • XML Web Services expose useful functionality to Web users through a standard Web protocol. In most cases, the protocol used is SOAP.
  • XML Web services provide a way to describe their interfaces in enough detail to allow a user to build a client application to talk to them. This description is usually provided in an XML document called a Web Services Description Language (WSDL) document.
  • XML Web services are registered so that potential users can find them easily. This is done with Universal Discovery Description and Integration (UDDI).

    Basic structure of an ASP.NET web services file

    ASP.NET web services files have the extension .asmx and these are text files just like .aspx files and are URI-addressable.
    This is a simple web services file:
    	<%@ WebService Language="C#" Class="HelloWorld" %>
    
    	using System; 
    	using System.Web.Services;
    	 
    	public class HelloWorld : WebService {
    
    		[WebMethod] public String SayHelloWorld() {
    			return "Hello World";
    		 }
    	}
    The file starts with an ASP.NET directive WebService, and sets the language to C#, Visual Basic, or JScript. Next, it imports the namespace System.Web.Services (must include this namespace). Next, the class HelloWorld is declared. This class is derived from the base class WebService (optional). Finally, any methods that will be accessible as part of the service have the attribute [WebMethod] in C# or in Visual Basic, in front of their signatures.


    WSDL

    WSDL or Web Services Description Language defines an XML-based grammar for describing network services as a set of endpoints that accept messages containing either document- or procedure-oriented information. The operations and messages are described abstractly. They are bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services). WSDL is extensible to allow the description of endpoints and their messages regardless of what message formats or network protocols are being used to communicate.

    Components of WSDL

    The WSDL grammar contains the following elements that are used together to describe endpoints:
    - Message: References to XML Schemas defining the different parts of the message (e.g Headers and Body).
    - Operation: Lists the messages involved in one message flow of the endpoint. For e.g a request-response operation would refer to two messages.
    - PortType: The set of message flows (operations) expected by a particular endpoint type, without any details relating to transport or encoding.
    - Binding: The transport and encoding particulars for a portType.
    - Port: The network address of an endpoint and the binding it adheres to.
    - Service: A collection of related endpoints.

    Back



    SHAREPOINT

    Custom applications

    Custom .aspx pages and web applications can be created and stored in a location that is accessible from all Web sites in a Windows SharePoint Services (WSS) deployment. Also web applications can be created that contain custom code that works with the global settings for the deployment.

    Location for Custom ASPX Pages and Web Applications

    Custom .aspx pages and Web applications can be built and stored in the following directory, which supports the _layouts virtual directory
    	Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS
    Pages in this directory are accessible from all Web sites in the WSS deployment through a URL in the following form
    	http:// Server /[ sites/ ][ Site ]/[ SubSite ]/[.../]_layouts/File_Name.aspx
    Location for Custom Code that Works with Global Settings

    For code that involves use of only the Microsoft.SharePoint.Administration namespace for working with global settings in a WSS deployment, it is recommended that the Web application is created on the administrative port and.aspx pages and Web applications are built and stored in the following directory:
    	Local_Drive :\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\ADMIN
    Pages in the \ADMIN directory are accessible through a URL in the following form
    	http:// Server:Port_# /_admin/ File_Name .aspx


    Webparts

    Web Parts are server-side controls that run inside the context of special pages (Web Part Pages) within an ASP.NET application or a WSS site. They are the 'building blocks' of pages in WSS. Windows SharePoint Services includes built-in Web Parts that can be used after installing the product. In addition, custom Web Parts can be built and deployed to the server.

    Types of Web Parts in WSS

    There are two different Web Part styles in WSS.

    SharePoint-based Web Parts - The older style Web Parts have a dependency on Microsoft.SharePoint.dll and must inherit from the WebPart base class in the Microsoft.SharePoint.WebPartPages namespace. These Web Parts can only be used in SharePoint Web sites, but in WSS 3.0, the Microsoft.SharePoint.dll was changed so that Web Parts written in the older style would be compatible with the WSS 3.0 runtime.

    ASP.NET Web Parts - These Web Parts are built on top of the ASP.NET Web Part infrastructure. The newer ASP.NET-style Web Parts have a dependency on System.Web.dll and must inherit from a different base class named WebPart in the System.Web.UI.WebControls.WebParts namespace. These Web Parts can be used in WSS applications whether WSS is involved or not, making them highly reusable.

    Note: When creating a Web Part specifically for a SharePoint site consuming the WSS object model, we can derive from the ASP.NET System.Web.UI.WebControls.WebParts.WebPart base class and add a reference to the SharePoint object model in the project.

    More about ASP.NET Web Parts

    The WSS 3.0 Web Part infrastructure is built on top of a control named SPWebPartManager that is derived from the ASP.NET WebPartManager control. The SPWebPartManager control overrides the standard behavior of the WebPartManager control to persist Web Part data inside the WSS content database instead of in the ASP.NET services database. In most cases, there is no worry about dealing directly with the SPWebPartManager control because the one and only required instance is already defined in default.master. When a content page is created that links to default.master, the SPWebPartManager control is already there.

    Note: Web Part zones for a Web Part Page in WSS 3.0 should be created by using the WebPartZone control defined inside the Microsoft.SharePoint.WebPartPages namespace, not by using the standard WebPartZone control from ASP.NET

    When a Web Part Page is created for a standard ASP.NET application, logic needs to be added that interacts with the WebPartManager control to manage the Web Part display mode, and generally editor parts and catalog parts need to be explicitly added to the page along with the HTML layout to accommodate them. These changes don't need to be performed when creating content pages for a WSS site. Instead, we inherit from the WebPartPage class that is defined inside the Microsoft.SharePoint.WebPartPages namespace and it does all the work behind the scenes.


    Custom Web Parts

    Custom Web Parts provide developers with a method to create user interface elements that support both customization and personalization. A site owner or a site member with the appropriate permissions can customize Web Part Pages by using a browser or by using MS Office SharePoint Designer to add, reconfigure or remove a Web Part.

    In WSS, developers can extend SharePoint sites by creating custom Web Parts, to add the extra dimensions of user customization and personalization. The term customization implies that changes are seen by all site members. Individual users can further personalize Web Part Pages by adding, reconfiguring and removing Web Parts and these changes will be seen only by the user that made them. Developing custom Web Parts provides an easy and powerful way to extend WSS sites.

    Because the WSS Web Part infrastructure is built on top of the ASP.NET Web Parts control set, knowledge of ASP.NET programming can be reused to create quick and robust custom Web Parts.

    Benefits of custom Web Parts
  • Creating custom properties to display and modify in the user interface
  • Improving performance and scalability. A compiled custom Web Part runs faster than a script
  • Implementing proprietary code without disclosing the source code
  • Securing and controlling access to content within the Web Part. Built-in Web Parts allow any users with appropriate permissions to change content and alter Web Part functionality. With a custom Web Part, the content or properties can be determined to display to users, regardless of their permissions.
  • Web Parts can be made connectable, allowing them to provide or access data from other connectable Web Parts
  • Interacting with the object models that are exposed in WSS. For e.g a custom Web Part can save documents to a WSS document library
  • Controlling the cache for the Web Part by using built-in cache tools. For e.g these tools can be used to specify when to read, write or invalidate the Web Part cache
  • Benefiting from a rich development environment with debugging features that are provided by tools such as Microsoft Visual Studio
  • Creating a base class for other Web Parts to extend. For e.g to create a collection of Web Parts with similar features and functionality, create a custom base class from which multiple Web Parts can inherit. This reduces the overall cost of developing and testing subsequent Web Parts
  • Controlling the implementation of the Web Part. For e.g a custom server-side Web Part can connect to a back-end database or be compatible with a broader range of Web browsers

    Deploying Webparts

  • Method 1 - manual

    Copy assembly DLL to either
    - /bin directory for a given IIS virtual server (e.g., c:\inetpub\wwwroot\bin)
    - Global Assembly Cache (e.g., c:\windows\assembly)

    Copy DWP file to C:\Inetpub\wwwroot\wpcatalog

    Copy resources to
    - For GAC-registered parts, C:\Program Files\Common Files\Microsoft Shared\web server extensions\wpresources
    - For Web Parts in the /bin directory, C:\Inetpub\wwwroot\wpresources

    Adjust web.config
    - Register as SafeControl
    - Select Code Access Security settings

  • Method 2: CAB File

    CAB file should contain
    -Assembly DLL
    -DWP file(s)
    -Manifest.XML
    -Resource files (if needed)


    CAB won't contain - Code Access Security settings

    Server-side object model has methods for deploying such a CAB file

    Deploy with STSADM.EXE, Located in C:\Program Files\Common Files\Microsoft Shared\web server extensions\60\BIN
    Add it to the path
    Stsadm -o addwppack -filename filename [-globalinstall] [-force]

  • Method 3: MSI File via WPPackager

    All of the features of CAB file deployment, but with
    - Code Access Security support
    - Ability to uninstall via Control Panel

    Get WPPackager.exe

    Add additional files to project for use by WPPackager

    Run WPPackager after project is built


    Sample Web Part

    	using Microsoft.SharePoint.WebPartPages;
    
    	public class SimpleWebPart : WebPart
    	{
    
    		protected override void RenderWebPart(HtmlTextWriter output)
    		{
    			RenderChildren(output);
    		}
    		
    		Button saveTitle;
    		TextBox newTitle;
    
    		public void saveTitle_click(object sender, EventArgs e)
    		{
    			this.Title = newTitle.Text;
    			try
    			{
    			  this.SaveProperties = true;
    			}
    			catch (Exception ex)
    			{
    			  this.Title = "Error: " + ex.Message;
    			}
    		}
    
    		protected override void CreateChildControls()
    		{
    			//Create text box
    			newTitle = new TextBox();
    			newTitle.Text = "";
    			Controls.Add(newTitle);
    
    			//Create button
    			saveTitle = new Button();
    			saveTitle.Text = "Set Web Part Title";
    			saveTitle.Click += new EventHandler(saveTitle_click);
    			Controls.Add(saveTitle);
    		}
    	}

    Steps in web part development

  • Create a Web Control Library project

    Web Parts are based on ASP.NET Web Form Controls and created in C# by using the ASP.NET Web Control Library template.

  • Add a Reference to Microsoft.SharePoint.dll

  • Set the Version Number and set up partially trusted callers

    By default, the AssemblyVersion property of the project is set to increment each time the Web Part is recompiled. A Web Part page identifies a Web Part with the version number that is specified in the web.config file. With the AssemblyVersion property set to increment, recompiling the Web Part after importing it into a Web Part page can cause an error since the Web Part framework will look for the version number specified in the web.config file. The version number of the Web part needs to be set in the AssemblyInfo file to prevent it from incrementing at each recompilation.

    Since signed code is being created, the assembly must be told to allow partially trusted code calls. By default, any strong-named assembly that does not explicitly opt in to its use by partially trusted code will be callable only by other assemblies that are granted full trust by security policy.

    To set the version number and allow partially trusted callers In Solution Explorer, double-click the AssemblyInfo file
    Edit the line [assembly: AssemblyVersion("1.0.*")] so that it reads [assembly: AssemblyVersion("1.0.0.0")]
    Add the following line to the top of the file: using System.Security;
    Add the following line to the bottom of the file: [assembly: AllowPartiallyTrustedCallers]
  • Rename the Class and Namespace

  • Add a Namespace Directive

  • Inherit from the Web Part Class

    By default, the Web Control Library template creates a custom control that inherits from the System.Web.UI.Control class (a parent class of both the ASP.NET and SharePoint WebPart classes). A SharePoint Web Part should inherit from the Microsoft.SharePoint.WebPartPages.WebPart base class.

  • Use the RenderWebPart Method

    WebPart.RenderWebPart Method (Microsoft.SharePoint.WebPartPages) renders the HTML for the body of a Web Part to the client.

    Namespace: Microsoft.SharePoint.WebPartPages
    Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

    	protected virtual void RenderWebPart (
    		HtmlTextWriter output
    	)
    Parameters - output, The HtmlTextWriter object that receives the Web Part content.

    The below example shows an overridden RenderWebPart method that renders HtmlTextBox and HtmlButton controls. This code example is part of a larger example provided for the WebPart class.
    	protected override void RenderWebPart(HtmlTextWriter output)
    	{
    		_mytextbox.RenderControl(output);
    		_mybutton.RenderControl(output);
    	}
  • Define the Logic and Rendering of the Web Part

  • Create a Valid Strong Name for the Assembly

    Web Parts are designed to be distributed over the internet or an intranet. For security reasons, when a custom Web Part is created, a strong name should be given to ensure that the Web Part can be trusted by its users.

    To assign a strong name to an assembly In Solution Explorer, right-click on the SimpleWebPart project and click Properties
    In the SimpleWebPart properties, click the Signing tab on the left side
    On the Signing tab, check the Sign the assembly checkbox
    Select New in the Choose a strong name key file drop-down menu
    In the Create Strong Name Key dialog, type SimpleWebPartKey and uncheck Protect my key file with a password
    Now, the assembly will be signed when it is built.

  • Build the Web Part

  • Copy the DLL to the Bin Directory

    To copy the DLL to the bin directory On the file system, locate the SimpleWebPart.dll file. The default location is C:\...\Projects\SimpleWebPart\SimpleWebPart\bin\Debug
    Copy the SimpleWebPart.dll file from the output directory to the Web application root bin directory. The default location of the Web application root is C:\Inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin
  • Increase the Default Trust Level and Add a SafeControl Entry for the Web Part

    To increase the default trust level and add a SafeControl entry Open the web.config file in the Web application root
    In the level attribute of the trust section, change WSS_Minimal to WSS_Medium
    In the SafeControls section of your web.config file, add a SafeControl entry for the custom assembly as follows
     
    	<SafeControl Assembly="SimpleWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=PublicKeyToken" 
    	Namespace="MyWebParts" TypeName="SimpleWebPart" Safe="True"/>
    Replace the PublicKeyToken with the actual value for the Web Part's assembly. To determine the correct PublicKeyToken for the Web Part, use the sn.exe command-line utility
    	sn.exe -T C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\SimpleWebPart.dll
  • Create a DWP File to Deploy the Web Part

    A Web Part definition file (.dwp) is a simple XML file that contains property settings for a single Web Part. To import the Web Part into a Web Part page, simply upload the .dwp file. After uploading the Web Part, the Web Part can be displayed by dragging it into one of the zones of the Web Part page.

    Two properties are required in the .dwp file: Assembly and TypeName. However, to display a default name and description for the Web Part after it is imported, the Title and Description properties should also be included. If other Web Part properties need to be set during import, they can be defined in a .dwp file. A .dwp file takes the following form.

    To create a DWP file

    Copy and paste the following XML into a new text file.
    	<?xml version="1.0"?>
    	<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
    		<Assembly>SimpleWebPart, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=PublicKeyToken</Assembly>
    		<TypeName>MyWebParts.SimpleWebPart</TypeName>
    		<Title>My Simple Web Part</Title>
    		<Description>A simple Web Part</Description>
    	</WebPart>
    Save this file as SimpleWebPart.dwp in the bin directory of the Web application root.

  • Import the Web Part into a Web Part Page

    To use and test the Web Part, import it into a Web Part page on a server that is running WSS or MS Office SharePoint Server.

    To import the Web Part Navigate to the page on the SharePoint site where the Web Part needs to be accessible
    In the Web Part page, click Site Actions, and select Site Settings
    On the Site Settings page, click Web Parts under the Galleries heading
    On the toolbar in the Web Part gallery, click Upload
    On the Upload Web Part page, click Browse and select the .dwp file that was created (should be in C:\inetpub\wwwroot\wss\VirtualDirectories\PortNumber\bin\). Click ok
    Navigate back to the Web Part page. In the Web Part page, click Site Actions, and select Edit Page
    In the preferred zone, click Add a Web Part and check the box next to My Simple Web Part in the dialog box. Click Add
    After the Web Part is added to the zone, type some text in the text box and click Set Web Part Title to test the Web Part.

    DataViewer web part
    	using System;
    	using System.Data; 
    	using System.Collections.Generic;
    	using System.ComponentModel;
    	using System.Linq;
    	using System.Text;
    	using System.Web;
    	using System.Web.UI;
    	using System.Web.UI.WebControls;
    	using System.Web.UI.WebControls.WebParts;
    	using System.Data.SqlClient; 
    
    	namespace DataViewer
    	{
    		public class DbAccess
    		{
    			private string strConnection;
    			public DbAccess()
    			{
    			}
    
    			public string StrConnection
    			{
    				get { return strConnection; }
    				set { strConnection = value; }
    			}
    
    			public DataTable GetSQlResult(string sql)
    			{
    				DataTable dt = new DataTable();
    
    				try
    				{
    					SqlConnection cnn = new SqlConnection(strConnection);
    					SqlDataAdapter da = new SqlDataAdapter(sql, cnn);
    					da.Fill(dt);
    					return dt;
    				}
    				catch (Exception ex)
    				{
    					return dt;
    				}
    			} 
    		} 
    
    		public class DataViewer : WebPart
    		{
    		//the RenderContents method is commented  because the CreateChildControls method will be used 
    		//to display the gridview in the webpart. 
    
    		//protected override void RenderContents (HtmlTextWriter output)
    		//{
    		//	output.Write ("Data Viewer  Text");
    		//}
    
    
    		protected override void CreateChildControls()
    		{ 
    
    				base.CreateChildControls();
    
    			try
    			{
    			GridView gv = new GridView();
    			DBAccess objDB = new DBAccess();
    			string StrConn = "UID=sa;PWD=dbadmin;Initial Catalog=hrdata;Data Source=Testserver1;";
    			string sql = "select fname, lname, title, dept from [emp] order by fname";
    			objDB.StrConnection = strConn;
    
    			DataTable dt = new DataTable();
    			dt = objDB.GetSQLResult(sql);
    
    			Controls.Add(gv);
    			gv.DataSource = dt;
    			gv.AlternatingRowStyle.BackColor = System.Drawing.Color.WhiteSmoke;
    			gv.GridLines = GridLines.Horizontal;
    			gv.CellPadding = 1;
    			gv.DataBind();
    			gv.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
    			}
    
    			catch (Exception ex)
    			{
    			Label lbl = new Label();
    			lbl.Text = "Error Occurred : ";
    			lbl.Text += ex.Message;
    			Controls.Add(lbl);
    			}
    
    		} 
    		}
    	}

    Sharepoint object model

    Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, the object hierarchy can be navigated to obtain the object that contains the members needed to use in the code.

    For creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, members of the Microsoft.SharePoint.SPContext class can be used to obtain the current site collection, Web site, or list. When a Web application is created in the /_layouts virtual directory, its functionality becomes available to all sites on the Web server. Outside of an HTTP context, such as in a console application or a Windows application, a constructor of the SPSite class can be used to obtain a specific site collection and to reach various objects within the collection.

    Server Architecture

    The SPFarm object is the highest object within the SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.

    Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.

    Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for e.g objects for Windows services (like the timer service), search, SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the MS Office system.

    An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.

    An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.

    Each SPWebApplication object represents a load-balanced Web application based in IIS. The SPWebApplication object provides access to credentials and other server farm-wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; i.e a set of one or more physical servers that appear as a single server to users.

    An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.

    An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.

    Site Architecture

    Each SPSite object, despite its singular name, represents a set of logically related SPWeb objects. Such a set is commonly called a site collection, but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWeb method of the SPSite class returns a specific Web site.

    Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.

    Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.

    Each SPField object has members that contain settings for the field.

    Each SPListItem object represents a single row in the list.

    Back


    Maintained by: Vincent Kandasamy, Database Architect/Administrator (kandasf@hotmail.com)
    Last Updated on: Jul 10 19:42