Introduction to .NET Framework 3.0/Print version


Introduction to .NET Framework 3.0

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Introduction_to_.NET_Framework_3.0

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

An Overview

The .NET Framework 3.0 has been created mainly as an extension of .NET 2.0. Hence, Microsoft assures us that most of the features of .NET 2.0 would be workable with .NET 3.0. Migration from .NET 2.0 to .NET 3.0 is easy as it involves only the upgradation of the features and not a complete installation of the .NET 3.0 framework. Applications written and run in .NET 2.0 will still continue to run in .NET 3.0 without affecting the execution of .NET 3.0 specific applications.Components shared with the .NET Framework 2.0 are installed at %windir%\Microsoft.NET\Framework\V2.0.50727. Components that are new to the .NET Framework 3.0 are installed to %windir%\Microsoft.NET\Framework\V3.0.

Released on November 6, 2006, .NET Framework 3.0 was designed to be shipped as an integral part of Windows Vista Operating System and Windows Server 2008 . Nevertheless, .NET 3.0 also works fine with Windows XP and Windows Server 2003.

.NET 3.0 does not contain any major architectural change from .NET Framework 2.0. The only significant change is the inclusion of four major components: Windows Communication Foundation, Windows Presentation Foundation, Windows Cardspace and Windows Workflow Foundation. These components contain modules of code in order to reduce complexity and to make programming simpler, faster and easier.

.NET Framework 3.0 includes version 2 of the Common Language Runtime(CLR).

A better idea of the .NET Framework can be obtained by visiting the official .NET 3.0 site www.netfx3.com.You can experience for yourself the features of .NET Framework 3.0 by registering and using Windows Vista simulations at Microsoft .NET 3 Virtual Labs

References ======================================================================================================================================================================================================================================================================================

edit
  1. http://msdn2.microsoft.com/en-us/netframework/aa663314.aspx


Advantages of .NET 3.0

The latest version of .NET i.e. .NET 3.0 has a number of advantages.

  • Development Time is reduced.
  • WPF provides tools to create graphically enhanced documents and web pages.
  • WWF facilitates the user to make a model of the development process.
  • WCF makes construction of distributed systems easier.

References

edit
  1. http://www.shinetechchina.com/tech/DotNet.htm


An Overview of Master Pages

Masterpages were introduced for the first time in .NET framework 2.0 in order to create an application in which multiple files have similar content. The content for which masterpages have been created include headers, trailers, etc. For sites which have a common header for all the pages, it is difficult and hectic to ensure that the same header has been inserted into the code of each page and to ensure uniformity in text alignment, etc. To overcome this drawback, we use master pages. In .NET 1.1, cascading style-sheets were used to perform this function. However, in .NET 3.0, these stylesheets were replaced by masterpages.

Introduction

edit

The syntax used to denote a masterpage is

<%@ Master Language="C#" %>
<%@ Master Language="C#" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>


This specifies that the page is a masterpage and is given at the start of the page.

The ASP.NET page which inherits content from a masterpage has the following tag in it.

<%@ Page Language="VB" MainPageFile="~/MainPages/Master1.main" Title="Content Page" %>

Use of Master Pages

edit

Creating a Master Page

edit
  1. Create a New Project
  2. Add a master page to the project. This could be done by clicking 'Add New Item' and selecting 'Masterpage' from the list of items displayed.
  3. Open the masterpage and enter the contents to be displayed just above the ContentPlace Holder object.
  4. Right-click on the project and click 'Add New Item'. Select 'Web Page' and check 'Select Master Page' option and click 'Ok'. The project folder dialog box will be displayed. Select the masterpage file (.master) from the list of files displayed and click 'Ok'. The file gets created and you will observe that a 'content' object gets created by default. This tag is created when a masterage is selected. If no masterpages are required in the page then this tag can be removed.
  5. Run the file. You will observe that the content specified on top of the ContentPlaceHolder in the Masterpage file appears on the Web page.

Nested Masterpages

edit

It is also possible to nest one masterpage inside another. The designer doesn't support nesting of master pages; however, two or more masterpages could be nested at the code level.

SiteMaster.master

edit

The SiteMaster page is made up exclusively of the Content control.

<asp:contentplaceholder id="SiteContentPlaceHolder" runat="server">
<h1>Site Master Page</h1></asp:contentplaceholder>

Section Master

edit

Section masterpages inherit from the site master. Syntax of a site master page is given below.

<asp:contentplaceholder id="SiteContentPlaceHolder" runat="server">
<h1>Site Master Page</h1></asp:contentplaceholder>

Scoping Masterpages

edit

Masterpages could be specified either at the page or folder or application level.

Criticism of Masterpages

edit

One complaint against master pages is that the head HTML tag is defined in the master page. This element must be shared across all pages that take their layout from the master. Several options are available to work around this issue, including modifying the head content at Runtime using Server-side code. The title, however, is freely editable via the title attribute in the master page file declaration at the top of a content page. It is actually possible to place a ContentPlaceHolder control inside the head section of the master page, although Visual Studio 2005 will generate warnings. Unfortunately, markup placed inside the associated Content control is rendered as a literal. The HtmlHead object contains specialized parsing routines to recognize elements such as link and script. This parsing code is not applied to children of a child ContentPlaceHolder control. However, there is a workaround for this. If each link and script control uses the runat="server" attribute, then they will be parsed by ContentPlaceHolder as individual HtmlGenericControls. Code can then be written to iterate through each HtmlGenericControl and replace it with the appropriate control type (HtmlLink, HtmlMeta, etc.) after performing attribute mapping.[citation needed]

References

edit
  1. http://www.codersource.net/asp_net_master_pages_whidbey.aspx


Caching

There are three types of caching supported by .NET 3.0

  • Absolute Expiration Caching
  • Sliding Caching
  • Cache Dependency Expiration caching

Absolute Expiration Caching

edit

This is a form of caching wherein the expiration time is specified in advance. After a specific period of time, the contents of the cache get deleted.

Sliding Caching

edit

Here, a time span is specified up to which the program checks for access. If no individual has accessed the site till the time span has expired, then the contents of the cache get deleted. So here, the time-span of the cache depends upon the popularity of the site.

Cache Dependency Expiration

edit

In cache dependency expiration, the timespan of the cache depends on when the particular item on which the data is dependent is changed.


Generics

Microsoft has introduced new generical features in its .NET 3.0. Until now, it was mandatory that the whole list should be declared as a single data type. However, in .NET 3.0, it is possible to have multiple declarations of the same list with multiple data type and the datatype of the data contained in it changes.

Example

edit
List<string> customerList = new List<string>(); 
customerList.Add('Ravi');
customerList.Add('Bala');
List<int> customerList = new List<int>();
customerList.Add(1);


Nullable Types

.NET 3.0 supports nullable data types. Previously, nullification of only 'int' values were supported by .NET. However, this addition comes as a big boon to developers who might find it easy even to have 'null date-time' values and the kind. Values might be nullifed in .NET by placing a '?' after the datatype name in the variable declaration

Examples

int? num = null;
DateTime? dt = null;

Note: Nullable support is available since .Net 2.0


Windows Presentation Foundation

Windows Presentation Foundation (codenamed:Avalon) is a new feature (a presentation platform) introduced with .NET Framework 3.0 which supports the creation of documents containing high-resolution pictures and graphics. WPF is also responsible for the integration of pictures and media in ordinary documents. At present, the component performing this function is Windows Forms.

What is Windows Presentation Foundation
edit

A productive, unified approach to UI, media and documents to deliver unmatched user experience

WPF Infrastructure

edit

The Presentation Foundation contains classes to create 'Print' and 'File Open' dialog boxes, script new windows, etc. It makes use of four specific classes most of the time:

  • UIElement
  • FrameworkElement
  • ContentElement
  • FrameworkContentElement

These classes help in building an effective and easy to use user interface. The WPF UI is usually in the form of a Element Tree. Element Trees used in WPF are of two types:

  • Logical Tree
  • Visual Tree

Element Trees are usually implemented in XAML by dragging and dropping and creating relationships between the concerned elements. In code, they depend on how we give property values for properties.

The logical tree involves creating a tree structure by adding a listbox tag and list items inside the tag. In the case of a DockPanel we use Children property.

The visual tree is mainly used by programmers who want to meddle with the underlying low-level components of the program.

Combination of Markup and Programming

edit

While the usage of a programming language as C# is best recommended for programming logic, the usage of markup languages is recommended for texts and UIs.

In earlier versions of the .NET framework, the designer part was separate from the code. However, in .NET 3.0, both the designer part programmed in XAML and the logic programmed in C# are included in the same code.

XAML File
<Canvas ID="root“ xmlns="http://schemas.microsoft.com/2003/xaml“>
	<Button Click="Button_Click">Click Me!</Button>
</Canvas>

C# code-behind file 
using…
namespace Button
{
	public partial class Default : Panel
	{     // Event handler
		   void Button_Click (object sender, System.Windows.Controls.ClickEventArgs e)
 	       {    btn1.Background = System.Windows.Media.Brushes.Red;  }
	}
}

Graphics

edit

Windows Presentation Foundation enables the user to create graphic applications of high-quality. You could add existing or create custom buttons using <button> tag, create docked panels, 2D and 3D graphical images, use color picker controls, create or modify images, videos, create custom medi players, etc.

Drawing Object Model

edit

The WPF graphics system offers a completely new programming style. With Win32-based UI technologies, if you want to draw customized graphics, you must write code that responds to repaint requests, drawing the details on demand. This code effectively paints directly to the screen. If that part of the screen becomes obscured by another window and then uncovered, Windows sends a message requesting that this be redrawn. If you want to change the appearance of your graphics, you need to instruct Windows to invalidate the relevant areas of the screen in order to initiate a repaint.

Richly Formatted Text

edit

WPF also helps us create formatted text easily and hence rich formatting could be used. The contents are enclosed within a <textblock> tag.

User Events could be executed easily by using triggers which are specified using the <trigger> tag. Apart from this, there are many other new innovations in WPF.

Templates and Styles

edit

There are two types of templates: Data Templates and Control Templates. Control Templates define the control and the visual structure of the control.

Syntax:

ControlTemplate x:Key=“MyButton” TargetType=“{x:Type Button}”>
    <Grid>
        <Ellipse />
        <ContentPresenter />
    </Grid>
</ControlTemplate>

On the contrary, data templates contain specifications about the data to be stored.


Syntax:


<DataTemplate DataType=“{x:Type PhotoObject}”>
    <Image Source=“{Binding FileName}” />
</ControlTemplate>

Styles are used to specify the syles of buttons used.

<Style x:Key=“MyStyle” TargetType=“{x:Type Button}”>
</Style>

Styles can also be based on other styles.

Style x:Key=“MyStyle” BasedOn=“{StaticResource BaseStyle}” />
    <Setter Property=“Background” Value=“Green” />
</Style>

Documents

edit

WPF supports three kinds of documents

  • Fixed Documents
  • Flow Documents
  • XPS Documents


WPF has introduced new concepts which make the integration of text with media files easier. WPF also supports a variety of fonts which were not handled by earlier versions.

Fixed Documents

edit

Fixed Documents are representative of WYSIWYG ("What you see is what you get") principle. Here, what you see on the screen indicates the actual layout that you will get on paper when the page is printed. Hence, even slight changes to the layout shall be critical.

Flow Documents

edit

Flow Documents are those document formats which adjust their size, readability, dimensions, etc. depending on the size of the screen. Documents of this type are also supported by WPF.

XPS Documents

edit

XPS documents are those which are exact representations of how the document shall look on paper. They resemble scanned images of the document itself.

Benefits

edit
  • Ease of Use -- Learn ability, Performance, Reliability, Security, Optimized form factors, Legibility / Readability, Relevance / Contextualization
  • Richness -- Graphics & Media, Data Visualization, Higher Fidelity Information, Globalization, Accessibility, Hardware & Printing Integration.

References

edit
  1. http://msdn2.microsoft.com/en-us/windowsvista/aa905016.aspx#Understanding%20Windows%20Presentation%20Foundation:%20Essential%20Concepts
  2. http://msdn2.microsoft.com/en-us/library/aa970268.aspx#Windows_Presentation_Foundation_Applications
  3. http://www.dotnet-u.com/


Windows Communication Foundation

Windows Communication Foundation (codenamed: Indigo) is a new Windows Vista framework designed to make it easier for application in computer or across multiple computers in a network to communicate.

It is one of the four main application development interfaces brought with .NET Framework 3.0. It is compatible for usage with Microsoft Windows XP, Windows 2003, Windows Longhorn Server and Microsoft Windows Vista.

Windows Communication Framework (WCF) combines the features of .NET Remoting, Web services, Distributed Transactions and Message Queues.

WCF uses SOAP messages for communication. When a WCF process communicates with a non–WCF process, XML-based encoding is used for the SOAP messages but when it communicates with another WCF process, the SOAP messages are encoded in an optimized binary format.

WCF Service

edit

A WCF service is made of three components: A service that implements the service to be provided, a host environment where the service runs and one or more endpoints or contracts

WCF provides unification, interoperability and service-oriented development.

Types of Contracts

edit

There are three different types of contracts in use:

  • Service Contracts
  • Data contracts
  • Operation Contracts

Service Contracts

edit

The service contracts refer to the entire service.

A service contract is not different from a webservice but only a part of the service

.

Service Contracts are a group of classes designated as operations. A service contract has a 'service contract' tag as seen in the following example.


[ServiceContract]
interface IMa
{


It performs multiple operations through its different classes. Each of these classes is designated as an "operation".

Classes may be used as service contracts but it is generally recommended that interfaces be used. The advantage of using classes as "Service Contracts" involve speed and simplicity. However, manage classes do not support inheritance and it wouldnt be possible to run all the operations of a service contract at the same time.

It is beneficial to use parameters in service contracts as service contracts often pass on values than reference to values. The primitive data types that service contracts use are serializeable by default.

Data Contracts

edit

Data contracts are generally used to specify the data members used in a contract. Data members are marked with a "Data Members" attribute. Members not specified as 'Data Members' are permitted but they shall not be a part of the contract and could not be implemented.

Syntax

The syntax for DataContracts attribute is

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Enum, Inherited=false, AllowMultiple=false)] 
public sealed class DataContractAttribute : Attribute


Example:

[DataContract]
public class CustomerDetails
{
    //Serialized Member//
    [DataMember]
    public string CustomerName;

    //Serialized Member//
    [DataMember]
    private int Age;

    // This is not serialized because the DataMemberAttribute 
    // has not been applied.
    private string CustomerMailID;

}

Operation Contracts

edit

Operation contracts are components of a service contract. Each and every method, a component of a service contract are tagged with the Operation contract attribute. Only methods designated as operations are considered as a part of the service.

Syntax

[AttributeUsageAttribute(AttributeTargets.Method)] 
public sealed class OperationContractAttribute : Attribute


Message Contracts

edit

Apart from these three types of contracts, there are message contracts which enable us to enter a parameter or return value. Message Contracts make it easier to serialize data so that a detailed knowledge of SOAP need not be necessary.

The components to be displayed as SOAP headers will be specified using MessageHeader attribute while SOAP body members will be specified using MessageBodyMember attribute.


Syntax

[MessageContract]
public class ABC
{
  [MessageHeader] A;
  [MessageHeader] B;
  [MessageBodyMember] C;
  [MessageBodyMember] D;
  [MessageBodyMember] E;
}

Contract Patterns

edit

There are three types of contracts specified in WCF Programming model:


  • Request/Reply Message Pattern
  • one-way message pattern
  • duplex message pattern

Request/Reply Message Pattern

edit

A Request/Reply Message Pattern is one in which a request by a client is followed by a reply from the server. Here, parameter values could be sent to the server by the client and at the same time return values could be passed by the server to the client.

However, there are major drawbacks in this pattern. If the functions are not in order, then each and every statement is regarded as a request or a reply. This shall include even statements which dont return values.

One-Way Message Pattern

edit

Here, the client makes a request and the server responds and the client functions regardless of whether any message arrives from the server.

Here, the service need not bother about SOAP faults. Generally, the service does not wait for the application to process.

The one-way message pattern is the same as the request-reply pattern except that we set "IsOneWay" property to "true" in order to specify that the pattern is a one-way message pattern.

Duplex Message Pattern

edit

The working behind the duplex message pattern is same as that of request/reply pattern except that the server and the client send messages independently of one another compared to request/reply pattern where both request and reply are parts of the same process.

A WCF Service Code Example

edit
[ServiceContract]
class HelloService 
{ 
  [OperationContract]
  [PrincipalPermission(SecurityAction.Demand, 
    Role = “Adminstrators")]
  [TransactionFlow(TransactionFlowOption.Mandatory)]
  [OperationBehavior(TransactionScopeRequired = true,
    TransactionAutoComplete = true)]
  String Hello(String Greeting) {return Greeting;}
}

<bindings>
  <wsHttpBinding>
    <binding name="Binding1“  transactionFlow="true">
      <security mode="Message">
        <message clientCredentialType="Windows“/>
      </security>
      <reliableSession enabled="true" />
    </binding>
  </wsHttpBinding>
</bindings>

References

edit
  1. http://msdn2.microsoft.com/en-us/library/ms733127.aspx
  2. http://msdn2.microsoft.com/en-us/library/ms733127.aspx


Windows Cardspace

Microsoft Cardspace (codenamed: Info Card) is a part of Microsoft's new initiative to construct an identity metasystem where different identities shall be stored and authentication provided by a single system.


Digital Identity

edit

People have multiple identities. For an immigration officer at an airport, a person is identified as a citizen of some country while to a traffic policeman who catches him for overspeed, he is a driver from a particular locality. In a similar way, a person on the net might want to purchase grocies from a grocer, book air tickets for a holiday and order a pizza from the nearest pizza shop through the computer. Hence a digital identity is needed to identify him and this may vary depending upon the vendor

This could be realized through a large-scale system of computers or a metasystem. No single system can issue identities or permissions especially when multiple businesses and multiple transactions are involved. This issue is tackled with by the use of a metasystem wherein each organization issues its own card or passport for the user.

By the use of standards as WS-Security, WS-Trust, WS-MetadataExchange, and WS-SecurityPolicy, it will be possible for the identity metasystem to work with multiple identities issue by different organizations.

Identities are usually assigned based on security tokens which consists of a set of claims. Each claim is a component which identifies the user such as username, address, telephone number,etc. which are unique to that particular user. The set of claims required to authenticate an user might vary from site to site and with this set of claims, the digital identity. These security tokens could be created using Security Assertion Markup Language (SAML), a new standard created by the industry group OASIS.

Digital Identities and Windows Cardspace

edit

Windows Cardspace implements the system of digital identity in Microsoft's identity metasystem effort by offering the user a system of cards from which the user might be able to select for authentication to different websites. Each of these cards is provided by an identity provider. These cards are authenticated by relying parties representing that particular business establishment.

Internal Working

edit

As seen earlier, Windows Cardspace uses a system of cards to authenticate an user. When a new card is created, it gets stored as a .CRD file. The .crd file is composed of metadata. It contains the card name, card image details and STS details. The URL of the location where user information is located is actually specified in the STS section. So, the card simply contains the address or location of the file which contains user information and not the information itself.

References

edit
  1. http://msdn2.microsoft.com/en-us/library/aa480189.aspx


Windows Workflow Foundation

Windows Workflow Foundation is a new component introduced by .NET Framework 3.0.

A workflow is a reliably repeatable pattern of activity enabled by a systematic organization of resources, defined roles and mass, energy and information flows, into a work process that can be documented and learned. Workflows are always designed to achieve processing intents of some sort, such as physical transformation, service provision, or information processing.

Activites

edit

A workflow is a set of activities. Each of these activities is a class which performs a particular operation. In Windows Workflow Foundation (WWF), they are coded using a language called XAML which has been introduced specifically for this purpose.

Workflow activities are classes which are created by the author and contains methods programmed by the author which could be called and executed by the workflow. There are different types of activities: Basic activities and composite activities. Basic activities are single activities executed by the workflow while composite activities are made up of activities. Apart from this, users can also create custom activities based on existing activities.

Typically, the WWF is made up of a number of activities or individual programs which are interlinked using XAML code. Hence, we need to include the namespace System.Workflow.ComponentModel.

Types of Workflow

edit

There are two types of workflows provided by WWF.

  • Sequential Workflow
  • State-machine workflow

Components of WWF

edit

WWF is made up of the following components:

  • Base Activity Library
  • Runtime Engine
  • Runtime Services
  • Hosts

Base Activity Library

edit

The base activity library usually contains some well-known or frequently used activities which are executed by the workflow. Besides, users can also add custom-built activities for use into the workflow. These could be activities which have been developed from existing activites or activities that have been coded from scratch. The base activity library is quite similary to the base class library(BCL) of the .NET framework and Java Class Libraries.

Runtime Engine

edit

Another component which forms a part of Windows Workflow Foundation is the Runtime Engine. As the name implies, this consist of the runtime classes and services required for the program to run. These runtime services of the runtime engine perform the same role as providers.

Runtime Services

edit

The runtime engine offers a number of runtime services for the workflow to run by default. But in case you want to add services on your own, you could do so by choosing and adding new services directly in the web.config. This is one of the major advantages of .NET Framework 3.0. Besides, you can also create your own custom services and implement them in your workflow. Hence, runtime services of WWF are fully extensible.

Hosts

edit

A hosting application or a host is the application which hosts workflows. These are applications which actually contain the workflows which are embedded in the application.

WF workflows define interfaces with methods and events to communicate with the outside world. A host application typically sets up an environment before running a workflow, providing objects that implement those interfaces. When an object implementing such interfaces raises an event, the corresponding workflow is retrieved and the data passed on to it.

Visual Designer

edit

The Visual Designer is a component of WWF that provides a flowchart-based model of the workflow along with the different activities. The important feature of the Visual Designer which differentiates it from designers provided with the earlier versions is the presence of a facility to include the designer in an application. true, the visual designer model of a workflow could be introduced in an application by adding a Visual Designer tool. This helps to create a monitoring tool and in the maintenance of the workflow-based application.

References

edit
  1. Wikipedia article on 'Windows Workflow Foundation'


Features of IIS 7.0

IIS 7.0 is an extension of IIS 6.0 and has a lot in common with IIS 6.0. While the underlying concepts remain the same various dramatic new concepts have been introduced in IIS 7.0.

Modular Architecture

edit

IIS 7.0 introduces the system of a "modular architecture". A modular architecture is one in which the extra functionality in the form of different modules can be added to the server and could be enabled or disabled depending on the administrator's wish. This is a marked change from the monolithic architecture implemented in earlier systems.

The modules that shall be shipped with the server include:

  • HTTP Modules
  • Security Modules
  • Content Modules
  • Compression Modules
  • Caching Modules
  • Logging and Diagnostics Modules

More Security

edit

In earlier versions of IIS, the ASP.NET web services were executed by aspnet_wp.exe (IIS 5.0) and w3wp.exe (IIS 6.0). Thus the pages were executed outside the IIS and could easily become targets of attacks by spoofers listening at the port. But in IIS 7.0, the pages are compiled and executed within the IIS and even if the hacker gains access to the system the stream of data which comes out of the port appears highly unintelligible and impossible for a hacker or spoofer to break.

Unfortunately, IIS 7.x, like IIS 6.x, is still running in the HTTP.SYS Windows kernel-driver, which Microsoft documents as dangerous:

"when a kernel-mode driver fails, it can crash an entire system, whereas the failure of a user-mode driver causes only the current process to crash. Windows Server can still run kernel-mode drivers, although this is not recommended for the stability reasons mentioned previously."

https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc784266(v=ws.10)

Ports

edit

IIS 7.0 allows the user to select the port where he wants the program or service to run. This is a welcome break from old versions of IIS where all applications would be run at a standard 8080 port making transactions less secure and slowing down execution.

Modules and Handlers

edit

In IIS 6.0, the modules and handlers are specified in the <system.web> configuration section. However in IIS 7.0, a new tag <system.webserver> is introduced and the modules and handlers are specified here. This is one of the most important migration issues that must be looked into while migrating from IIS 6.0 to IIS 7.0.

This is done by placing the tags <httpModules> and <httpHandlers> in <system.webservices> tag.

Microsoft Management Console

edit

The Microsoft Management Console (MMC) is a component of modern Microsoft Windows operating systems that provides system administrators and advanced users with a flexible interface through which they may configure and monitor the system

References

edit
  1. http://forums.iis.net/default.aspx?GroupID=41


Windows PowerShell

Windows PowerShell (codenamed:Monad) is a command-line driven interface (CLI). It is not supplied with older versions of Windows Vista, but it could be used, regardless, in Windows XP, Windows 2003 Server and Windows Vista.

Windows PowerShell is the foundation of the administrative tools for Exchange Server 2007, System Center Virtual Machine Manager 2007 and System Center Operations Manager 2007 where everything is done via command line interfaces and the administrative GUI is layered on top of those commands.


Working

edit

Windows PowerShell works according to a system called "Monadology" according to which the whole earth is composed of metaphysical structures not connected to each other called monads. The "monads" of Windows PowerShell are objects called "cmdlets". Following the failure of Windows Script Host, Microsoft started working on Windows PowerShell as early as 2003. Unlike Windows Script Host, Windows Powershell interacts directly with the shell and is highly secure.

Instead of services which use pipes or streams data in order to communicate with each, Windows Powershell uses object-to-object communication between two cmdlets in different remote machines. A listing of processes will consist not of text describing them, but objects representing them, so that methods can be called on those objects without explicit reference to any outside structure or library.

Windows PowerShell operates within a hosting application (the default is powershell.exe) that exposes a command line to the user and uses a host interface to communicate with the commands invoked by the command line. The hosting application can be a console application, a Windows application, or a Web application. In most cases, the hosting application uses its Main function to interact with the Windows PowerShell runtime through the internal host interface; however, a hosting application can optionally support its own custom host by implementing the PSHost class along with one or more related user interface classes. Together, these classes allow direct communication between the application and Windows PowerShell commands.

Creating a Runspace

edit

The first thing that the hosting application must do in communicating with the Windows PowerShell runtime is to create a runspace, which is the abstraction of the Windows PowerShell runtime used to simplify a user session. To do this, the hosting application calls the CreateRunspace method of the RunspaceFactory class. The runspace itself is represented by a Runspace object. In addition, Windows PowerShell provides the RunspaceConfiguration class to define the configuration of the runspace. Configuration information includes data about commands and Windows PowerShell providers that the hosting application supports, and startup scripts for the runspace. User scripts are not reflected in the runspace configuration. When a runspace is created, a corresponding session is automatically opened, with its state represented by a SessionState object. Session state data includes information about Windows PowerShell paths, Windows PowerShell drives, Windows PowerShell providers, plus cmdlets and other commands that are active during the session.

Opening the Runspace

edit

When the hosting application has created a runspace, it must open the runspace for the type of session that is required. For a session using synchronous I/O, the application can call the Open method. If the application uses asynchronous I/O and must perform other operations while the runspace fulfills a read/write request, it can call the OpenAsync method. If calling OpenAsync, a hosting application defining a custom host will need to support an appropriate callback method to receive I/O notifications.

When the runspace is opened, the hosting application can manipulate the session by creating and invoking pipelines in the runspace, as described in Processing Commands.

The runspace allows the hosting application to manipulate the session with calls to the GetVariable and SetVariable methods of the SessionStateProxy object for the session.

Creating a Pipeline

edit

When the hosting application has accumulated a command sequence from the user, it must form the commands into one or more pipelines, each represented by a Pipeline object for the active runspace.

A command sequence can be made up of multiple nested pipelines, separated by semicolon (;) statement separators. Here's an example of such a sequence.

PS>pqr | bar; a | b

The Windows PowerShell runtime represents this sequence as one pipeline with two nested pipelines, pqr | bar and a | b.

To create its own pipeline, the hosting application calls either the CreatePipeline method or the CreateNestedPipeline method. The application calls CreatePipeline to form an empty pipeline or if it must create a pipeline and populate it with commands. If the application must create a pipeline for a runspace with its current pipeline executing, it must call CreateNestedPipeline.

Starting the Pipeline

edit

Now that its pipeline is set up, the hosting application must start its operation. If the application is using synchronous I/O, it calls the Invoke method, using the variant for either an empty pipeline or a populated one. For asynchronous I/O, the application can call InvokeAsync instead.

Features

edit

The first version contains the following features:

  • A C#-like scripting language with support for hash tables, switch statements which can test on regular expressions, array slicing and anonymous methods (script blocks) which can be stored as data and then later executed. It also provides looping (for/foreach/while), conditional statements (if/switch), variable scoping (global/script/local) and the ability to define functions.
  • Cmdlets inherit certain options, allowing the user to choose things such as the level of interaction and how to deal with errors. Cmdlets which produce side effects support the options -WhatIf and -Confirm. -WhatIf informs the user what would have happened, but no action takes place. -Confirm informs the user what is about to happen and allows the user to control whether it takes place or not.
  • One option for dealing with errors is to invoke a "suspend" feature which allows the user to enter a new command shell, investigate a problem, and resume the original command. The user can define the prompts to be shown in such circumstances.
  • An extensible provider model allows access to and manipulation of the file system and other hierarchical data stores. Some examples: PowerShell comes with a registry provider which allows access to the registry via the "HKLM" and "HKCU" hives; with this, the registry can be browsed by executing commands like "dir HKLM:\SOFTWARE\Microsoft" at the shell prompt. PowerShell comes with providers for the certificate store, the environment, and shell functions and aliases. Like cmdlets, the provider model is extensible, allowing third parties to create their own provider model and plug it into PowerShell.
  • A concept called "execution policies" which allows coarse security constraints to be imposed upon PowerShell script execution. Execution policies define the restrictions under which PowerShell loads configuration files and runs scripts. The four execution policies are Restricted, AllSigned, RemoteSigned, and Unrestricted.
  • Support for the use of script signing to verify the identity of a script publisher and to validate the integrity of a published script using digital signatures.
  • The command-line options are generally whole words, but they can be specified as the minimum number of letters necessary to disambiguate. For example, the option -show-detailed-information could be entered as -s if no other option begins with 's'.
  • Comprehensive, user-extensible tab completion features. The cmd.exe shell in current versions of Windows can only complete file or directory names, in contrast to the advanced completion in shells such as Bash and zsh.
  • The ability to assign the output of a command to a variable, which will then be an object or array of objects inspectable in any way desired.

References

edit
  1. http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx
  2. http://msdn2.microsoft.com/en-us/library/ms714658.aspx