SlideShare a Scribd company logo
Lectures 15 - 17:
C#, cmdLet
programming &
scripting
Network design & Administration
Why does a Systems Administrator
need to know about programming?
• Tools not available to perform task
 • Have to write new tools
• Use scripting to provide more power than




                                              Network Design & Administration
  executing single command line tools
• Automate tasks
• Need to alter the OS (if Unix based)
• There are lots of reasons why a knowledge
  of programming is essential!                        2
Powershell
• Powershell is “the next generation command shell and
  scripting language”[1]
• Provides access to lots of powershell programs (cmdlets)
• Cmdlets can be joined together (output -> input)




                                                             Network Design & Administration
• Powershell provides a set of scripting commands to
  facilitate in linking cmdlets together (more later)
• Can program your own cmdlets to do specific tasks



                                                                     3
What do you need to know to
be able to program a cmdlet?
• C# !
• C# is a C++/Java like language
• C# requires the .Net framework to be installed
• Cmdlets are written in C# but you need to:
   • Extend the PSCmdLet class




                                                                 Network Design & Administration
   • Provide parameter attributes
   • Implement the following methods:
       • BeginProcessing
       • ProcessRecord
       • EndProcessing
   • Provide your code!
• Before we look at cmdlet programming in more detail, a quick           4
  introduction to C# is in order!
                                                     [4]
C# Data types
• C# has the same primitive data types that you find in C++ and
  Java
  •   int         e.g. int value = 5;
  •   bool        e.g. bool receivedInput = false;
  •   float       e.g. float value = 8.5;




                                                                  Network Design & Administration
  •   arrays      e.g. string []params; BUT!

• More complex data types:
  •   String
  •   List
  •   ArrayList
  •   Stack
  •   Queue                                                               5
  •   …
C# Classes
• In C#, everything is an Object
• A class provides the blueprint as to what data and operations
  it can offer
• However, you have to use the class blueprint to create an




                                                                        Network Design & Administration
  object instance before you can access it
• Follows a similar syntax to a Java Class.

 public class MyFirstClass{
     public MyFirstClass() {
         // Constructor …
     }                               Use dot notation tonew keyword
                                                Use the
                                     access the objects
                                                to instantiate object
 }
                                     methods                                    6
                       MyFirstClass m = new MyFirstClass();
                       m.print();
Anatomy of a C# Program
using System;
                                                     1.   Using (import other
namespace ConsoleApplication1
                                                          classes)
{                                                    2. Namespace
  class MyFirstProgram                               3. Class definition
  {
    private String _message = "Hello ";
                                                     4. Private data
                                                     5. Class constructor




                                                                                Network Design & Administration
    public MyFirstProgram(String userName)           6. One Main method
    {
                                                          per program (has to
      Console.WriteLine(_message + userName);
    }
                                                          be static)
                                                     7. Parameter passing
    public static void Main(String[] args)           8. Instantiating a new
    {
                                                          object
      MyFirstProgram myProg = new MyFirstProgram("Clark");
    }                                                9. Writing output to
  }                                                       the console
}                                                                                       7
C# Strings
• Strings are objects of the System.String Class
• Can assign a sequence of characters to them…
    String machineName = "CIB108-34";
  • i.e. use the assignment operator =




                                                                     Network Design & Administration
• You can join strings together…
    String fullName = machineName + ".ads.ntu.ac.uk";
  • Using the + operator
• Because String is a class there are several handy methods and
  properties it provides…
  • Length – returns the number of characters in the string
  • Substring( int startPosition, int length) – returns characters
    between start and start+length characters                                8
Inheritance
    • C# allows you to inherit functionality from another class.
public class Employee
{
    private String name = string.Empty;
     public Employee(String n)




                                                                             Network Design & Administration
     {
    public class Manager : Employee
         name = n;                             Inherits the print() method
    {}
       private List<Employee> employeeList = new List<Employee>();
    public void print()
    { public Manager(String name) : base(name)
        Console.WriteLine("Employee name: " + name );
       {
    }
        }
}
        public void manages(Employee employee)
        {
            employeeList.Add(employee);                                              9
        }
    }
The Object Class
• When you create a new class (for example):

                using System;

                public class MyFirstClass




                                                                     Network Design & Administration
                {
                    public MyFirstClass()
                    {
                        // …
                    }
                }

• You can define a class and not provide any explicit inheritance.
• However, all classes derive from a base class even if it is not    10
  explicitly stated.
• This is the object class.
The object class
• Because all classes derive from object within C# we can use the
  object class as a way of providing a generic interface to methods
              public void add(object obj) { }

• This is done by boxing and unboxing which also allows value types
  (primitive data types) to act like reference types (objects)




                                                                      Network Design & Administration
• For example, boxing value types:
    int myValue = 1000;
    object obj = myValue;
    int newValue = (int)obj;
                       obj
      myValue
                       int                       newValue
       1000
                         1000                     1000
                                                                      11
• However, unboxing must be explicit!
Namespaces
• C# provides you with hundreds of classes that you can use within
  your programs.
• Each class you create/use will have a name (e.g.):
                     public class ListCommand

• What happens if there is another class called ListCommand?




                                                                       Network Design & Administration
• You can use a Namespace to limit the scope of any classes that you
  define:        namespace myLibrary
                 {
                      public class ListCommand
                      {
                          // ...
                      }
                 }

• Now ListCommand is visible within the myLibrary namespace            12
• You can now access your class as:
                 myLibrary.ListCommand ...
Interfaces
• An interface allows you to define a specific interface to a class.
• Any class that implements that interface will have to provide a
  set of pre-defined method signatures.
         namespace myLibrary




                                                                       Network Design & Administration
         {
             interface MyListInterface
             {
                 void add(object onj);
                 object get(int index);
                 int size();
                 void toString();
             }
         }                                                             13
Interfaces
• To use an interface you have to specify a class which inherits
  the interface
    namespace myLibrary
    {
        interface MyListInterface




                                                                   Network Design & Administration
        {
            void add(object onj);
            object get(int index);
            int size();
            void toString();
        }

        public class MyList : MyListInterface
        {
            public MyList() { }                                    14
        }
    }
this and is keywords
• this
   • Refers to current instance of an object
   • Example:
         private string name;
         public void setName(string name) {




                                                                      Network Design & Administration
           this.name = name;
         }

• is
   • provides you with a way to determine if the object supports an
     interface
   • If it does, then you can access methods within it
   • Syntax:
                <expression> is <type>
   • Example:                                                         15
          Employee CKent = new Employee("Clark Kent");
          if( CKent is Employee ) CKent.print();
C# Control Structures
• C# provides the same control structures as C/C++ and Java
• if statement
       if( x == 10 ) {
          // …
       } else {
          // ..




                                                                       Network Design & Administration
       }

• Remember - when comparing objects
       if( obj1 == obj2 ) {}

• Isn’t comparing that the two objects contain the same data but is
  instead comparing the pointers of each object.
• But Strings are different!
       String name1 = "clark";
       String name2 = "lois";
                                                                       16
       if( name1 == name2 ) Console.WriteLine("they are the same!");
       else Console.WriteLine("they are not the same!");
C# Control Structures
• C# provides the same control structures as C/C++ and Java

• Switch statement
  switch( value ) {




                                                              Network Design & Administration
     case 1:
         Console.WriteLine("Option 1!");
         break;
     case 2:
         Console.WriteLine("Option 2!");
         break;
     default:
         Console.WriteLine("Option 2!");
         break;                                               17
  }
Loops
• For loops are the same as in C++/Java
  for (int iCounter = 0; iCounter < 10; iCounter++)
  {
     Console.WriteLine("counter = " + iCounter);
  }




                                                      Network Design & Administration
• Foreach:
  List<string> myList = new List<string>();
  for (int counter = 0; counter < 10; counter++) {
      myList.Add("item " + counter);
  }
  foreach (string value in myList) {
      Console.WriteLine(value);
                                                      18
  }
Reading and Writing to the
  console
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)




                                                              Network Design & Administration
    {
      Console.WriteLine("Enter first number:");
      int value1 = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("Enter second number:");
      int value2 = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine("multiplying {0} by {1} gives {2}",
                        value1, value2, (value1 * value2));
    }
                                                              19
  }
}
Exception handling
    • C# provides you with throw and try-catch statements so that
      you can handle any unwanted exceptions
    • Program {
class Classes that you use within your C# code will usually throw an
                                                                    rd
    public List<string> myList =(especially if you are relying on 3
      exception if an error occurs new List<string>();
    static api’s / Main(string[] args) {
      part void libraries)




                                                                         Network Design & Administration
        Program m = new Program();
        for (int counter = 0; counter < 10; counter++) {
            m.myList.Add("item " + counter);
        }
        Console.WriteLine(m.getIndex(50));
    }
    public string getIndex(int index){
        if (index > myList.Count) throw new IndexOutOfRangeException();
        else return myList[index];                                    20
    }
}
Exception handling
class Program {
    public List<string> myList = new List<string>();
    static void Main(string[] args) {
        Program m = new Program();
        for (int counter = 0; counter < 10; counter++) {
            m.myList.Add("item " + counter);




                                                                          Network Design & Administration
        }
        Try {
            Console.WriteLine(m.getIndex(50));
        } catch (IndexOutOfRangeException error) {
            Console.WriteLine("Error occurred: " + error.Message);
        }
    }
    public string getIndex(int index) {
        if (index > myList.Count) throw new IndexOutOfRangeException();
        else return myList[index];                                        21
    }
}
Properties
     • In C# you can use properties to access private data
     • Use the get and set methods to allow read or write access
                                                            Private data stored
                                                            within the class




                                                                                     Network Design & Administration
The get method
returns the value of      private string _name;
the private data                                            The property!
element. Used when
access the property by    public string Name
name or on RHS of =
                          {
                                                            Special keyword in C#.
                           get { return _name; }            Gives the value from
                           set { _name = value; }           the RHS of an =
The set method allows                                       operation.
you to assign a value     }
to the private data                                                                  22
element. This is called                    Examples:
automatically when =                       Name = “Clark”;
is used                                    String userName = Name;
Exercise!
• Spend 5 minutes to work out what
  errors are in the code in the hand-out.
• The person who identifies the correct




                                            Network Design & Administration
  number of errors gets a prize!



                                            23
Now back to cmdlets … Cmdlet naming[2]
• Cmdlets are named using a verb-noun pair
• Verbs are used to describe what action the cmdlet will perform
• Nouns are used to describe what entity the cmdlet will perform the
  action on
• Examples (encountered in the labs):




                                                                       Network Design & Administration
   • New-ADComputer
   • Get-Help
   • Set-ADUser
• There are lots of pre-defined verbs (stored in classes):
   • VerbsCommon                  VerbsLifeCycle
   • VerbsCommunications          VerbsSecurity
   • VerbsData                    VerbsOther
                                                                       24
   • VerbsDiagnostic
Sending input to cmdlets
• Cmdlets can accept parameters
            new-gpo –name “Publishers Policy”

• Cmdlets can also be chained together so that the output of
  one can be the input to another.




                                                               Network Design & Administration
• For example:
  new-gpo –name “Publishers Policy” | new-gplink –target
  “ou=publishers, dc=testnetwork, dc=com”

• Here, new-gpo is creating a new GPO object and passing it
  (using the pipe symbol |) to the new-gplink cmdlet.

                                                               25
Anatomy of a cmdlet
using    System;
using    System.Collections.Generic;
using    System.Text;
using    System.Management.Automation;
namespace HelloWorldExample {
    [Cmdlet(VerbsCommunications.Send, "Hello World Example!")]




                                                                 Network Design & Administration
    public class HellowWorld : PSCmdlet {
        [Parameter(Mandatory = true)]
        public string yourName {
            get { return userName; }
            set { userName = value; }
        }
        private string userName;
           protected override void ProcessRecord() {
               WriteObject("Hello" + userName + "!");            26
           }
     }
}
Processing within cmdlets
  • The Cmdlet and PSCmdlet classes provide the following methods:
             • BeginProcessing
             • ProcessRecord
             • EndProcessing
  • These methods need to be implemented by the developer




                                                                                  Network Design & Administration
  • Sending objects through a pipeline between cmdlets can be
    demonstrated by the following :-

Input Pipeline                                                  Output Pipeline


Object 1
                                                    cmdlet
Object 2
                      Begin      Process           End
Object 3            Processing   Record         Processing                        27
                                                New Output
                                                 Object 2
                                                  Object3
Snap-ins
• Once you have finished writing your C# cmdlet
  you have to create another file which contains
  snap-in information.
• Snap-ins are used to register cmdlets with




                                                      Network Design & Administration
  powershell and to setup any registry entries
• If you do not register a cmdlet within powershell
  you will not be able to run it
• A snap-in for the cmdlet would be added to your
  project and get linked in when the project is
                                                      28
  compiled
Anatomy of a Snap-in
using   System;
using   System.Collections.Generic;
using   System.Text;
using   System.Management.Automation;
using   System.ComponentModel;
namespace ListCommand {
  [RunInstaller(true)]




                                                        Network Design & Administration
  public class ListCommandSnapIn : PSSnapIn {
    public override string Name {
      get { return "ListCommand"; }
      }
    public override string Vendor {
      get { return "Jon Robinson"; }
      }
    public override string Description {
      get { return "New directory listing command"; }
                                                        29
      }
  }
}
Compiling cmdlets and linking
into Powershell
1. Cmdlets can be created and compiled within visual
   studio
  • Need a special template project to create cmdlets
    which can be downloaded from the web[3]
2. Can also be compiled using the .Net framework C#




                                                           Network Design & Administration
   compiler (csc.exe)
  • Found under windowssystem32Microsoft.Net<.net
    version>
3. Use the installutil command to register the cmdlet in
   powershell
4. Use add-pssnapin <new cmdlet> to access cmdlet from
   powershell prompt                                       30
Powershell Scripting
• Powershell provides a rich scripting language
• Used to provide more complex functionality
  linking cmdlet’s together
• Types of language features available:




                                                  Network Design & Administration
   • variables
   • if/else statements
   • switch statements
   • for loops
   • command line parameter passing               31

   • Etc…
Powershell scripting example [1]
[int]$intPing=10
[string]$intNetwork="127.0.0."
       Variables have the following syntax:
         [<data type>] $<variable name> = <data value>
for($i=1; $i -le $intPing; $i++) {
       Available data types:
  $strQuery = "select * from win32_pingstatus




                                                                         Network Design & Administration
       [array]            [bool]
where address = '" [char]
       [byte]               + $intNetwork + $i + "'"
  $wmi [decimal]
        = get-wmiobject -query $strQuery
                          [double]
       [hashtable]        [int]
  "Pinging $intNetwork$i ..."
       [long]             [string]
  if( $wmi.statuscode -eq 0 )
       [single]           [xml]
    {"success"}                          -eq (equal to)
  else If statement syntax:              -lt (less than)
    {"error: " + $wmi.statuscode + " occurred"}
                                         -gt (greater than)
       if( $<variable name> <evaluation expression> <value> )equal to)
                                         -ge (greater than or            32
}         {"success"}                     -le (less than or equal to)
          else                            -ne (not equal)
           {"fail"}
Powershell switch example
   Switch statement syntax:
   switch <expression evaluation type> ($<variable name>) {
   … expressions …
   }




                                                              Network Design & Administration
      [int] $simpleSwitchExample = 2

      switch($simpleSwitchExample) {
        1 { "Option 1" }
        2 { "Option 2" }
        3 { "Option 3" }
        default { "No idea..." }                              33
      }
Powershell switch example
[string] $regularExpressionSwitchExample = "1234"
[int] $size = 0

switch -regex ($regularExpressionSwitchExample) {
  "d{4}" { $size = 4; break; }
  "d{3}" { $size = (regular expression)
               -regex 3; break; }
               -wildcard (wildcard!)




                                                                  Network Design & Administration
  "d{2}" { $size = 2; break; }
  "d{1}" { $size = 1; break; }
  default {
     "No idea..."
     $size = -1
     }
}

if( $size -gt 0 ) { "The string had " + $size + " characters" }
else { "Wasn't able to work out how many characters!" }           34
Getting input from the user
• Scripts can interact with the user to provide more
  functionality.
• Scripts can display information by just saying “message…”.
  • However, this is not formatted.
• Can use the Write-Host cmdlet to display output.




                                                                              Network Design & Administration
  • Can format the message (colours, spaces, etc)
  • For example:
     Write-host “hello world” –foregroundcolor black –backgroundcolor white
• Scripts can get input from the user by using the Read-Host
  cmdlet.
  • For example:
     $ipAddress = Read-Host “Enter the ip address:”
  • Can use the –AsSecureString option to mask what has been                  35
    entered.
     $password = read-host –assecurestring “Enter your password:”
Powershell functions
function display {
      param ([string]$message="")
      Write-Host "Your message is $message"
}




                                                           Network Design & Administration
display "hello world"
                                 Un-typed – could be any
                                   type of information
function display( $message ) {
      Write-Host "Your message is $message"
}

display "hello world"                                      36
Powershell functions
function display {
  param ([string]$message="")
  param ([int]$repeat=1)
  $returnMessage = “”
  for($count=1; $count –le $repeat; $count++) {




                                                   Network Design & Administration
    Write-Host "Your message is $message“
      $returnMessage = $returnMessage +
                      “Your message is $message”
    }
  return $returnMessage
}
                                                   37
display("hello world“, 5)
Next Time & References
• Updating Systems

References
[1] “Windows PowerShell Scripting Guide”, Wilson, E., Microsoft Press
[2] http://msdn.microsoft.com/en-us/library/windows/desktop/ms714428%28v=vs.85%29.aspx




                                                                                            Network Design & Administration
[3] http://channel9.msdn.com/forums/sandbox/249904-Windows-PowerShell-Visual-Studio-2005-
Templates-C-and-VBNET
[4] http://msdn.microsoft.com/en-us/library/zw4w595w.aspx




                                                                                            38
Ad

Recommended

Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Introduction to objective c
Introduction to objective c
Sunny Shaikh
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
Objective c
Objective c
ricky_chatur2005
 
Inheritance
Inheritance
piyush Kumar Sharma
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
Java oops PPT
Java oops PPT
kishu0005
 
Introduction to class in java
Introduction to class in java
kamal kotecha
 
Core java complete ppt(note)
Core java complete ppt(note)
arvind pandey
 
Class introduction in java
Class introduction in java
yugandhar vadlamudi
 
04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
Oops concept in c#
Oops concept in c#
ANURAG SINGH
 
Parte II Objective C
Parte II Objective C
Paolo Quadrani
 
Java ppt Gandhi Ravi ([email protected])
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Introduction to java and oop
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
Java oop
Java oop
bchinnaiyan
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
Subhransu Behera
 
Java Basics
Java Basics
Rajkattamuri
 
Chapter 04 inheritance
Chapter 04 inheritance
Nurhanna Aziz
 
camel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
java training faridabad
java training faridabad
Woxa Technologies
 
Java Basics
Java Basics
F K
 
Introduction to Objective - C
Introduction to Objective - C
Asim Rais Siddiqui
 
Java Day-3
Java Day-3
People Strategists
 
Java basic tutorial
Java basic tutorial
Bui Kiet
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V
Hari Christian
 
Objective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 

More Related Content

What's hot (20)

Core java complete ppt(note)
Core java complete ppt(note)
arvind pandey
 
Class introduction in java
Class introduction in java
yugandhar vadlamudi
 
04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
Oops concept in c#
Oops concept in c#
ANURAG SINGH
 
Parte II Objective C
Parte II Objective C
Paolo Quadrani
 
Java ppt Gandhi Ravi ([email protected])
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Introduction to java and oop
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
Java oop
Java oop
bchinnaiyan
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
Subhransu Behera
 
Java Basics
Java Basics
Rajkattamuri
 
Chapter 04 inheritance
Chapter 04 inheritance
Nurhanna Aziz
 
camel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
java training faridabad
java training faridabad
Woxa Technologies
 
Java Basics
Java Basics
F K
 
Introduction to Objective - C
Introduction to Objective - C
Asim Rais Siddiqui
 
Java Day-3
Java Day-3
People Strategists
 
Java basic tutorial
Java basic tutorial
Bui Kiet
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V
Hari Christian
 

Similar to Lecture 13, 14 & 15 c# cmd let programming and scripting (20)

Objective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
Oops concept on c#
Oops concept on c#
baabtra.com - No. 1 supplier of quality freshers
 
Oops
Oops
Gayathri Ganesh
 
201005 accelerometer and core Location
201005 accelerometer and core Location
Javier Gonzalez-Sanchez
 
Presentation 1st
Presentation 1st
Connex
 
C# classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Objective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 
Jaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
C#ppt
C#ppt
Sambasivarao Kurakula
 
introduction to c #
introduction to c #
Sireesh K
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
C#2
C#2
Sudhriti Gupta
 
Net framework
Net framework
Abhishek Mukherjee
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Understanding C# in .NET
Understanding C# in .NET
mentorrbuddy
 
C#unit4
C#unit4
raksharao
 
Java2
Java2
Ranjitham N
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
yazad dumasia
 
Object oriented programming. (1).pptx
Object oriented programming. (1).pptx
baadshahyash
 
Objective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
Presentation 1st
Presentation 1st
Connex
 
Objective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 
Jaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
introduction to c #
introduction to c #
Sireesh K
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Understanding C# in .NET
Understanding C# in .NET
mentorrbuddy
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
yazad dumasia
 
Object oriented programming. (1).pptx
Object oriented programming. (1).pptx
baadshahyash
 
Ad

More from Wiliam Ferraciolli (20)

Lecture 12 monitoring the network
Lecture 12 monitoring the network
Wiliam Ferraciolli
 
Lecture 11 managing the network
Lecture 11 managing the network
Wiliam Ferraciolli
 
Lecture 10 the user experience
Lecture 10 the user experience
Wiliam Ferraciolli
 
Lecture 10 the user experience (1)
Lecture 10 the user experience (1)
Wiliam Ferraciolli
 
Lecture 9 further permissions
Lecture 9 further permissions
Wiliam Ferraciolli
 
Lecture 8 permissions
Lecture 8 permissions
Wiliam Ferraciolli
 
Lecture 7 naming and structuring objects
Lecture 7 naming and structuring objects
Wiliam Ferraciolli
 
Lecture 5&6 corporate architecture
Lecture 5&6 corporate architecture
Wiliam Ferraciolli
 
Lecture 4 client workstations
Lecture 4 client workstations
Wiliam Ferraciolli
 
Lecture 3 more on servers and services
Lecture 3 more on servers and services
Wiliam Ferraciolli
 
Lecture 2 servers and services
Lecture 2 servers and services
Wiliam Ferraciolli
 
Lecture 1 introduction
Lecture 1 introduction
Wiliam Ferraciolli
 
Isys20261 lecture 14
Isys20261 lecture 14
Wiliam Ferraciolli
 
Isys20261 lecture 12
Isys20261 lecture 12
Wiliam Ferraciolli
 
Isys20261 lecture 11
Isys20261 lecture 11
Wiliam Ferraciolli
 
Isys20261 lecture 10
Isys20261 lecture 10
Wiliam Ferraciolli
 
Isys20261 lecture 09
Isys20261 lecture 09
Wiliam Ferraciolli
 
Isys20261 lecture 08
Isys20261 lecture 08
Wiliam Ferraciolli
 
Isys20261 lecture 07
Isys20261 lecture 07
Wiliam Ferraciolli
 
Isys20261 lecture 06
Isys20261 lecture 06
Wiliam Ferraciolli
 
Ad

Lecture 13, 14 & 15 c# cmd let programming and scripting

  • 1. Lectures 15 - 17: C#, cmdLet programming & scripting Network design & Administration
  • 2. Why does a Systems Administrator need to know about programming? • Tools not available to perform task • Have to write new tools • Use scripting to provide more power than Network Design & Administration executing single command line tools • Automate tasks • Need to alter the OS (if Unix based) • There are lots of reasons why a knowledge of programming is essential! 2
  • 3. Powershell • Powershell is “the next generation command shell and scripting language”[1] • Provides access to lots of powershell programs (cmdlets) • Cmdlets can be joined together (output -> input) Network Design & Administration • Powershell provides a set of scripting commands to facilitate in linking cmdlets together (more later) • Can program your own cmdlets to do specific tasks 3
  • 4. What do you need to know to be able to program a cmdlet? • C# ! • C# is a C++/Java like language • C# requires the .Net framework to be installed • Cmdlets are written in C# but you need to: • Extend the PSCmdLet class Network Design & Administration • Provide parameter attributes • Implement the following methods: • BeginProcessing • ProcessRecord • EndProcessing • Provide your code! • Before we look at cmdlet programming in more detail, a quick 4 introduction to C# is in order! [4]
  • 5. C# Data types • C# has the same primitive data types that you find in C++ and Java • int e.g. int value = 5; • bool e.g. bool receivedInput = false; • float e.g. float value = 8.5; Network Design & Administration • arrays e.g. string []params; BUT! • More complex data types: • String • List • ArrayList • Stack • Queue 5 • …
  • 6. C# Classes • In C#, everything is an Object • A class provides the blueprint as to what data and operations it can offer • However, you have to use the class blueprint to create an Network Design & Administration object instance before you can access it • Follows a similar syntax to a Java Class. public class MyFirstClass{ public MyFirstClass() { // Constructor … } Use dot notation tonew keyword Use the access the objects to instantiate object } methods 6 MyFirstClass m = new MyFirstClass(); m.print();
  • 7. Anatomy of a C# Program using System; 1. Using (import other namespace ConsoleApplication1 classes) { 2. Namespace class MyFirstProgram 3. Class definition { private String _message = "Hello "; 4. Private data 5. Class constructor Network Design & Administration public MyFirstProgram(String userName) 6. One Main method { per program (has to Console.WriteLine(_message + userName); } be static) 7. Parameter passing public static void Main(String[] args) 8. Instantiating a new { object MyFirstProgram myProg = new MyFirstProgram("Clark"); } 9. Writing output to } the console } 7
  • 8. C# Strings • Strings are objects of the System.String Class • Can assign a sequence of characters to them… String machineName = "CIB108-34"; • i.e. use the assignment operator = Network Design & Administration • You can join strings together… String fullName = machineName + ".ads.ntu.ac.uk"; • Using the + operator • Because String is a class there are several handy methods and properties it provides… • Length – returns the number of characters in the string • Substring( int startPosition, int length) – returns characters between start and start+length characters 8
  • 9. Inheritance • C# allows you to inherit functionality from another class. public class Employee { private String name = string.Empty; public Employee(String n) Network Design & Administration { public class Manager : Employee name = n; Inherits the print() method {} private List<Employee> employeeList = new List<Employee>(); public void print() { public Manager(String name) : base(name) Console.WriteLine("Employee name: " + name ); { } } } public void manages(Employee employee) { employeeList.Add(employee); 9 } }
  • 10. The Object Class • When you create a new class (for example): using System; public class MyFirstClass Network Design & Administration { public MyFirstClass() { // … } } • You can define a class and not provide any explicit inheritance. • However, all classes derive from a base class even if it is not 10 explicitly stated. • This is the object class.
  • 11. The object class • Because all classes derive from object within C# we can use the object class as a way of providing a generic interface to methods public void add(object obj) { } • This is done by boxing and unboxing which also allows value types (primitive data types) to act like reference types (objects) Network Design & Administration • For example, boxing value types: int myValue = 1000; object obj = myValue; int newValue = (int)obj; obj myValue int newValue 1000 1000 1000 11 • However, unboxing must be explicit!
  • 12. Namespaces • C# provides you with hundreds of classes that you can use within your programs. • Each class you create/use will have a name (e.g.): public class ListCommand • What happens if there is another class called ListCommand? Network Design & Administration • You can use a Namespace to limit the scope of any classes that you define: namespace myLibrary { public class ListCommand { // ... } } • Now ListCommand is visible within the myLibrary namespace 12 • You can now access your class as: myLibrary.ListCommand ...
  • 13. Interfaces • An interface allows you to define a specific interface to a class. • Any class that implements that interface will have to provide a set of pre-defined method signatures. namespace myLibrary Network Design & Administration { interface MyListInterface { void add(object onj); object get(int index); int size(); void toString(); } } 13
  • 14. Interfaces • To use an interface you have to specify a class which inherits the interface namespace myLibrary { interface MyListInterface Network Design & Administration { void add(object onj); object get(int index); int size(); void toString(); } public class MyList : MyListInterface { public MyList() { } 14 } }
  • 15. this and is keywords • this • Refers to current instance of an object • Example: private string name; public void setName(string name) { Network Design & Administration this.name = name; } • is • provides you with a way to determine if the object supports an interface • If it does, then you can access methods within it • Syntax: <expression> is <type> • Example: 15 Employee CKent = new Employee("Clark Kent"); if( CKent is Employee ) CKent.print();
  • 16. C# Control Structures • C# provides the same control structures as C/C++ and Java • if statement if( x == 10 ) { // … } else { // .. Network Design & Administration } • Remember - when comparing objects if( obj1 == obj2 ) {} • Isn’t comparing that the two objects contain the same data but is instead comparing the pointers of each object. • But Strings are different! String name1 = "clark"; String name2 = "lois"; 16 if( name1 == name2 ) Console.WriteLine("they are the same!"); else Console.WriteLine("they are not the same!");
  • 17. C# Control Structures • C# provides the same control structures as C/C++ and Java • Switch statement switch( value ) { Network Design & Administration case 1: Console.WriteLine("Option 1!"); break; case 2: Console.WriteLine("Option 2!"); break; default: Console.WriteLine("Option 2!"); break; 17 }
  • 18. Loops • For loops are the same as in C++/Java for (int iCounter = 0; iCounter < 10; iCounter++) { Console.WriteLine("counter = " + iCounter); } Network Design & Administration • Foreach: List<string> myList = new List<string>(); for (int counter = 0; counter < 10; counter++) { myList.Add("item " + counter); } foreach (string value in myList) { Console.WriteLine(value); 18 }
  • 19. Reading and Writing to the console namespace ConsoleApplication1 { class Program { static void Main(string[] args) Network Design & Administration { Console.WriteLine("Enter first number:"); int value1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number:"); int value2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("multiplying {0} by {1} gives {2}", value1, value2, (value1 * value2)); } 19 } }
  • 20. Exception handling • C# provides you with throw and try-catch statements so that you can handle any unwanted exceptions • Program { class Classes that you use within your C# code will usually throw an rd public List<string> myList =(especially if you are relying on 3 exception if an error occurs new List<string>(); static api’s / Main(string[] args) { part void libraries) Network Design & Administration Program m = new Program(); for (int counter = 0; counter < 10; counter++) { m.myList.Add("item " + counter); } Console.WriteLine(m.getIndex(50)); } public string getIndex(int index){ if (index > myList.Count) throw new IndexOutOfRangeException(); else return myList[index]; 20 } }
  • 21. Exception handling class Program { public List<string> myList = new List<string>(); static void Main(string[] args) { Program m = new Program(); for (int counter = 0; counter < 10; counter++) { m.myList.Add("item " + counter); Network Design & Administration } Try { Console.WriteLine(m.getIndex(50)); } catch (IndexOutOfRangeException error) { Console.WriteLine("Error occurred: " + error.Message); } } public string getIndex(int index) { if (index > myList.Count) throw new IndexOutOfRangeException(); else return myList[index]; 21 } }
  • 22. Properties • In C# you can use properties to access private data • Use the get and set methods to allow read or write access Private data stored within the class Network Design & Administration The get method returns the value of private string _name; the private data The property! element. Used when access the property by public string Name name or on RHS of = { Special keyword in C#. get { return _name; } Gives the value from set { _name = value; } the RHS of an = The set method allows operation. you to assign a value } to the private data 22 element. This is called Examples: automatically when = Name = “Clark”; is used String userName = Name;
  • 23. Exercise! • Spend 5 minutes to work out what errors are in the code in the hand-out. • The person who identifies the correct Network Design & Administration number of errors gets a prize! 23
  • 24. Now back to cmdlets … Cmdlet naming[2] • Cmdlets are named using a verb-noun pair • Verbs are used to describe what action the cmdlet will perform • Nouns are used to describe what entity the cmdlet will perform the action on • Examples (encountered in the labs): Network Design & Administration • New-ADComputer • Get-Help • Set-ADUser • There are lots of pre-defined verbs (stored in classes): • VerbsCommon VerbsLifeCycle • VerbsCommunications VerbsSecurity • VerbsData VerbsOther 24 • VerbsDiagnostic
  • 25. Sending input to cmdlets • Cmdlets can accept parameters new-gpo –name “Publishers Policy” • Cmdlets can also be chained together so that the output of one can be the input to another. Network Design & Administration • For example: new-gpo –name “Publishers Policy” | new-gplink –target “ou=publishers, dc=testnetwork, dc=com” • Here, new-gpo is creating a new GPO object and passing it (using the pipe symbol |) to the new-gplink cmdlet. 25
  • 26. Anatomy of a cmdlet using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; namespace HelloWorldExample { [Cmdlet(VerbsCommunications.Send, "Hello World Example!")] Network Design & Administration public class HellowWorld : PSCmdlet { [Parameter(Mandatory = true)] public string yourName { get { return userName; } set { userName = value; } } private string userName; protected override void ProcessRecord() { WriteObject("Hello" + userName + "!"); 26 } } }
  • 27. Processing within cmdlets • The Cmdlet and PSCmdlet classes provide the following methods: • BeginProcessing • ProcessRecord • EndProcessing • These methods need to be implemented by the developer Network Design & Administration • Sending objects through a pipeline between cmdlets can be demonstrated by the following :- Input Pipeline Output Pipeline Object 1 cmdlet Object 2 Begin Process End Object 3 Processing Record Processing 27 New Output Object 2 Object3
  • 28. Snap-ins • Once you have finished writing your C# cmdlet you have to create another file which contains snap-in information. • Snap-ins are used to register cmdlets with Network Design & Administration powershell and to setup any registry entries • If you do not register a cmdlet within powershell you will not be able to run it • A snap-in for the cmdlet would be added to your project and get linked in when the project is 28 compiled
  • 29. Anatomy of a Snap-in using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; using System.ComponentModel; namespace ListCommand { [RunInstaller(true)] Network Design & Administration public class ListCommandSnapIn : PSSnapIn { public override string Name { get { return "ListCommand"; } } public override string Vendor { get { return "Jon Robinson"; } } public override string Description { get { return "New directory listing command"; } 29 } } }
  • 30. Compiling cmdlets and linking into Powershell 1. Cmdlets can be created and compiled within visual studio • Need a special template project to create cmdlets which can be downloaded from the web[3] 2. Can also be compiled using the .Net framework C# Network Design & Administration compiler (csc.exe) • Found under windowssystem32Microsoft.Net<.net version> 3. Use the installutil command to register the cmdlet in powershell 4. Use add-pssnapin <new cmdlet> to access cmdlet from powershell prompt 30
  • 31. Powershell Scripting • Powershell provides a rich scripting language • Used to provide more complex functionality linking cmdlet’s together • Types of language features available: Network Design & Administration • variables • if/else statements • switch statements • for loops • command line parameter passing 31 • Etc…
  • 32. Powershell scripting example [1] [int]$intPing=10 [string]$intNetwork="127.0.0." Variables have the following syntax: [<data type>] $<variable name> = <data value> for($i=1; $i -le $intPing; $i++) { Available data types: $strQuery = "select * from win32_pingstatus Network Design & Administration [array] [bool] where address = '" [char] [byte] + $intNetwork + $i + "'" $wmi [decimal] = get-wmiobject -query $strQuery [double] [hashtable] [int] "Pinging $intNetwork$i ..." [long] [string] if( $wmi.statuscode -eq 0 ) [single] [xml] {"success"} -eq (equal to) else If statement syntax: -lt (less than) {"error: " + $wmi.statuscode + " occurred"} -gt (greater than) if( $<variable name> <evaluation expression> <value> )equal to) -ge (greater than or 32 } {"success"} -le (less than or equal to) else -ne (not equal) {"fail"}
  • 33. Powershell switch example Switch statement syntax: switch <expression evaluation type> ($<variable name>) { … expressions … } Network Design & Administration [int] $simpleSwitchExample = 2 switch($simpleSwitchExample) { 1 { "Option 1" } 2 { "Option 2" } 3 { "Option 3" } default { "No idea..." } 33 }
  • 34. Powershell switch example [string] $regularExpressionSwitchExample = "1234" [int] $size = 0 switch -regex ($regularExpressionSwitchExample) { "d{4}" { $size = 4; break; } "d{3}" { $size = (regular expression) -regex 3; break; } -wildcard (wildcard!) Network Design & Administration "d{2}" { $size = 2; break; } "d{1}" { $size = 1; break; } default { "No idea..." $size = -1 } } if( $size -gt 0 ) { "The string had " + $size + " characters" } else { "Wasn't able to work out how many characters!" } 34
  • 35. Getting input from the user • Scripts can interact with the user to provide more functionality. • Scripts can display information by just saying “message…”. • However, this is not formatted. • Can use the Write-Host cmdlet to display output. Network Design & Administration • Can format the message (colours, spaces, etc) • For example: Write-host “hello world” –foregroundcolor black –backgroundcolor white • Scripts can get input from the user by using the Read-Host cmdlet. • For example: $ipAddress = Read-Host “Enter the ip address:” • Can use the –AsSecureString option to mask what has been 35 entered. $password = read-host –assecurestring “Enter your password:”
  • 36. Powershell functions function display { param ([string]$message="") Write-Host "Your message is $message" } Network Design & Administration display "hello world" Un-typed – could be any type of information function display( $message ) { Write-Host "Your message is $message" } display "hello world" 36
  • 37. Powershell functions function display { param ([string]$message="") param ([int]$repeat=1) $returnMessage = “” for($count=1; $count –le $repeat; $count++) { Network Design & Administration Write-Host "Your message is $message“ $returnMessage = $returnMessage + “Your message is $message” } return $returnMessage } 37 display("hello world“, 5)
  • 38. Next Time & References • Updating Systems References [1] “Windows PowerShell Scripting Guide”, Wilson, E., Microsoft Press [2] http://msdn.microsoft.com/en-us/library/windows/desktop/ms714428%28v=vs.85%29.aspx Network Design & Administration [3] http://channel9.msdn.com/forums/sandbox/249904-Windows-PowerShell-Visual-Studio-2005- Templates-C-and-VBNET [4] http://msdn.microsoft.com/en-us/library/zw4w595w.aspx 38