Friday, July 27, 2012

How to enable hidden administrator account in windows 7 - Vista

First you’ll need to open a command prompt in administrator mode by right-clicking and choosing “Run as administrator” (or use the Ctrl+Shift+Enter shortcut from the search box)



Now type the following command:
net user administrator /active:yes
 You should see a message that the command completed successfully. Log out, and you’ll now see the Administrator account as a choice.

Wednesday, July 25, 2012

.NET Framwork Tools

Develop, configure, and deploy applications by using Microsoft .NET Framework technologies
[MSDN LINKS]





























Source : MSDN

Tuesday, July 24, 2012

Partial Keyword in C#

A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:
  • Signatures in both parts of the partial type must match.
  • The method must return void.
  • No access modifiers or attributes are allowed. Partial methods are implicitly private.
The following example shows a partial method defined in two parts of a partial class:
namespace PM
{
partial class A
{
partial void OnSomethingHappened(string s);
}

// This part can be in a separate file.
partial class A
{
// Comment out this method and the program
// will still compile.
partial void OnSomethingHappened(String s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
}

More Information On MSDN

Override in c#

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

In this example, the Square class must provide an overridden implementation of Area because Area is inherited from the abstract ShapesClass:

abstract class ShapesClass
{
abstract public int Area();
}
class Square : ShapesClass
{
int side = 0;

public Square(int n)
{
side = n;
}
// Area method is required to avoid
// a compile-time error.
public override int Area()
{
return side * side;
}

static void Main()
{
Square sq = new Square(12);
Console.WriteLine("Area of the square = {0}", sq.Area());
}

interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}

}
// Output: Area of the square = 144
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. For information about inheritance, see Inheritance (C# Programming Guide).[MSDN LINK]
You cannot override a non-virtual or static method. The overridden base method must be virtualabstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.[MSDN LINK]
You cannot use the newstatic, or virtual modifiers to modify an override method.
An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property, and the overridden property must be virtualabstract, or override.
For more information about how to use the override keyword, see Versioning with the Override and New Keywords (C# Programming Guide) and Knowing when to use Override and New Keywords.[MSDN LINK]
This example defines a base class named Employee, and a derived class named SalesEmployee. The SalesEmployee class includes an extra property,salesbonus, and overrides the method CalculatePay in order to take it into account.

class TestOverride
{
public class Employee
{
public string name;

// Basepay is defined as protected, so that it may be
// accessed only by this class and derrived classes.
protected decimal basepay;

// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}

// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return basepay;
}
}

// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal salesbonus;

// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay,
decimal salesbonus) : base(name, basepay)
{
this.salesbonus = salesbonus;
}

// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}

static void Main()
{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice",
1000, 500);
Employee employee2 = new Employee("Bob", 1200);

Console.WriteLine("Employee4 " + employee1.name +
" earned: " + employee1.CalculatePay());
Console.WriteLine("Employee4 " + employee2.name +
" earned: " + employee2.CalculatePay());
}
}
/*
Output:
Employee4 Alice earned: 1500
Employee4 Bob earned: 1200
*/


DllImportAttribute Class in C#

Indicates that the attributed method is exposed by an unmanaged dynamic-link library (DLL) as a static entry point.


Namespace:  System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

You can apply this attribute to methods.
The DllImportAttribute attribute provides the information needed to call a function exported from an unmanaged DLL. As a minimum requirement, you must supply the name of the DLL containing the entry point.
You apply this attribute directly to C# and C++ method definitions; however, the Visual Basic compiler emits this attribute when you use the Declare statement. For complex method definitions that include BestFitMappingCallingConventionExactSpellingPreserveSigSetLastError,(MSDN LINK) or ThrowOnUnmappableChar (MSDN LINK) fields, you apply this attribute directly to Visual Basic method definitions.
Note   JScript does not support this attribute. You can use C# or Visual Basic wrapper classes to access unmanaged API methods from JScript programs.
For additional information about using the platform invoke service to access functions in unmanaged DLLs, see Consuming Unmanaged DLL Functions.(MSDN LINK)

The following code example shows how to use the DllImportAttribute attribute to import the Win32 MessageBox function. The code example then calls the imported method.

using System;
using System.Runtime.InteropServices;

class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}

Extern Keyword in C#

The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code. In this case, the method must also be declared as static, as shown in the following example:

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
NOTE:
The extern keyword can also define an external assembly alias, which makes it possible to reference different versions of the same component from within a single assembly. For more information, see extern alias (C# Reference).
It is an error to use the abstract (C# Reference) (MSDN LINK) and extern modifiers together to modify the same member. Using the extern modifier means that the method is implemented outside the C# code, whereas using the abstract modifier means that the method implementation is not provided in the class.
NOTE:
The extern keyword has more limited uses than in C++. To compare with the C++ keyword, see Using extern to Specify Linkage in the C++ Language Reference.
In this example, the program receives a string from the user and displays it inside a message box. The program uses the MessageBox method imported from the User32.dll library.

// Add the following directive to your file:
// using System.Runtime.InteropServices;
class ExternTest
{
[DllImport("User32.dll", CharSet=CharSet.Unicode)]
public static extern int MessageBox(int h, string m, string c, int type);

static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return MessageBox(0, myString, "My Message Box", 0);
}

}
This example creates a DLL from a C program that is invoked from within the C# program in the next example
// cmdll.c
// Compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
return i*10; 
}

This example uses two files, CM.cs and Cmdll.c, to demonstrate extern. The C file is the external DLL created in Example 2 that is invoked from within the C# program.

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
[DllImport("Cmdll.dll")]
public static extern int SampleMethod(int x);

static void Main()
{
Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
}
}

Yield in C#

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration. For more information about iterators, see Iterators (C# Programming Guide).(MSDN LINK) The following example shows the two forms of the yield statement.

public
static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}



In a yield return statement, expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.
In a yield break statement, control is unconditionally returned to the caller of the iterator, which is either the IEnumerator.MoveNext method (or its genericSystem.Collections.Generic.IEnumerable<T>(MSDN LINK) counterpart) or the Dispose method of the enumerator object.
The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.(MSDN LINK)
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.
yield statement cannot appear in an anonymous method. For more information, see Anonymous Methods (C# Programming Guide).(MSDN LINK)

When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, see Exception Handling Statements (C# Reference).(MSDN LINK)

In the following example, the yield statement is used inside an iterator block, which is the method Power(int number, int power). When the Powermethod is invoked, it returns an enumerable object that contains the powers of a number. Notice that the return type of the Power method isSystem.Collections.IEnumerable, an iterator interface type.

public class List
{
//using System.Collections;
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}

static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
}
/*
Output:
2 4 8 16 32 64 128 256
*/

Out Keyword in C#

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:

class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile:

class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out."
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:

class OutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(out int i) { i = 5; }
}
Properties are not variables and therefore cannot be passed as out parameters.
For information about passing arrays, see Passing Arrays Using ref and out (C# Programming Guide).(MSDN LINK)

Declaring an out method is useful when you want a method to return multiple values. The following example uses out to return three variables with a single method call. Note that the third argument is assigned to null. This enables methods to return values optionally.

class OutReturnExample
{
static void Method(out int i, out string s1, out string s2)
{
i = 44;
s1 = "I've been returned";
s2 = null;
}
static void Main()
{
int value;
string str1, str2;
Method(out value, out str1, out str2);
// value is now 44
// str1 is now "I've been returned"
// str2 is (still) null;
}
}

Ref Keyword in C#

The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.

class RefExample
{
static void Method(ref int i)
{
i = 44;
}
static void Main()
{
int val = 0;
Method(ref val);
// val is now 44
}
}

An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile:
class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out."
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither as in the following example:
class RefOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters.
For information about how to pass arrays, see Passing Arrays Using ref and out (C# Programming Guide).(MSDN LINK)
class RefExample2
{
static void Method(ref string s)
{
s = "changed";
}
static void Main()
{
string str = "original";
Method(ref str);
Console.WriteLine(str);
}
}
// Output: changed

Params in C#

The params keyword lets you specify a method parameter that takes a variable number of arguments.

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

static void Main()
{
// You can send a comma-separated list of arguments of the
// specified type.
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");

// A params parameter accepts zero or more arguments.
// The following calling statement displays only a blank line.
UseParams2();

// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);

object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);

// The following call causes a compiler error because the object
// array cannot be converted into an integer array.
//UseParams(myObjArray);

// The following call does not cause an error, but the entire
// integer array becomes the first element of the params array.
UseParams2(myIntArray);
}
}
/*
Output:
1 2 3 4
1 a test

5 6 7 8 9
2 b test again
System.Int32[]
*/

Source:MSDN

Lock Statement in C#

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form

Object thisLock = new Object();
lock (thisLock)
{
// Critical code section.
}
For more information, see Thread Synchronization (C# Programming Guide).(MSDN link)
The lock keyword ensures that one thread does not enter a critical section of
code while another thread is in the critical section. If another thread tries
to enter a locked code, it will wait, block, until the object is released.
The section Threading (C# Programming Guide)(MSDN LINK) discusses threading.
The lock keyword calls Enter at the start of the block and Exit at the end of the block.
In general, avoid locking on a public type, or instances beyond your code's control. The common constructs 

lock (this)lock (typeof (MyType)), andlock ("myLock") violate this guideline:
  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.
Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.)
The following sample shows a simple use of threads without locking in C#.
//using System.Threading;

class ThreadTest
{
public void RunMe()
{
Console.WriteLine("RunMe called");
}

static void Main()
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(b.RunMe);
t.Start();
}
}
// Output: RunMe called

The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance will never become a negative number.








// using System.Threading;

class Account
{
private Object thisLock = new Object();
int balance;

Random r = new Random();

public Account(int initial)
{
balance = initial;
}

int Withdraw(int amount)
{

// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}

// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (thisLock)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
}

public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}

class Test
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}