Friday, November 28, 2014

Async and Await in c# 5.0

What is Async and Await and why do we need it?

In .NET Framework 4.0 the Task Type was introduced which greatly simplified the asynchronous programming check out my article on Tasks here.  
With .NET Framework 4.5 comes C#  5.0 and brings along Async and Await which makes its writing asynchronous programs same a writing synchronous codes,will discuss more on that .

We all know when a method is called , the control only returns to the caller once the method is executed , this behavior is called synchronous .

Check out the below code    
    private  void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
            SimulateLongProcess();

           Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
           Result.Text += Environment.NewLine;
        }


       void SimulateLongProcess() 
        {         

             Longrunningtask();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        void Longrunningtask()
        {
          
                for (int i = 0; i < int.MaxValue; i++)
                {

                }
           
       }
The Above code will freeze your UI as heavy computing is done on the main thread, you can either spin of a thread on every click of the button, or use tasks (better suited to the scenario) ,

Updated the above code to use task 
     private  void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
            SimulateLongProcess();

        }


       void SimulateLongProcess() 
        {         

             Longrunningtask();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        void Longrunningtask()
        {

            Task.Run(() =>
            {
                for (int i = 0; i < int.MaxValue; i++)
                {

                }

                Dispatcher.BeginInvoke((Action)(() =>
                {
                    Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
                    Result.Text += Environment.NewLine;

                }

                    ));
            });
           
       }
    }
        
Task does solve the problem of freezing the UI as the heavy computing is thread pooled and then returned back to the main thread after completion of the task , if you compare the code of the synchronous execution and asynchronous exception, there is a quite a bit if difference , The Async and Await make the asynchronous  Code look more like Synchronous code

Check the Code update to use async await below:
  private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Result.Text += "Long Running Simulation Started" + DateTime.Now.ToLongTimeString();
            Result.Text += Environment.NewLine;
           await SimulateLongProcessAsync();

           Result.Text += "Long Running Simulation Ended" + DateTime.Now.ToLongTimeString();
           Result.Text += Environment.NewLine;
        }


       async Task SimulateLongProcessAsync() 
        {         

            await LongrunningtaskAsync();
       }    
       /// 
       /// Simulating Long Running Task
       /// 
       /// 
        async  Task LongrunningtaskAsync()
        {
          await  Task.Run(() =>
            {
                for (int i = 0; i < int.MaxValue; i++)
                {

                }
            });
       }
There is a lot of patterns build around the use of async and await which is explained very well by Lucian in his Blog and Here.

Background Task in windows phone 8.1

What we had in windows phone 8 ?

In windows phone 8  we had is Period Tasks or Resource Intensive task that could run as background agents , but these has a lot of constraints(CPU time , memory , running time and more), and very little  flexibility to trigger these background agents .

What does windows Phone 8.1 bring to the table ?  

First and the very notable thing is the Triggers, now there is lot more ways you can kick off a background Task , now the developers have lot of options to kick off a background tasks.

Common Trigger Types

  • System Triggers: you can subscribe to some of the events(InternetAvailable,NetworkStateChange,OnlineIdConnectedStateChange,   SmsReceived,TimeZoneChange) raised by OS and trigger your background tasks .
  • Timer Triggers : your app can register a background task that runs every 30 minutes on Windows Phone (** for this trigger you need your app  needs to be on the lock screen).
  • Push Notification Triggers:You can trigger the background task when you receive a raw notification for your app.
  • Maintenance Triggers: This is similar to timer Triggers but this trigger does not have  the prerequisite of the app being placed on the lock screen, instead this will only run when the device is pluggedin  to the power source .
  • Update Task Triggers: Allows you to run some code in the background when the user updates your app to the newer version .
  • DeviceUse Triggers: allows you to access  peripheral devices through background  Tasks .
  • RfcommConnection Triggers:This triggers a background task when ever a Rfcomm connection is made to a device 
  • DeviceConnectionChange Triggers:This Triggers a background task when a Bluetooth device gets connected or disconnected .
  • GattCharacteristicNotificationChange : The Bluetooth device can trigger a background Task by Changing a value for which the app has subscribed for a ValueChanged Event .

How enable your app to run in background

How to create  background task

  1. Add a new project to your solution where you have your foreground app and the project type should be of the type Windows Runtime Component .
  2. Add the above project as a reference to your foreground app(windows phone app) .
  3. In your Windows Runtime Component all you need to do is implement the IBackgroundTask   interface as shown below .

  1. using Windows.ApplicationModel.Background; namespace Tasks { public sealed class ExampleBackgroundTask : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { //if you have any async operation then use deferral backgroundtaskdef _def = taskInstance.Getdeferral(); // perform your async task and then call deferral complete _def.Complete(); } } }

 How to register the background task  from your foreground app?

  1. The minimum  object that are need to participate in  registering a background task are

  • TaskEntryPoint :this  will be the fully qualified name of your class name that has implemented the IBackgroundTask Interface
  • TaskName:the name given to your background task
  • TriggerType:lets developer configure how to trigger the background tasks
  • Condition: you can add a system conditions(InternetAvailable ,FreeNetworkAvailable and more  ) along with the trigger option , this condition is an optional parameter.
Below is the generic method which registers the background task and returns a BackgroundTaskRegistration object .

public static async BackgroundTaskRegistration RegisterBackgroundTask(
                                                string taskEntryPoint, 
                                                string name,
                                                IBackgroundTrigger trigger,
                                                IBackgroundCondition condition)
{
    //
    // Check for existing registrations of this background task.
    //

    foreach (var cur in BackgroundTaskRegistration.AllTasks)
    {

        if (cur.Value.Name == taskName)
        {
            // 
            // The task is already registered.
            // 

            return (BackgroundTaskRegistration)(cur.Value);
        }
    }


    //
    // Register the background task.
    //

    var builder = new BackgroundTaskBuilder();

    builder.Name = name;
    builder.TaskEntryPoint = taskEntryPoint;
    builder.SetTrigger(trigger);

    if (condition != null)
    {

        builder.AddCondition(condition);
    }

   // Rumour of a bug which means you have to call this before calling Request...
            BackgroundExecutionManager.RemoveAccess();

            await BackgroundExecutionManager.RequestAccessAsync();

    BackgroundTaskRegistration task = builder.Register();

    return task;
}


3. Declare background task in App Manifest

Update your App Manifest file (Package.appxmanifest) file to declare  all the background tasks used in the app, if this step is not done then the registration will fail.
below is  xml code snippet tgat needs to used in the manifest file 

  <Extensions>
  <Extension Category="windows.backgroundTasks" 

            EntryPoint="Your fully qualified Backgroundclas Name">
    <BackgroundTasks>
      <Task Type="systemEvent" />
    </BackgroundTasks>
  </Extension>
</Extensions>
   
Here is the Sample Code for working with Background task (Download).

Data storage options in windows phone 8.1


Where can I store my app data in windows phone 8.1?

  1. Local storage(folders and settings): save your data here which is local to your app(** no data limits)
  2. Roaming Storage (folder and settings): if your want to save some data which you want to access across devices in which your app is installed , then your should be saving your data in Roaming storage (** have a data limit of 100kb).
  3. Temp Storage(folder ): if your have any data that needs to be saved for  only limited amount of time  and does not really affect the app if lost then save your data in temp folder
  4. PasswordVault: if you want to same some user credentials data securely then you will save  then in the PasswordVault(** this data roams across devices).

  How do I save and retrieve values from  local settings ?

   Below is the code snippet on to how  you save a load  from local settings 

//Get the LocalSettings object 
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;          
 //Check if the key already exists 
 if (localSettings.Values.ContainsKey("MySetting"))
 {
    //overwrite the value if you need to 
 }
else
 {
    localSettings.Values["MySetting"] = "Green Theme";
 }
 //Read the value ** will return null objet if there is no key as "MySetting"
Object value = localSettings.Values["MySetting"];
//Delete the "MySetting" entry if exists 
localSettings.Values.Remove("MySetting");           

How do I save and retrieve values from local folders?

few point worth  remembering
  • you can access your files through uri's (ms-appdata:///local/,ms-appdata:///roaming/,ms-appdata:///temp/)
  • you can also access the files though the api(Windows.Storage.ApplicationData.Current.LocalFolder,RoamingFolder,TempFolder).
  • you can write and read from  a file either by using FileIO or by using the streams
Below Code Snippet  to  write data to a file  and read data from a file with FileIO
     public async void writeTextToLocalStorageFile(string filename, string text)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            /* you can get access to the file as shown below as well
               Uri  theFileUri = new Uri(string.Format("ms-appdata:///local/{0}",filename));
               StorageFile fileToWrite = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(theFileUri);
               await FileIO.WriteTextAsync(fileToWrite, text);
             * */
       
            //Or you can get access to the file directly 
            //you use the CreationCollisionOption to suit your needs 
            
            StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(file, text);
        }
  public  async Task readTextFromLocalStorage(string filename)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
             /* you can get access to the file as shown below as well
               Uri  theFileUri = new Uri(string.Format("ms-appdata:///local/{0}",filename));
               var folder = Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(theFileUri);
             */
            StorageFile file = await localFolder.GetFileAsync(filename);
            string result = await FileIO.ReadTextAsync(file);
            return result;
        }

Working with Roaming Settings and Roaming Folders?

The concept of reading  and writing to the  roaming settings and folders is exactly same as that of  local settings and folders .
But there is two important points that you need to remember while you are working with roaming settings .
  1. Both your apps needs to have same name (say if are developing a app for big windows and windows phone  then both these app needs to have the same name).
  2. You need to make the package store association for both your windows phone and big windows app , its very simple to do it all you need to do is right click on the project (windows and windows phone store) navigate to the stores context menu option and then click on Associate app with store  menu
** if your apps don't satisfy above two conditions then your roaming data does not work.

How to save Objects to File and read them back ?

In the nutshell we can save the public properties and fields of objects into a file in json/xml format through  serialization , and we can  load the json back as objects  in the memory  through deserialization . 
   public class Employee 
    {
        public string Name { get; set; }

        public string Designation { get; set; }

        public int ID { get; set; }
    }

    public class Employees 
    {

        public List employeeList = new List();


        public Employees()
        {
            employeeList.Add(new Employee() { Name = "testname1", ID = 1, Designation = "testDesignation1" });
            employeeList.Add(new Employee() { Name = "testname2", ID = 2, Designation = "testDesignation2" });
            employeeList.Add(new Employee() { Name = "testname3", ID = 3, Designation = "testDesignation3" });
            employeeList.Add(new Employee() { Name = "testname4", ID = 4, Designation = "testDesignation4" });
        }
    }

 // Code to Serialize to json 
       public async void writeEmployeesJsonToLocalStorage(string filename)
        {

            Employees empCollection = new Employees();
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
          
            StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);


            using (Stream stream = await file.OpenStreamForWriteAsync())
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Employees));

                jsonSerializer.WriteObject(stream, empCollection);
            } ;

        }

// Code to deSerialize from json
 public async void ReadEmployeesJsonFromLocalStorage(string filename)
        {

            Employees empCollection;
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            StorageFile file = await localFolder.GetFileAsync(filename);



            using (Stream stream = await file.OpenStreamForReadAsync())
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Employees));

                empCollection = jsonSerializer.ReadObject(stream) as Employees;
            };

        }

Working with credential locker

CredentialLocker lets to you save secure data like username and password on the device and also lets these data roam across device .

Below is the  code .snippet to save a retrieve  the data from the password vault.

 // Store credentials in the CredentialLocker
 private void SaveMyCred(string userName, string password) 
  {
   PasswordVault myVault = new PasswordVault();
   PasswordCredential userCred = new PasswordCredential("MyResource", userName, password);
   myVault.Add(userCred);
   }

  private void GetCred() 
   {
      PasswordVault myVault = new PasswordVault();
      List allCred;
      PasswordCredential myCred;
      try
       {
         allCred = myVault.FindAllByResource("MyResource") as List;
          myCred =allCred.FirstOrDefault();
        }
      catch (Exception)
        {
          // Handle any exception
        }

   }

Assess user data

you can get access to photos in the Picture library (camera roll ,saved pictures),Music library and video library . 
** first thing you need to make sure when working with these folders is that you have to check the capabilities  in the app manifest file .

Below is the code to get access to Know Folders
           //Gives access to PicturesLibrary
           var picturesFolders =  Windows.Storage.KnownFolders.PicturesLibrary;
           //Gives access to VideosLibrary
           var videoFolders = Windows.Storage.KnownFolders.VideosLibrary;
           //Gives access to MusicLibrary
           var musicFolders = Windows.Storage.KnownFolders.MusicLibrary;

Once you get access to these folders, you can

  • Create your own  Sub folders 
  • Loop though all the sub folders and access the files 
  • get meta data of the folders and files 
  • read and write files with FileIO and stream 
** in the capabilities if you have checked Removable storage then the files in  PicturesLibrary,VideosLibrary and MusicLibrary of the SD Card is also  accessible with the same above API's


Working with SD Card .

you can write to read data from SD card .

** as usual don't forget to check the Removable storage capability in app manifest 

same apis will work if  you want to access the picture library , music library and video library  from SD Card as discussed in the previous section .

if you want to access  files in other folders then you do associate the file type that you need to access.

How to i do the fie association ?

In the Package.appxmanifest file got the Declaration and Select the File Type Associations as shown below .




















Once the file type associations are done you can access the files of that type from the app

Below is the sample code snippets lets your access a text file in the sd card
** TO DO

Thursday, November 27, 2014

Task In C#


Task in very simple terms represents a asynchronous operation , Task type was introduced in .net framework 4.0   as a part of TPL(task parallel library) ,if you are working with WINRT Api's  we can see these Task Types  as a return type for  most of the APi's with supports async and await keywords.

What is the difference between Threads and Tasks? 

  • Threads are very expensive (both on memory ,CPU time , Context switching )to create and to clean up  
  • Running code in a task does not mean a new thread instead Task use the thread pool shipped with  the .net framework,the framework manages the available cores to provide  best possible output .this is not available with thread where we developers have to manage every thing. 
  • Threads work in a single core but Task best suited to utilize multiple core.
  • Easier Exception Handling in case of Tasks

How to create a task ?

Task in its simplest form can be created as below:
// if you asre working with .NET Framework 4 
Task.Factory.StartNew(() => { Console.WriteLine("I am being run by Task "); });

//if you are working with .NET Framework 4.5 and above 
 Task.Run(() => { Console.WriteLine("I am being run by Task "); });

Once the task is started the code block after that will continue to run, Check; the below code

static void Main(string[] args)
        {

          var theTask =  Task.Run(() => {
              // simulating a long running task 
              Thread.Sleep(10000);
              Console.WriteLine("I am run by Task"); });
     Console.WriteLine("is my task complted ::"+theTask.IsCompleted);
     Console.WriteLine("last line of code now the application will exit");
        }
in the above code the app will exit even before the task is completed.

How to wait for a task to complete?

All this needs is a one line of code(Task.Wait()) as show below
 static void Main(string[] args)
        {
          var theTask =  Task.Run(() => {
              // simulating a long running task 
              Thread.Sleep(3000);
              Console.WriteLine("I am run by Task"); });
     Console.WriteLine("is my task complted ::"+theTask.IsCompleted);
          theTask.Wait();
     Console.WriteLine("is my task complted ::" + theTask.IsCompleted);
     Console.WriteLine("last line of code now the application will exit");
        
        }

How to Return a value from task?

Every task that is initiate either gives you back a task object or any of its  Generics sub classes  Task<TResult>, using this  Task object you can track the status of the Running tasks ,check is its completed get the result from the task if  there is any return type also also easily check if the task failed , all these features are given out of the box in  with Task and it is very tedious to build this feature when working with Threads .

Below is a  simple code snippet which returns a simple string :

      //Returns the task object which represents the task that is initiated
       static Task ReturnTask()
        {
            Task theTask = Task.Run(() =>
            {
                // simulating a long running task 
                Thread.Sleep(3000);
                Console.WriteLine("I am run by Task");
                return  "I am done with the task";
            });
            return theTask;            
        }
     // you get the reference to the task object 
     Task checkTask = ReturnTask();

// when you want to get  the result all you need to  do 
// query the task object and get the result if ready 
 void ReadResult(Task taskObject) 
        {
            bool isTaskCompleted = taskObject.IsCompleted;
            if (isTaskCompleted)
            {
                Console.WriteLine("task Completed with the result ::" + taskObject.Result);
            }

        }
** There is lot more explore

  • Imperative Data Parallelism (Involves using Parallel for,foreach and Invoke )
  • Declarative Data Parallelism(PLINQ)

Thursday, November 6, 2014

Windows Runtime apps Application Life Cycle(Windows Phone 8.1 and windows 8.1)



The application life cycle is a very basic and one the most important concepts that every app developer should know and use the application life cycle events to handle the use case scenarios to give the best possible experience to the user .

If you are a windows phone 8 developer then things have changed here and if you have developed for big windows(windows 8/8.1) then you will feel more at home.

Lets get started .


Image Courtesy: msdn 

Must have seen the above diagram in many  msdn  articles , lets get in to the details .

From the above diagram we have the below list of application states 

  • Running
  • Suspended 
  • NotRunning 

The application is either Running, Suspended or NotRunning .

When do we say the application is running?

When the application in the foreground, and also when the application goes to the background(by pressing the windows key/search key/back key)just before it gets suspended.


When do we say the application is Suspended?

When the user navigates away from your application ,which he can in many ways (by pressing the windows key/search key/back key). and does not return back to the application soon enough(could be between 5 to 10 seconds), the application gets suspended.

 When do we say the application is NotRunning?

  •  If the application is a fresh install (application was never launched).
  •  If the application is closed by the user (using task switcher).
  •  If the application goes into the suspended state , and the OS decides to terminate the application to  give some memory to foreground application.

Now that we know the different application states, lets us see what the OS has to offer to the developers to react to these different states.

Below are the list to events that are available for developers

Now lets go over each of  the application life cycle events .

Application.OnLaunched Event

Usually  this event is fired when the user taps on the primary tile or launches the application from the app list. but need not be the only case , there are several ways by  which an application can be launched ,more on that later.

How does the developer react to this event?

In the app.xaml.cs file you have to override the  Onlaunched  Handler 

 protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        //
    }

What should the developer do when this event occurs?

In the Onlaunched Handler the developer gets the LaunchActivatedEventArgs object as parameter which holds  vital information like how the application was launched and how was the previous instance of the application exited. using these information  the developer can decide to show the default page of the application or take the user to the page where he was when the application was previously exited.

Check out the below code :
protected override void OnLaunched(LaunchActivatedEventArgs e)
    {

          /*means application is launched by the user 
             by clicking on tile/from app list for the first time */
        if (e.Kind == ActivationKind.Launch && e.PreviousExecutionState == ApplicationExecutionState.NotRunning)
        {
             // and you would want to show the splash screen and take the user to the default screen
        }

             /*means application is launched by the user 
                by clicking on tile/from app list and the previous instance of the  app was closed by the user        */
        if (e.Kind == ActivationKind.Launch && e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
        {
            //here based on the developer choice you can either take the user to default screen/restore the previous state 
        }


        /*means application is launched by the user 
           by clicking on tile/from app list and the previous instanse app was terminated by OS to free up memory*/    
        if (e.Kind == ActivationKind.Launch  && e.PreviousExecutionState == ApplicationExecutionState.Terminated )
        {
            /*here the developer would want to take the user to the screen where he left off
              you would want to consider the timespan as well when the app  was suspended,
              because  sometimes if the app was suspended for days , you would want to take the user 
              to the default screen rather than restoring the state.
             *** its totally the developers calls  make sure the user gets the best experiance using the application */
        }

        /* lets say you  app is  music player application  the app is registered to handle the .mp3 file */
            
        if (e.Kind == ActivationKind.File && e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
        {
            /* this condition occurs when the application launched by clicking a mp3 file,
              here developer can take appropriate action */
              
        }
}

we just walked through a few combinations of use cases that the developer would generally handle.There are lot more  possible combinations check out ActivationKind enumeration  and ApplicationExecutionState enumeration , use the combination best suited to your needs.

Application.OnActivated Event


This event is fired when the application is not launched by App Contracts and Extensions like  voice command, PickerReturned etc, can find more about it here .

How does the developer react to this event?

In the app.xaml.cs file you have to override the  OnActivated  Handler

 protected override void OnActivated(IActivatedEventArgs args)
    {
           
    }

What should the developer do when this event occurs?

The IActivatedEventArgs object passed as  parameter offers the same  ActivationKind enumeration and ApplicationExecutionState enumeration values and  things can be handled in the exact same way as in OnLaunched Event.

There are contract specific Activation events as well which the developer will have to subscribe for different type of activation of the application.

Application.Suspended  Event


This event occur when the user navigates away from your app by either hitting the windows keys , task switcher or any other way .


What should the developer do when this event occurs?

  • save any unsaved session data of the user so that you can restore them when the user comes back to the application .
  • serialize heavy object and save  to a file , so that you can free up some memory .
  • release the recourse used  (opened file stream / network stream or more).

Please note the application will never receive a termination event, so you should do all the clean up job in this event Handler .


How does the developer react to this event?

In the app.xaml.cs file you can subscribe to the Suspending event in the App constructor or you can also do it at the page level .
 
public App()
    {
      this.InitializeComponent();
      this.Suspending += OnSuspending;
    }

 void OnSuspending(object sender, SuspendingEventArgs e)
    {
      // All your clean up logic here 
    }


OR

public MainPage()
   {
      InitializeComponent();
      Application.Current.Suspending +=
      new SuspendingEventHandler(App_Suspending);
   }

 void OnSuspending(object sender, SuspendingEventArgs e)
    {
      // All your clean up logic here 
    }


If you have any asynchronous operation that needs to be completed before the application is suspended then you will have to defer the suspension till the  async operation is complete.
** the operation still needs to complete within 10 seconds  .

Below is how you do the async operation .
async protected void OnSuspending(object sender, SuspendingEventArgs args)
{
    SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
    await SuspensionManager.SaveAsync();
    deferral.Complete();
}

Application.Resuming event


This event occurs when the application comes from suspended state into running state (when user switches back into your application).

What should the developer do when this event occurs?

When the application is resuming from the suspended state, the application data and states are automatically restored as the snap shot of the application is saved by the OS during suspension.
But there are scenarios when you have to handle this resuming state, let me list out a few of them 
  • Timer don't tick when the app is suspended you should handle the timer ticks.
  • you might want to make network calls to show the updated data.
  • you will have to update the location information.

How does the developer react to this event?

In the app.xaml.cs file you can subscribe to the Suspending event in the App constructor or you can also do it at the page level as already shown for suspended event .

public App()
    {
      this.InitializeComponent();
      this.Resuming += OnResuming;
    }

  void OnResuming(object sender, object e)
    {
    }


Downcast from Base Type to Derived Type in C#

There are times when developers try to Downcast an object of a Base Type to Derived Type.
Well !! in the nutshell it is not allowed by design.

We will see why with a trivial example
Lets have Employee class  as a base class and Manager class  a  derived class from the Employee

class Employee
    {

    }
class Manager : Employee
    {

    }
class Program
    {
        static void Main(string[] args)
        {
          //This is definitely not allowed
          //(Compile time casting exception)            
             Manager Mngr= new Employee();   

          // Well this seems to be ok(No compile time error) 
            Manager Mngr= (Manager)new Employee();
         }
    }

Run the above code
Result:Unable to cast object of type 'Employee' to type 'Manager'


Can every Employee be a Manager??
That is definitely not true.so the behavior looks correct.

Now lets see in which situation the downcast is successful.

For the cast to be successful, the instance you are down casting must be a instance of the class that you are down casting to.

Not clear enough !! .

Let me use the same example to clear the above statement.

static void Main(string[] args)
        {
            //Will say Manager is an employee. Well he is 
             Employee Emp = new Manager();

            // Now cast the Emp back to Manager
              Manager Mngr = (Manager)Emp;

         }

Run the  code with the above changes .
Result: the cast works..

We would want to void  the above scenario with a better design  using Interface (will talk more on interface in  another post) .

There is a tricky work around that would work for some scenarios
That is Serialize the base class type and then Deserialize it to the derived class type,
but this approach is only good if you have simple class structure and not too many objects to process

 static void Main(string[] args)
   {
     Employee Emp = new Employee();
     var IntermediateObject = JsonConvert.SerializeObject(Emp);
     Manager Mngr = JsonConvert.DeserializeObject(IntermediateObject);
   }

*using Newtonsoft.Json to Serialize and Deserialize