Search

Get the Computer, User and domain name using Javascript

This come quite easy, you just have to initialize an ActiveX object for "WScript.Network"
 
/* Jscript - ComputerName, Username & DoaminName */

var oWshNet = new ActiveXObject("WScript.Network");
var computerNmae = oWshNet.ComputerName;
var userName = oWshNet.UserName;
var domainName = oWshNet.UserDomain;


Note: This works only with ActiveX in IE.

Interface in C#

An interface contains only the signatures of methods, delegates or events.
  • The implementation of the methods is done in the class that implements the interface, as shown in the following example.
  • An interface can be a member of a namespace or a class and can contain signatures of Methods.properties.Indexes & Events.
  • An interface can inherit from one or more base interfaces.
  • When a base type list contains a base class and interfaces, the base class must come first in the list.
  • A class that implements an interface can explicitly implement members of that interface.
  • An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    interface ISampleInterface
    {
    void SampleMethod();
    }

    namespace Tutorial
    {
    class Program : ISampleInterface
    {
    // Explicit interface member implementation:
    void ISampleInterface.SampleMethod()
    {
    // Method implementation.
    Console.WriteLine("Method implementation.");
    }

    static void Main(string[] args)
    {
    // Declare an interface instance.
    ISampleInterface obj = new Program();
    // Call the member.
    obj.SampleMethod();
    Console.ReadLine();
    }
    }
    }





    The following example demonstrates interface implementation. In this example, the interface IPoint contains the property declaration, which is responsible for setting and getting the values of the fields.

    The class Point contains the property implementation. random



    using System;
    using System.Collections.Generic;
    using System.Text;

    interface IPoint
    {
    // Property signatures:
    int x
    {
    get;
    set;
    }
    int y
    {
    get;
    set;
    }
    }// interface

    class Point : IPoint
    {
    // Fields:
    private int _x;
    private int _y;
    // Constructor:
    public Point(int x, int y)
    {
    _x = x;
    _y = y;
    }
    // Property implementation:

    public int x
    {
    get
    {
    return _x;
    }
    set
    {
    _x = value;
    }
    }
    public int y
    {
    get
    {
    return _y;
    }
    set
    {
    _y = value;
    }
    }
    }// class

    namespace IndiLogiX.Tutorial
    {
    class Program
    {
    static void PrintPoint(IPoint p)
    {
    Console.WriteLine("x={0}, y={1}", p.x, p.y);
    }
    static void Main(string[] args)
    {
    Point p = new Point(2, 3);
    Console.Write("My Point: ");
    PrintPoint(p);
    Console.ReadLine();
    }
    }
    }



  • Collection Class in C#

    This tutorial shows how to implement a collection class that can be used with the foreach statement.

    The foreach statement is a convenient way to iterate over the elements of an array. It can also enumerate the elements of a collection, provided that the collection class has implemented the System.Collections.IEnumerator and System.Collections.IEnumerable interfaces.

    Example 1

    The following code sample illustrates how to write a collection class that can be used with foreach. The class is a string tokenizer, similar to the C run-time function strtok.

     

    // tokens.cs
    using System;
    // The System.Collections namespace is made available:
    using System.Collections;

    // Declare the Tokens class:
    public class Tokens : IEnumerable
    {
    private string[] elements;

    Tokens(string source, char[] delimiters)
    {
    // Parse the string into tokens:
    elements = source.Split(delimiters);
    }

    // IEnumerable Interface Implementation:
    // Declaration of the GetEnumerator() method
    // required by IEnumerable
    public IEnumerator GetEnumerator()
    {
    return new TokenEnumerator(this);
    }

    // Inner class implements IEnumerator interface:
    private class TokenEnumerator : IEnumerator
    {
    private int position = -1;
    private Tokens t;

    public TokenEnumerator(Tokens t)
    {
    this.t = t;
    }

    // Declare the MoveNext method required by IEnumerator:
    public bool MoveNext()
    {
    if (position < t.elements.Length - 1)
    {
    position++;
    return true;
    }
    else
    {
    return false;
    }
    }

    // Declare the Reset method required by IEnumerator:
    public void Reset()
    {
    position = -1;
    }

    // Declare the Current property required by IEnumerator:
    public object Current
    {
    get
    {
    return t.elements[position];
    }
    }
    }

    // Test Tokens, TokenEnumerator

    static void Main()
    {
    // Testing Tokens by breaking the string into tokens:
    Tokens f = new Tokens("This is a well-done program.",
    new char[] {' ','-'});
    foreach (string item in f)
    {
    Console.WriteLine(item);
    }
    }
    }

     


    Unboxing in C#

    Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
  • Checking the object instance to make sure that it is a boxed value of the given value type.
  • Copying the value from the instance into the value-type variable.
    The following statements demonstrate both boxing and unboxing operations:
     int i = 123;      // a value type 
    object o = i; // boxing
    int j = (int)o; // unboxing

    The following figure demonstrates the result of the previous statements.
    Unboxing Conversion
    UnBoxing Conversion graphic


  • For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

    Boxing in C#

    Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
    Consider the following declaration of a value-type variable:
    The following statement implicitly applies the boxing operation on the variable i:
    int i = 123;
    
    
    
    // Boxing copies the value of i into object o. 
    object o = i;
    
    
    

    The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.
    Boxing Conversion

    BoxingConversion graphic
    It also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:
    int i = 123;
    object o = (object)i;  // explicit boxing
    
    
    
    
    
    Example:
    class TestBoxing
    {
    static void Main()
    {
    int i = 123;
    
    // Boxing copies the value of i into object o. 
    object o = i;  
    
    // Change the value of i.
    i = 456;  
    
    // The change in i does not effect the value stored in o.
    System.Console.WriteLine("The value-type value = {0}", i);
    System.Console.WriteLine("The object-type value = {0}", o);
    }
    }
    /* Output:
    The value-type value = 456
    The object-type value = 123
    */
    
    
    
    
    The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.
    class TestUnboxing
    {
    static void Main()
    {
    int i = 123;
    object o = i;  // implicit boxing 
    
    try
    {
    int j = (short)o;  // attempt to unbox
    
    System.Console.WriteLine("Unboxing OK.");
    }
    catch (System.InvalidCastException e)
    {
    System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
    }
    }
    }
    
    This program outputs:
    Specified cast is not valid. Error: Incorrect unboxing.
    If you change the statement:
    int j = (short) o;
    to
    int j = (int) o;
    the conversion will be performed, and you will get the output:
    Unboxing OK.

    Boxing and Unboxing in C#

    Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object. In the following example, the integer variable i is boxed and assigned to object o.



    int i = 123;
    // The following line boxes i.
    object o = i;






    The object o can then be unboxed and assigned to integer variable i:


    o = 123;
    i = (int)o; // unboxing






    The following examples illustrate how boxing is used in C#.


    // String.Concat example.
    // String.Concat has many versions. Rest the mouse pointer on
    // Concat in the following statement to verify that the version
    // that is used here takes three object arguments. Both 42 and
    // true must be boxed.
    Console.WriteLine(String.Concat("Answer", 42, true));


    // List example.
    // Create a list of objects to hold a heterogeneous collection
    // of elements.
    List mixedList = new List();

    // Add a string element to the list.
    mixedList.Add("First Group:");

    // Add some integers to the list.
    for (int j = 1; j < 5; j++)
    {
    // Rest the mouse pointer over j to verify that you are adding
    // an int to a list of objects. Each element j is boxed when
    // you add j to mixedList.
    mixedList.Add(j);
    }

    // Add another string and more integers.
    mixedList.Add("Second Group:");
    for (int j = 5; j < 10; j++)
    {
    mixedList.Add(j);
    }

    // Display the elements in the list. Declare the loop variable by
    // using var, so that the compiler assigns its type.
    foreach (var item in mixedList)
    {
    // Rest the mouse pointer over item to verify that the elements
    // of mixedList are objects.
    Console.WriteLine(item);
    }

    // The following loop sums the squares of the first group of boxed
    // integers in mixedList. The list elements are objects, and cannot
    // be multiplied or added to the sum until they are unboxed. The
    // unboxing must be done explicitly.
    var sum = 0;
    for (var j = 1; j < 5; j++)
    {
    // The following statement causes a compiler error: Operator
    // '*' cannot be applied to operands of type 'object' and
    // 'object'.
    //sum += mixedList[j] * mixedList[j]);

    // After the list elements are unboxed, the computation does
    // not cause a compiler error.
    sum += (int)mixedList[j] * (int)mixedList[j];
    }

    // The sum displayed is 30, the sum of 1 + 4 + 9 + 16.
    Console.WriteLine("Sum: " + sum);






    In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.


    Casting in C#

    Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed. For example:
    static void TestCasting()
    {
    int i = 10;
    float f = 0;
    f = i;  // An implicit conversion, no data will be lost.
    f = 0.5F;
    i = (int)f;  // An explicit conversion. Information will be lost.
    }
    
    
    
    
    


    A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined. You can write custom conversion operators to convert between user-defined types. For more information about defining a conversion operator, see explicit (C# Reference) and implicit (C# Reference).

    The following program casts a double to an int. The program will not compile without the cast.


    class Test
    {
    static void Main()
    {
    double x = 1234.7;
    int a;
    a = (int)x;  // cast double to int
    System.Console.WriteLine(a);
    }
    }
    

    Polymorphism in C#

    Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism. In C#, every type is polymorphic. Types can be used as their own type or as a Object instance, because any type automatically treats Object as a base type.

    Polymorphism is important not only to the derived classes, but to the base classes as well. Anyone using the base class could, in fact, be using an object of the derived class that has been cast to the base class type. Designers of a base class can anticipate the aspects of their base class that are likely to change for a derived type. For example, a base class for cars might contain behavior that is subject to change when the car in question is a minivan or a convertible. A base class can mark those class members as virtual, allowing derived classes representing convertibles and minivans to override that behavior.

    Overview

    When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.

    Replacing a member of a base class with a new derived member requires the new keyword. If a base class defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or property on a derived class. The new keyword is placed before the return type of a class member that is being replaced. For example:


    public class BaseClass
    {
    public void DoWork() { }
    public int WorkField;
    public int WorkProperty
    {
    get { return 0; }
    }
    }

    public class DerivedClass : BaseClass
    {
    public new void DoWork() { }
    public new int WorkField;
    public new int WorkProperty
    {
    get { return 0; }
    }
    }





    When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members. Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. For example:



    DerivedClass B = new DerivedClass();
    B.DoWork(); // Calls the new method.

    BaseClass A = (BaseClass)B;
    A.DoWork(); // Calls the old method.



    In order for an instance of a derived class to completely take over a class member from a base class, the base class has to declare that member as virtual. This is accomplished by adding the virtual keyword before the return type of the member. A derived class then has the option of using the override keyword, instead of new, to replace the base class implementation with its own. For example:

    public class BaseClass
    {
    public virtual void DoWork() { }
    public virtual int WorkProperty
    {
    get { return 0; }
    }
    }
    public class DerivedClass : BaseClass
    {
    public override void DoWork() { }
    public override int WorkProperty
    {
    get { return 0; }
    }
    }





    Fields cannot be virtual; only methods, properties, events and indexers can be virtual. When a derived class overrides a virtual member, that member is called even when an instance of that class is being accessed as an instance of the base class. For example:



    DerivedClass B = new DerivedClass();
    B.DoWork(); // Calls the new method.

    BaseClass A = (BaseClass)B;
    A.DoWork(); // Also calls the new method.




    Virtual methods and properties allow you to plan ahead for future expansion. Because a virtual member is called regardless of which type the caller is using, it gives derived classes the option to completely change the apparent behavior of the base class.


    Virtual members remain virtual indefinitely, no matter how many classes have been declared between the class that originally declared the virtual member. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. For example:




    public class A
    {
    public virtual void DoWork() { }
    }
    public class B : A
    {
    public override void DoWork() { }
    }

    //--
    public class C : B
    {
    public override void DoWork() { }
    }





    A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealed keyword before the override keyword in the class member declaration. For example:




    public class C : B
    {
    public sealed override void DoWork() { }
    }




    In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes using the new keyword, as the following example shows:




    public class D : C
    {
    public new void DoWork() { }
    }





    In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.


    A derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword. For example:

    public class A
    {
    public virtual void DoWork() { }
    }
    public class B : A
    {
    public override void DoWork() { }
    }


    //--2


    public class C : B
    {
    public override void DoWork()
    {
    // Call DoWork on B to get B's behavior:
    base.DoWork();

    // DoWork behavior specific to C goes here:
    // ...
    }
    }


    Create a multidimensional array

    This C# code snippet creates a multidimensional Array of the specified Type, dimension lengths, and lower bounds.
    using System;
     
    public class MultidimensionalArray
    {
       public static void Main()
       {
          int[] lowerBounds = {1, 2, 4};
          int[] lengths     = {4, 2, 1};
          Console.WriteLine
             ("One dimensional array lower bound = {0}", 
             new string[10].GetLowerBound (0));      
          Array array = Array.CreateInstance 
             (typeof (int), lengths, lowerBounds);
          Console.WriteLine
             ("Bounds dimension {0} = [{1},{2}]", 
             0, array.GetLowerBound (0), array.GetUpperBound (0)); 
          Console.WriteLine
             ("Bounds dimension {0} = [{1},{2}]", 
             1, array.GetLowerBound (1), array.GetUpperBound (1)); 
          Console.WriteLine
             ("Bounds dimension {0} = [{1},{2}]", 
             2, array.GetLowerBound (2), array.GetUpperBound (2));
       } 
    }