Total Pageviews

Sunday, August 12, 2012

Windows Power Shell Jump Start

Windows PowerShell® is a task-based command-line shell and scripting language designed especially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals and power users control and automate the administration of the Windows operating system and applications that run on Windows.

Windows PowerShell is built on top of the .NET Framework common language runtime (CLR) and the .NET Framework, and accepts and returns .NET Framework objects. This fundamental change in the environment brings entirely new tools and methods to the management and configuration of Windows.

Windows PowerShell is very different.
  • Windows PowerShell does not process text. Instead, it processes objects based on the .NET Framework platform.

  • Windows PowerShell comes with a large set of built-in commands with a consistent interface.

  • All shell commands use the same command parser, instead of different parsers for each tool. This makes it much easier to learn how to use each command.

Best of all, you do not have to give up the tools that you have become accustomed to using. You can still use the traditional Windows tools, such as Net, SC, and Reg.exe in Windows PowerShell.

A cmdlet (pronounced "command-let") is a single-feature command that manipulates objects in Windows PowerShell. You can recognize cmdlets by their name format -- a verb and noun separated by a dash (-), such as Get-Help, Get-Process, and Start-Service.

Each cmdlet has a help file that you can access by typing:
get-help <cmdlet-name> -detailed

Windows PowerShell provides a new architecture that is based on objects, rather than text. The cmdlet that receives an object can act directly on its properties and methods without any conversion or manipulation. Users can refer to properties and methods of the object by name, rather than calculating the position of the data in the output.

Windows PowerShell provides a complete interactive environment. When you type a command or expression at the Windows PowerShell command prompt, the command or expression is processed immediately and the output is returned to the prompt.

This is true for all command types, including cmdlets, aliases, functions, CIM commands, workflows, and executable files.

You can also send the output of a command to a file or printer, or you can use the pipeline operator (|) to send the output to another command.

What is a script?


A script is text file that contains one or more Windows PowerShell commands or expressions. When you run the script, the commands and expressions in the script file run, just as if you typed them at the command line.
Typically, you write a script to save command sequence that you use frequently or to share a command sequence with others.

http://www.sqlmag.com/article/windows-powershell/powershell-scripting

http://technet.microsoft.com/en-us/library/ff730939.aspx


Thursday, August 9, 2012

This Keyword

This Keyword is used To inform the compiler that you wish to
set the current object’s
name data field to the incoming name parameter, simply use this to resolve
the ambiguity:
public void SetDriverName(string name)
{ this.name = name; }

Chaining Constructor Calls Using this
Another use of the
this keyword is to design a class using a technique termed constructor chaining.
This design pattern is helpful when you have a class that defines multiple constructors. Given the
fact that constructors often validate the incoming arguments to enforce various business rules, it
can be quite common to find redundant validation logic within a class’s constructor set.

A cleaner approach is to designate the constructor that takes the
greatest number of arguments
as the “master constructor” and have its implementation perform the required validation logic. The
remaining constructors can make use of the
this keyword to forward the incoming arguments to
the master constructor and provide any additional parameters as necessary. In this way, we only
need to worry about maintaining a single constructor for the entire class, while the remaining constructors
are basically empty.
Here is the final iteration of the
Motorcycle class (with one additional constructor for the sake
of illustration). When chaining constructors, note how the
this keyword is “dangling” off the constructor’s
declaration (via a colon operator) outside the scope of the constructor itself:
class Motorcycle
{
public int driverIntensity;
public string driverName;
// Constructor chaining.
public Motorcycle() {}
public Motorcycle(int intensity)
: this(intensity, "") {}
public Motorcycle(string name)
: this(0, name) {}
// This is the 'master' constructor that does all the real work.
public Motorcycle(int intensity, string name)
{
if (intensity > 10)
{
intensity = 10;
}
driverIntensity = intensity;
driverName = name;
}
...
}

Observing Constructor Flow
On a final note, do know that once a constructor passes arguments to the designated master constructor
(and that constructor has processed the data), the constructor invoked originally by the
caller will finish executing any remaining code statements.

Constructors

C# supports the use of
class constructors
, which allow the state of an object to be
established at the time of creation. A constructor is a special method of a class that is called indirectly
when creating an object using the
new keyword. However, unlike a “normal” method,
constructors never have a return value (not even
void) and are always named identically to theclass they are constructing.

Every C# class is provided with a freebee
default constructor that you may redefine if need be. By
definition, a default constructor never takes arguments. Beyond allocating the new object into
memory, the default constructor ensures that all field data is set to an appropriate default value

Defining Custom Constructors
Typically, classes define additional constructors beyond the default. In doing so, you provide the
object user with a simple and consistent way to initialize the state of an object directly at the time
of creation

However, as soon as you define a custom constructor, the default constructor is
silently removed
from the class and is no longer available! Think of it this way: if you do not define a custom constructor,
the C# compiler grants you a default in order to allow the object user to allocate an
instance of your type with field data set to the correct default values. However, when you define
a unique constructor, the compiler assumes you have taken matters into your own hands.

Strings vs string Builder

Defining Verbatim Strings

When you prefix a string literal with the
@ symbol, you have created what is termed a verbatim
string
. Using verbatim strings, you disable the processing of a literal’s escape characters and print
out a
string as is. This can be most useful when working with strings representing directory and
network paths. Therefore, rather than making use of
\\ escape characters, you can simply write the
following:
// The following string is printed verbatim
// thus, all escape characters are displayed.
Console.WriteLine(@"C:\MyApp\bin\Debug");

Strings: Strings are immutable , that is when you are manipulating the strings every time a new object is created, and the old one is garbage collected.
the
string type can be inefficient and result in bloated code if misused, especially when performing string concatenation. If you need to represent basic character data such as a US Social Security number (SSN), first or last names, or simple string literals used within your application, the string data type is the perfect choice.However, if you are building an application that makes heavy use of textual data (such as a word processing program), it would be a very bad idea to represent the word processing data using string types, as you will most certainly (and often indirectly) end up making unnecessary copies of string data. 

Strings use System.String Namespace.

String Builder;
What is unique about the
StringBuilder is that when you call members of this type, you are
directly modifying the object’s internal character data (and is thus more efficient), not obtaining a
copy of the data in a modified format. When you create an instance of the
StringBuilder, you cansupply the object’s initial startup values via one of many
constructors.
By default, a
StringBuilder is only able to hold a string of 16 characters or less;
however, this initial value can be changed via an additional constructor argument:
// Make a StringBuilder with an initial size of 256.
StringBuilder sb = new StringBuilder("**** Fantastic Games ****", 256);
If you append more characters than the specified limit, the
StringBuilder object will copy itsdata into a new instance and grow the buffer by the specified limit.

Declaring Variables

Local Variables when declared must be initialized before they are used, otherwise a compile time error will be raised.

“New-ing” Intrinsic Data Types
All intrinsic data types support what is known as a
default constructor. In a nutshell,
this feature allows you to create a variable using the
new keyword, which automatically sets the variable to its default value:
Although it is more cumbersome to use the
new keyword when creating a basic data type variable,
the following is syntactically well-formed C# code and more advisable.
static void NewingDataTypes()
{
Console.WriteLine("=> Using new to create intrinsic data types:");
bool b = new bool(); // Set to false.
int i = new int(); // Set to 0.
double d = new double(); // Set to 0.
DateTime dt = new DateTime(); // Set to 1/1/0001 12:00:00 AM
Console.WriteLine("{0}, {1}, {2}, {3}", b, i, d, dt);
Console.WriteLine();
}

Tuesday, August 7, 2012

the Main() Method

the class that defines the
Main() method is termed the application object
.
While it is possible for a single executable application to have more than one application object
(which can be useful when performing unit tests), you must informthe compiler which
Main()
method should be used as the entry point via the
/main option of the command-line compiler.
Note that the signature of
Main() is adorned with the static keyword, implies that static members are scoped to the class level (rather than the object level) and can thus be invoked without the need to first create a new class instance.
In addition to the
static keyword, this Main() method has a single parameter, which happens
to be an array of strings (
string[] args). Although you are not currently bothering to process this
array, this parameter may contain any number of incoming command-line arguments (you’ll see
how to access them momentarily). Finally, this
Main() method has been set up with a void return
value, meaning we do not explicitly define a return value using the
return keyword before exiting
the method scope.
The logic of
Program is within Main() itself. Here, you make use of the Console class, which is
defined within the
System namespace. Among its set of members is the static WriteLine() which, asyou might assume, pumps a text string and carriage return to the standard output.

While a vast majority of your
Main() methods will return void as the return value, the ability to
return an
int from Main() keeps C# consistent with other C-based languages. By convention,
returning the value
0 indicates the program has terminated successfully, while another value (such
as
-1) represents an error condition (do be aware that the value 0 is automatically returned, even ifyou construct a
Main() method prototyped to return void).
Processing Command-Line Arguments
Now that you better understand the return value of the
Main() method, let’s examine the incoming
array of
string data. Assume that you now wish to update your application to process any possiblecommand-line parameters.

One way to do so is using a C# for loop
As an alternative to the standard
for loop, you may iterate over an incoming string array usingthe C#
foreach keyword.
Finally, you are also able to access command-line arguments using the static
GetCommandLineArgs()
method of the System.Environment type. The return value of this method is
an array of
strings. The first index identifies the name of the application itself, while the remaining
elements in the array contain the individual command-line arguments (note that when using this
approach, it is no longer necessary to define
Main() as taking a string array as the input parameter,
although there is no harm in doing so):
static int Main(string[] args)
{
...
// Get arguments using System.Environment.
string[] theArgs = Environment.GetCommandLineArgs();
foreach(string arg in theArgs)
Console.WriteLine("Arg: {0}", arg);
Console.ReadLine();
return -1;
}



Some Additional Members of
the System.Environment Class
Environment.GetLogicalDrives()
Environment.OSVersion

ExitCode
Gets or sets the exit code anywhere within the application
MachineName
Gets the name of the current machine
NewLine
Gets the newline symbol for the current environment
StackTrace
Gets the current stack trace information for the application
SystemDirectory
Returns the full path to the system directoryUserName Returns the name of the user that started this application

what are the features of C#

core C# features that are found in all versions of the language:
• No pointers required! C# programs typically have no need for direct pointer manipulation
(although you are free to drop down to that level if absolutely necessary).
• Automatic memory management through garbage collection. Given this, C# does not support
a
delete keyword.
• Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates.
• The C++-like ability to overload operators for a custom type, without the complexity (e.g.,
making sure to “return
*this to allow chaining” is not your problem).
• Support for attribute-based programming. This brand of development allows you to annotate
types and their members to further qualify their behavior.
• The ability to build generic types and generic members. Using generics, you are able to build
very efficient and type-safe code that defines numerous “placeholders” specified at the time
you interact with the generic item.
• Support for anonymous methods, which allow you to supply an inline function anywhere a
delegate type is required.
• Numerous simplifications to the delegate/event model, including covariance, contravariance,
and method group conversion.
• The ability to define a single type across multiple code files (or if necessary, as an in-memory
representation) using the
partial keyword.
• Support for strongly typed queries (a la LINQ, or Language Integrated Query) used to interact
with various forms of data
• Support for anonymous types, which allow you to model the “shape” of a type rather than its
behavior
• The ability to extend the functionality of an existing type using extension methods
• Inclusion of a lambda operator (
=>), which even further simplifies working with .NET delegate
types
• A new object initialization syntax, which allows you to set property values at the time of
object creation