Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, November 2, 2017

C# 6

1. Defining a Parameterless Constructor for a struct

In C# 5.0, every struct had a default parameterless constructor that you couldn’t override. Using the new operator invoked this constructor and all members of the struct were assigned default values.

public struct MyPoint
{
   public double X;
   public double Y;
}


class Program
{
   static void Main(string[] args)
   {
      MyPoint pt = new MyPoint(); // default values for X, Y (0.0)
      Console.WriteLine("{0}, {1}", pt.X, pt.Y);
   }
}


In C# 6.0, you can explicitly define a parameterless constructor for a struct, giving non-default values to the members of the struct

public struct MyPoint
{
   public double X;
   public double Y;


   public MyPoint()
   {
      X = 100.0;
      Y = 100.0;
   }
}

static void Main(string[] args)
{
   MyPoint pt = new MyPoint(); // 100.0, 100.0
   Console.WriteLine("{0}, {1}", pt.X, pt.Y);
}



2. Filtering Exceptions

C# 6.0 will include support for exception filters, that is–only catching a particular type of exception if an associated expression evaluates to true.
You can filter exceptions by including an if statement after the catch expression. If the result of evaluating the expression supplied is true, the exception is caught. If not, the behavior is as if you didn’t supply a catch block.
In the example below, we don’t catch divide by zero exceptions on Saturdays


int denom;
try
{
   denom = 0;
   int x = 5 / denom;
}
// Catch /0 on all days but Saturday
catch (DivideByZeroException xx) if (DateTime.Now.DayOfWeek != DayOfWeek.Saturday)
{
   Console.WriteLine(xx);
}



3. Using Lambda Expressions for Function Members

In C# 5.0, you could use a lambda expression wherever a delegate instance was expected. For example:

Func doubleMyNumber = (i) => 2 * i;

In C# 6.0, you can also use a lambda expression as the body of a function member. This simplifies the syntax for simple methods. For example:

public class Dog
{
   public Dog(string name, int age)
   {
      Name = name;
      Age = age;
   }

   public string Name { get; protected set; }
   public int Age { get; set; }

   public void AgeIncrement() => Age++;
   public int AgeInDogYears() => Age * 7;
}



4. Using Lambdas for Getter-Only Auto-Properties

In addition to using lambda expressions for method bodies in C# 6.0, you can use a lambda expression to implement the getter of a read-only auto-property.

public string Name { get; protected set; }
public int Age { get; set; }

public string BackwardsName => new string(Name.Reverse().ToArray());


The presence of the lambda expression tells the compiler that this is a property with a getter, rather than a field


5. Auto-property initializers

In early C# times there was only one way to declare them – very explicit:

private string _name = "Joe"; // backing field
public string Name
{
   get { return _name; }
   set { _name = value; }
}


The C# 6 release serves well here. You can now initialize property inline. It’s concise and readable.

public string Name { get; protected set; } = "Joe"
public string Name { get; set; } = "Joe";
public List Ingredients { get; } = new List { "dough", "sauce", "cheese" };


All of the initializers you’ve seen so far evaluate to a static expression. Non-static expressions, like the ones below, will generate compiler errors:

// compiler errors //public string Name2 { get; set; } = Name; //public decimal Price4 { get; set; } = InitMe();

decimal InitMe() { return 5m; }


The code tries to initialize Name2 with the value of Name, another property, which won’t work. Similarly, InitMe() is an instance method that won’t compile when used as the initializer for Price4. It doesn’t matter that InitMe() returns a numeric literal. Both of these situations generate a compiler error. Here's the error message for Price4

A field initializer cannot reference the non-static field, method, or property 'PizzaBase.InitMe()'

A virtual auto-property can be initialized too. Here’s an example:

A virtual auto-property can be initialized too. Here’s an example:

During initialization of the containing type, Price initializes before the constructor executes. It initializes like a field, meaning that a Price property override isn’t called during auto-property initialization. If you wanted the polymorphic initialization, you should initialize Price in the base class constructor, like this:

public abstract class PizzaBase
{
   public string Name { get; protected set; } = "Cheeze";

   public virtual decimal Price { get; set; } = 3.00m;

   public PizzaBase(IEnumerable extraIngredients)
   {
      Price = 2.95m;
   }
}


The abstract PizzaBase class is a base class for the PepperoniPizza class shown below. This class overrides the Price property:

public class PepperoniPizza : PizzaBase
{
   public decimal ExtraPrice { get; set; } = 0.25m;

   decimal price;
   public override decimal Price
   {
      get
      {
         return price;
      }

      set
      {
         price = value + .50m;
      }
   }

   public PepperoniPizza(decimal extraFees) : base(new List { "pepperoni" })
   {
      ExtraPrice += extraFees;
      Name = "Pepperoni";
   }
}

Thursday, July 20, 2017

C# Func vs Action

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action)

Func is probably most commonly used in LINQ - for example in projections: list.Select(x => x.SomeProperty) or filtering: list.Where(x => x.SomeValue == someOtherValue) or key selection: list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List.ForEach: execute the given action for each item in the list





Traditional way of using Delegate

//Declare delegate
public delegate void PrintMessage(string message);
public delegate int Calculate(int x, int y);


class SimpleClass
{
   public void SayHello(string name)
   {
      Console.WriteLine("Hello {0}", name);
   }


   public int Add(int x, int y)
   {
      return x+y;
   }
}

//Use delegate
var sc = new SimpleClass();
var printer = new PrintMessage(sc.SayHello);
printer("Pollux");

var calculator = new Calculate(sc.Add);
var result = calculator(5,10);



Action

This delegate was introduced in Framework 2.0. We can now use Action delegate to pass a method as a parameter without explicitly defining the delegate. The compiler will take care of it. This delegate can accept parameters but without a return type.

Action act = delegate(string name)
{
   Console.WriteLine("Hello ", name);
};


Call the delegate use act(4, 5)



Func

This was introduced in Framework3.5. This delegate is different from Action in the sense that it supports for return value.

Func fn = delegate(int x, int y)
{
   return x+y;
};


Call the delegate use Console.WriteLine(“Using Func<> :” + fn(6, 6));

Monday, July 3, 2017

How to resolve a System.Security.Principal.IdentityNotMappedException?

Sometimes when working with a non-English version of Windows, we get kinda problem
"Some or all identity references could not be translated"
This indicates that we are getting a System.Security.Principal.IdentityNotMappedException
What does it mean?


The first thing to understand is that in Windows, User Accounts and Groups have a unique and immutable identifier known as a Security Identifier (SID). When working with User Accounts and Groups in Windows, you can work with them via their SID or by their name.

In Windows, a user is represented by an Access Token (You can find more information on Access Tokens at http://msdn.microsoft.com/en-us/library/windows/desktop/aa374909(v=vs.85).aspx) which can be associated with a process or to a thread (via impersonation).
The token contains the user’s SID and all the Groups the user is a member of. The token contains the Group SIDs. (The groups are NOT stored by their names)

There are Win32 APIs that allows an application to translate between the name and the SID:



These Win32 APIs actually calls the LSA APIs. (One difference with these APIs is that they allow to translate multiple names/SIDs instead just one.)


When converting between a Name and a SID and vice versa, you can encounter an error if the translation can’t be done. The common Win32 Error code that you will see is 1332 also known as ERROR_NONE_MAPPED which translates to “No mapping between account names and security IDs was done.”

At the LSA API level where status errors are returned, the error is: STATUS_NONE_MAPPED or STATUS_SOME_NOT_MAPPED. In .NET, the error code is mapped as the following exception:System.Security.Principal.IdentityNotMappedException

Why would the translation APIs fail? Well, the API remarks provides some details on how the translation is done. It uses a lookup order to translate (there is also a local cache as well)

In addition to looking up SIDs for local accounts, local domain accounts, and explicitly trusted domain accounts, LsaLookupSids can look up SIDs for any account in any domain in the Windows forest, including SIDs that appear only in the SIDhistory field of an account in the forest. The SIDhistory field stores the former SIDs of an account that has been moved from another domain. To perform these searches, the function queries the global catalog of the forest.

So a translation failure could happen if you have an issue with your Domain(s) or an issue with SID History. So the first step in determining the issue is identifying which user or SID is the issue. Once you have identified the User or SID, you can then review its relationship with the caller (who is this and what domain do they belong to and what domain does the system belong to where the caller is running)

Finally, a word of advice, internally most APIs are going to be working with SIDs so you can avoid the translation error and improve performance by always trying to work with SIDs.
You’ll notice that most classes in .NET such as IsInRole() allows you to specify a SID instead of the name (via the SecurityIdentifier class). WindowsIdentity.Groups allows you access to the SID as well.


Example:
I want to set permission for a user

static void SetPermission(string directory)
{
   var directoryInfo = new DirectoryInfo(directory);
   var directorySecurity = directoryInfo.GetAccessControl();
   CanonicalizeDacl(directorySecurity);
   directorySecurity.AddAccessRule(new FileSystemAccessRule("BUILTIN\\IIS_IUSRS", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
   directoryInfo.SetAccessControl(directorySecurity);
}


This code would be failed if it run in a non-English version of Windows because the "BUILTIN\\IIS_IUSRS" could not be translated. Exactly the "BUILTIN" could not be translated. To fix this problem, I could change to remove "BUILTIN" or use an SID instead.

static void SetPermission(string directory)
{
   var directoryInfo = new DirectoryInfo(directory);
   var directorySecurity = directoryInfo.GetAccessControl();
   var sid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
   directorySecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
   directoryInfo.SetAccessControl(directorySecurity);
}


Refer these links for SID
https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
https://msdn.microsoft.com/en-us/library/cc980032.aspx

Tuesday, January 19, 2016

Threads vs. Tasks

.Net has three low-level mechanisms to run code in parallel: Thread, ThreadPool, and Task. These three mechanism serve different purposes.

Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture. 

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available. 

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.


ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.


Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.


Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads. The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.