Best 3 Method to Export Office 365 Mailbox to PST File Easily

Udemy
The importance of data security has become a major concern in the present world. Data backup is considered as a reliable solution to secure data from any mishap. The matter gets more serious when it comes to protecting your Office 365 data. The data backup and retention policy of Microsoft is not a full-proof one. For this reasons, it is deemed essential to backup Office 365 mailbox online. Converting Office 365 emails into PST is a secured way to backup Office 365 data. This post will discuss how to export Office 365 Mailbox to PST. Here, readers will know different methods of migrating Office 365 data to PST.

Approaches to Convert Office 365 Mailbox to PST

Office 365 emails can be converted to PST using three different approaches. We will discuss all three techniques in detail. Users can follow the step by step instruction in order to perform O365 mailbox export.

Method 1: Using PowerShell
This technique uses PowerShell to export O365 Mailbox to PST. Before going to the guideline of this procedure, let’s define the examples used here. The mailbox that will be imported is test1@cloudsystool.onmicrosoft.com. The new account created in O365 for export purpose is test2.onmicrosoft.com. Finally, the email with all admin permission is test3@cloudsystool.onmicrosoft.com. Now, going straight to the stepwise instruction.

Step 1: Connecting to MS Exchange Using PowerShell

i. To begin the export process, execute the following command in PowerShell:
“$UserCredential = Get-Credential”

Users have to enter Office 365 credentials here including username and password in the dialog box that will appear named Windows PowerShell Credential Request. Enter test3@cloudsystool.onmicrosoft.com credentials in the window.

ii. Now, execute this command:
“$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic –AllowRedirection”

iii. After that, execute the following command:
“Import-PSSession $Session”

Remember:
  • Make sure to enter correct username and password in step 1. Incorrect credentials will stop you from proceeding.
  • To prevent denial-of-access (DoS) attacks, users are allowed to try three limited open remote PowerShell connections only with Exchange online organization.
  • Account that is being used for connecting to Exchange, must be turned on for remote PowerShell. Do not forget to confirm this.
  • ‘TCP port 80’ traffic between O365 account and local system must be opened. Make sure to check this.
Step 2: Providing Full Access Right to Mailbox to Export Using PowerShell

In this step, test1@cloudsystool.onmicrosoft.com will be provided complete access to test2.onmicrosoft.com mailbox. Use this example for granting permission:

“Add-MailboxPermission – User hr-freshdtls@msoutlookemails.com -Identity hr-managementdtls@msoutlookemails.com -AccessRights FullAccess -InheritanceType All”

Step 3: Open MS Outlook as test2.onmicrosoft.com. Confirm that in the list of mailbox on the left pane, test1@cloudsystool.onmicrosoft.com mailbox is visible. Wait a few minutes for permission grant to take effect.

Step 4: Check MS Outlook Configuration Settings

Here, validate if Outlook is prepared to get configured for saving all emails for limited time.Use the steps mentioned:

i. Click File on Menu bar >> Info page >> Account Settings
ii. Select Account Settings from menu. Select your account and click Change button.
iii. Check if Use Cached Exchange Mode option is enabled (checked) and Mail to keep offline option is set to All.
Users can relaunch Outlook to update it with all the recent changes made.

Step 5: Convert O365 Mailbox to PST by Using Import/Export Wizard
i. Open Import/ Export wizard to export test1@cloudsystool.onmicrosoft.com mailbox to PST. Click File >> Open & Export >> Import/ Export.
ii. From the options, choose Export to a file from the given list and click Next.
iii. Now, choose Outlook Data file (.pst) and then click on Next.
iv. From the list of mailbox folders, choose test1@cloudsystool.onmicrosoft.com and click Next. Also, check the option Include Subfolders.
v. Enter a new name and choose destination storage for PST file, for example, c:\tmp\outlook-archive- test1@cloudsystool -20160209.pst
vi. Choose from Do not export duplicate items or Replace duplicates with items exported options. Finally, click Finish.
vii. Now, enter a password or leave it blank, depending on your policy. Click OK.
viii. During export process, you will not be able to operate Outlook. Wait until the control is gained.

Step 6: Verifying Successful Completion of Export Process
In order to verify successful export of mailbox, compare the size of mailbox with the size of exported PST. Perform these steps to compare:

i. Right-click the mailbox situated on right pane. Choose the option Data file properties.
ii. Click Folder Size button under General tab.
iii. Click Server Data tab and take note of value mentioned as Total Size.
iv. Finally, check the exported PST file properties to find out the size. Compare if both the sizes are compatible or not.

Step 7: Removing Permission
After export completion, remove the permission granted earlier using PowerShell. Use this syntax to remove permission:

“Remove-MailboxPermission -User hr-freshdtls@stellaroutlookemails.com -Identity hr-managementdtls@stellaroutlookemails.com -AccessRights FullAccess”

Step 8: Closing PowerShell Session
After permission removal, execute this command to close down current PowerShell session:
“Remove-PSSession $Session”

After performing all the steps, Office 365 mailbox will convert to PST successfully.
  • Method 2: Using eDiscovery
In this method, an O365 inbuilt program called “eDiscovery PST Export Tool” is used for backup. Only Office 365 Admins can perform this method. Before starting the process, acquire permission for this tool by following the instruction.

i. Log into Office 365 Account by using Admin Credentials.

ii. First, go to Admin >> Exchange.


iii. From left pane, select Permissions. Then click admin roles tab and click Discovery Management.



iv. Click on + icon in order to add roles. From roles options, select Mailbox Import Export. Click + icon again under ‘Members’ and select the user who requires permission. Click on Save.



The selected user has received permission to use eDiscovery PST Export Tool. Now that user can transfer Office 365 mailbox to PST. Here are the steps to perform O365 mailbox backup.

a) Start Office 365 and go to Exchange Admin Center (EAC).
b) Click Compliance Management option from the left pane.



c) Now, click In-Place eDiscovery & Hold tab. The list of mailboxes will appear. Select your necessary items from the list.
d) Click on Download icon. A migration wizard will appear.



e) From the wizard, Browse to choose the destination location of the resultant PST file.
f) Select ‘Enable deduplication’ checkbox to avoid duplicate emails in PST file.
g) If needed, users can also select ‘Include unsearchable items’ checkbox. This includes emails that cannot be indexed by Exchange Search, like emails with attachments. All emails of this category will be downloaded in a separate PST file.
h) Click Export. This will start the backup. A progress box will appear that will show the development in export process.

Drawbacks of Export Methods using PowerShell and eDiscovery

Both these methods suffer from serious limitations. Here are some the drawbacks of these techniques.

(i) Admin Permission: These processes require Admin Permission. If users do not have permission, they will not be able to perform these methods.
(ii) Complex Process: These processes consume significant amount of time. Also, users have to be technically knowledgeable to perform these techniques.
(iii) Format Changing: Sometimes after migration to PST, changes in email formatting is seen. Data integrity of the files can be compromised too.

Method 3: Using Automated Tool

The numerous drawbacks of these methods are key to the popularity of automated tools. Users often opt for the method of using automatic application to export Office 365 mailbox to PST. Office 365 Exporter is considered as the perfect tool for this business. This program is devoid of all the drawbacks of previous methods and migrates O365 mailbox to PST effortlessly. It can even migrate several user accounts at the same time. This software supports Windows 10 and all other versions of Windows OS. Users do not need technical knowledge to operate this tool. All in all, this is a perfect application to export Office 365 mailbox to PST.

Conclusion

The concern over data security is increasing keeping pace with the importance of data. Despite being a cloud-based facility, taking backup of Office 365 mailbox is extremely important. Office 365 backup into PST can protect you during any unwanted situations. This write-up has been an endeavour to inform readers how to export Office 365 mailbox to PST. Users can try any of the methods mentioned here to save O365 data in PST. However, professionals suggest using the cited automated program for smooth migration of O365 to PST.



Implement Equality for Reference Types in C#

Udemy

Introduction

In the last post we discussed about why to implement equality for our value types in c# and we saw how it can help writing more efficient code when writing our own value types as the default implementation in .NET framework for value types uses reflection to check for equality of two value types on the basis of the values they contain so it is always a better option to override the equality behavior for our value types which of course will be a performance gain during execution. 

What we will learn ?

We didn't discussed about implementing equality for reference types so in this post we will be just focusing on overriding the equality behavior  for reference types, as with references types there are other complications involved too which are needed to be addressed when implementing equality for reference types which includes inheritance as unlike value types we have inheritance feature available in case of reference types and another thing is handling nulls to as reference types can be null but is not the case for value types. 


Another thing that we will see is what are the use cases where we should implement equality for reference types, we already saw the reasons why we need to do this in case of value types. 

We will be overriding equality for a reference type to demonstrate the concepts the same way as we did in case of value types to have clear understanding of the concepts here. We will see what the necessary steps are to do when implementing equality for a reference type and another important thing we will learn is how to implement it when we have inheritance involved too in reference types. For example, class A implements equality for itself but in future a class B inherits from A, in the case how the class B would implement the equality for itself without breaking the equality behavior of class A

Let's get Started

The way we implement equality for reference types is little different than what we do in case of value types. As we discussed above in case reference types we also have to deal with inheritance too, which we never need to handle in case of value types as they are by default marked as sealed in the .NET framework, so expecting the implementation of equality for reference types would be more complicated than of value types. 


Now let's create a reference type for which we will implement equality in this post next. So let’s start creating the class for which we will implement equality in this post.  

We will use the Car class as example as we want to understand it for Reference types. The following is the implementation of our Car class: 

    public class Car 
    { 

        public int MakeYear { get; private set; } 

        public Decimal Price { get; private set; } 

        public Car(int makeYear, Decimal price) 
        { 
            MakeYear = makeYear; 
            Price = price; 
        } 


        public override string ToString() 
        { 
            return $"Model: {MakeYear}, Price: {Price}"; 
        } 

    } 


We know that classes are Reference types and because of that we the ability to use Object Orientation principles in it and one of the important part of which is Inheritance and we will be looking in to how two objects are checked for  equality when inheritance is also in play and for that we will consider the Car type as base class and we will extend it with a subclass to understand the behavior how it behaves and how we can implement it.


Now we will create a derived class which will have overridden implementation which will be of course different than the base class. Let’s say we create a class called LeaseCar which will have an extra property which will hold the information of Lease options that are available for the lease car and the object will hold the specific options chosen at time of object creation.


Our LeaseCar class will look like following:

    public class LeaseCar : Car 
    { 

        public LeaseOptions Options { get; set; } 

        public LeaseCar(int makeYear, Decimal price, LeaseOptions options) : base(makeYear, price) 
        { 
            Options = options; 
        } 

        public override string ToString() 
        { 
            return $"{nameof(DownPayment)}: {DownPayment}, {nameof(InstallmentPlan)}: {InstallmentPlan.ToString()}, {nameof(MonthlyInstallment)}: {MonthlyInstallment}"; 
        } 

} 

Our LeaseCar contains one new property which will hold the options select for the car to be leased and we have provided overridden implementation for ToString() method too which will return the name of down payment information, Installment Plan and Monthly Installment for the car in comma separated form.


And our LeaseOptions implementation looks like :

    public class LeaseOptions 
    { 

        public Decimal DownPayment { get; } 

        public InstallmentPlan InstallmentPlan { get; } 

        public Decimal MonthlyInstallment { get; } 



        public LeaseOptions(Decimal downPayment, InstallmentPlan installmentPlan, Decimal monthlyInstallment) 
        { 

            DownPayment = downPayment; 
            InstallmentPlan = InstallmentPlan; 
            MonthlyInstallment = monthlyInstallment; 
        } 
  

    } 

First, we will write some basic code to see what the default behavior for is comparing two reference types for equality when there is no implementation being provided specifically about how to compare two. Following is the code for our Main Program:

        static void Main(string[] args) 
        { 

            Car carA = new Car(2018, 100000); 
            Car carA2 = new Car(2018, 100000); 
            Car carB = new Car(2016, 2500000); 

            
            LeaseCar leasedCarA = new LeaseCar(2014, 2500000, new LeaseOptions(1000000,InstallmentPlan.FiveYears, 10000)); 
            LeaseCar leasedCarA2 = new LeaseCar(2014, 2500000, new LeaseOptions(1000000, InstallmentPlan.FiveYears, 10000)); 
            LeaseCar leasedCarB = new LeaseCar(2016, 2500000, new LeaseOptions(1000000, InstallmentPlan.FiveYears, 10000)); 

  

            Console.WriteLine(carA == carA2); 
            Console.WriteLine(carA == carB); 
            Console.WriteLine(leasedCarA == leasedCarA); 
            Console.WriteLine(leasedCarB == carB); 
  

            Console.Read(); 

        } 

We can see that there are five different objects created all of which are either of type Car or their type inherits from Car due to which we can actually say that all objects are of type Car and we are comparing all of those with each other one by one for equality and the output is not any surprise, it is what we were expecting, all other comparison operations returned false except leaseCarA == leaseCarA which is quite obvious as we are comparing the leaseCarA object reference with itself and we are clear here that it is comparing the references for equality not values in it as class is a reference type. Following is the output of the above program: 


We can also check using Object.Equals() method instead of == operator in the above example program but the output will remain same as both will check for the references of two objects are pointing to same memory location or not.

One thing more to note is that we saw previously that for value types for == operator to get working for doing comparison we had to define overloads for == and != in that value type but for reference types we don’t need to define those as it is a reference type and the base type Object already takes care of doing reference comparison for any reference type except String as it’s case is little different which we have seen in one of the past post.

Motivation for Overriding Equality for Reference Types

The motivation to provide the overridden implementation for value types is now pretty clear to all of us i.e. the performance of the code as if we don’t provide own implementation for our value-types the framework will use reflection to compare the fields, properties of both objects for equality, but some of us might be having question in mind that Why do we need to implement for Reference types as well?

Here's the answer

The answer to it is that there can be cases where we don’t want to just rely on the reference equality for two objects of a particular reference, we might want to consider two objects to be equal if let’s say two of the properties in the reference type are having same value in both objects, in these kind of situations we would need to implement equality for those reference types ourselves instead of depending on the default behavior of framework for reference types.

So, we can say it this way as well that when we want our objects to be checked for equality on the basis of values in it instead of the reference of the objects. In general, it is not commonly needed to implement equality for reference types than value types. 

Possible Use Cases for Overriding Reference Equality

One example for this kind of case can be a class named Marks which holds the marks of each subject for a student and let’s say we frequently need to compare the marks of students with each other for any reason, in that case we can override the implementation for Marks class to compare the marks of each subject between two objects. Another case can be that we might have a class holding the location details as Latitude Longitude and we would want to check for equality on the basis of those values to be equal.

Examples

Another good example can be of a Model class or any class which holds string properties and we want the equality check to be done by comparing the string values. Let’s take the following class as example:

public class User
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string EmailAddress {get;set;}
}

Let's write the following code in Main method:

    void Main() 
    { 

    

      User user1 = new User() 
                    { 

                       FirstName="ehsan", 
                       LastName="sajjad", 
                       EmailAddress="ehsansajjad@yahoo.com" 
                   }; 

      User user2 = new User() 
                   { 

                      FirstName="ehsan", 
                      LastName="sajjad", 
                      EmailAddress="ehsansajjad@yahoo.com" 

                   }; 

    
    Console.WriteLine(user1 == user2); 

  } 

we will see that these two objects are not considered equal though both are equal if we consider the values in the properties they are all exactly same and equal but as the User is a reference type so it is doing reference equality here not value.

Expected Consequences of Overriding Equality

We should watch closely before implementing value equality in a reference type as most of the developers would be expecting the equality comparison to do reference equality check not value based, so there should be a good reason to override the default behavior of framework for reference types. 


The cases that we discussed above might also not be a good reason to override equality for reference types sometimes. If we are considering overriding equality for reference types we should first think about the usage of the class that we are writing and we use take into account  that does overriding the equality for it will make it more easy for the consumers of it or not, the result can be either one depending on what is the actual purpose of the that reference type and how the consumer code would be utilizing it. 

Alternative Approach for Overriding Reference Type Equality

.NET framework also provided another way to provide other developers the ability to compare the objects of your class using value equality to check if they contain the same values, so we can do that without overriding the equality for the reference type. 


We would need to write a EqualityComparer class which would inherit from  IEqualityComparer<T>  and we would write the logic there to compare  the reference type objects as value based. This actually allows developers to plug in for value equality check when needed otherwise the default behavior would be the reference equality check which is also default behavior in .NET framework for reference types. So, using this approach gives more flexibility when doing equality check, but one thing to note is that using this approach we would not be able to do value equality check using == operator and we will need to call the Equals method on the instance of equality comparer and passing both objects as parameter in for comparing them.  

Overriding Equals() in Base Class

So Now we will first define the equality behavior for our base class Car in which the first thing that will include is overriding the Object.Equals method so that it would compare two car objects using the values of its properties. 


The following will be the code for our base  class Employee as overridden  implementation of Equals method of Object. 

        public override bool Equals(object obj) 
        { 

            if (obj == null) 
                return false; 


            if (ReferenceEquals(obj, this)) 
                return true; 


            if (obj.GetType() != this.GetType()) 
                return false; 


            Car carToCheck = obj as Car; 

  
            return this.MakeYear == carToCheck.MakeYear 
                && this.Price == carToCheck.Price; 

        } 

The code is pretty simple, first of all it makes sure the passed in parameter is not null and if it's null we simply tell the caller that both objects are not equal and we would be comparing it with the object which actually called this instance method so it's obvious that this wouldn't be null.

Then we check if using ReferenceEquals() method that if both instances are reference to same object which means we are comparing the object to itself and that obviously get us to the result that both objects are equal of course, so we return true in that case. This check is useful in giving little performance benefit as eventually our latter check will also evaluate true so it's good if we get the result early within the method call and save ourselves from comparing multiple properties values of our type.

Another thing that we need to make sure before performing the values equality is that that type of passed in parameter object is same that of the this and that's what we are trying if they both have different type that simply means that they are not same object so we just return false as instances of two reference types wouldn't be equal normally.


Lastly, we have code which would check that if both objects have same values for the properties that we are checking then we can say that both objects are same and we return true as result.



We also need to provide the implementation of GetHashCode() method so that it aligns with our implementation of Equals() method, it would be quite same the way we did for value types before, here is the code for it:

        public override int GetHashCode() 
        { 
            return this.MakeYear.GetHashCode() ^ this.Price.GetHashCode(); 
        } 


We are just getting the values of the three properties and doing XOR of them. We will not go in to the details in this post about why we do this and other details, we will see details about this in some later post.



We have discussed this in one of previous posts too about what are the essential steps to do when overriding equality for a type, so here we have implemented two method, we also need to overload the == operator and != operator methods, as if we don't it would result in inconsistent and contradictory results for devs using this type. So, let’s write the overloads:

        public static bool operator ==(Car carA, Car carB) 
        { 
            return Object.Equals(carA, carB); 
        } 

  
        public static bool operator !=(Car carA, Car carB) 
        { 
            return !Object.Equals(carA, carB); 
        } 

We are just calling static Equals() method which will first check both the parameters to make sure that either of them is not null and then eventually will call the virtual Equals method of Object class and in return the overridden implementation of our type will get called which is what we want here and for != operator we are just  inverting the result of Object.Equals() method.

So, we are almost done with all the things needed to be implemented when overriding equality for a Reference type.

Overriding Derived Class Equality

Now, we will implement the equality in LeaseCar class which inherits from Car class. First of all like we did for Parent class we will provide the Equals() method override and here is the implementation for it:

        public override bool Equals(object obj) 
        { 

            if (!base.Equals(obj)) 
                return false; 

            LeaseCar objectToCompare = (LeaseCar)obj; 

            return this.Options == objectToCompare.Options; 

        } 

For the derived type we need to do it differently than for the base reference type. In Base we were checking equality of all the properties that we consider to be checked when comparing two objects of Car so here we will be reusing the base class method to do initial checking. So first we call the Equals implementation of Base and see what it returns. If the base implementation call results shows that both instances are not equal, we do not proceed for further derived class properties checking, as the base class already told us that the two objects are not same so, they are different it means.

But if the base class implementation tells that that both objects are equal then we proceed further for derived class checks to be executed for which the code starts from Line 5 in the above method and what base class Equals is doing is we already saw that above that it makes sure both instances are of same type and have same values in them and then we check the derived class properties for value equality to decide if the objects are equal or not.


But if we look at the property Options here it is also a reference type and object of type LeaseOptions class. So, we will need implement the Equality for that as well so that we can use it in the LeaseCar in a better manner. The following is the implementation for LeaseOptions:


    public class LeaseOptions 
    { 

        public Decimal DownPayment { get;  } 

        public InstallmentPlan InstallmentPlan { get;} 

        public Decimal MonthlyInstallment { get;  } 

  

        public LeaseOptions(Decimal downPayment,InstallmentPlan installmentPlan,Decimal monthlyInstallment) 
        { 

            DownPayment = downPayment; 
            InstallmentPlan = InstallmentPlan; 
            MonthlyInstallment = monthlyInstallment; 

        } 

  

        public override bool Equals(object obj) 
        { 

            if (obj == null) 
                return false; 


            if (ReferenceEquals(obj, this)) 
                return true; 


            if (obj.GetType() != this.GetType()) 
                return false; 

  
            LeaseOptions optionsToCheck = obj as LeaseOptions; 

  

            return this.DownPayment == optionsToCheck.DownPayment 
                && this.InstallmentPlan == optionsToCheck.InstallmentPlan 
                && this.MonthlyInstallment == optionsToCheck.MonthlyInstallment; 

        } 

        public override int GetHashCode() 
        { 

            return this.DownPayment.GetHashCode()  
                 ^ this.InstallmentPlan.GetHashCode() 
                 ^ this.MonthlyInstallment.GetHashCode(); 

        } 

  

        public static bool operator ==(LeaseOptions optionsA, LeaseOptions optionsB) 
        { 
            return Object.Equals(optionsA, optionsB); 
        } 

  

        public static bool operator !=(LeaseOptions optionsA, LeaseOptions optionsB) 
        { 
            return !Object.Equals(optionsA, optionsB); 
        } 

  

        public override string ToString() 
        { 
            return $"{nameof(DownPayment)}: {DownPayment}, {nameof(InstallmentPlan)}: {InstallmentPlan.ToString()}, {nameof(MonthlyInstallment)}: {MonthlyInstallment}"; 
        } 
  

    } 


So, now when we will call equality check for LeaseOptions it will be checked using the implementation provided and we will be reusing it in the other overloads that we need to write for Derived class and also would be used in GetHashCode() implementation of LeaseCar.



We don't need to take care of null handling as we first call the base.Equals and in the implementation of that we are already taking care of nulls. Now, let’s implement the  GetHashCode() method for LeaseCar:

        public override int GetHashCode() 
        { 
            return base.GetHashCode() ^ this.Options.GetHashCode(); 
        } 


So, what we are doing here is calling the base implementation to get the hash code of it and then XOR it with the field Options of LeaseCar and as we have also provided the implementation for LeaseOptions class too to generated the GetHashCode() the same way using all the fields that we want.



Now we also need to provide the == and != operator overloads as well which would be similar to what we did in base class to call the static object.Equals method which will eventually call the overridden implementation of LeaseCar via call to virtual Equals method of Object class.

The methods implemented would be like:
        public static bool operator ==(LeaseCar carA, LeaseCar carB) 
        { 
            return object.Equals(carA, carB); 
        } 


        public static bool operator !=(LeaseCar carA, LeaseCar carB) 
        { 
            return object.Equals(carA, carB); 
        } 

If we notice our above overloads are having same implementation what we have in the base class, so if we want to skip implementing these two we can and the result would be same what we will get using these. But for the sake of giving the whole implementation for derived class too we are adding it for this post.



Now as we are done with the implementation of both of our classes. Let's write some code to test for the correctness of our equality implementations. Following is the code to add in the Main method:


    class Program 
    { 

        static void Main(string[] args) 
        { 

            Car carA = new Car(2018, 100000); 
            Car carA2 = new Car(2018, 100000); 
            Car carB = new Car(2016, 2500000); 

            LeaseCar leasedCarA = new LeaseCar(2014, 2500000, new LeaseOptions(1000000,InstallmentPlan.FiveYears, 10000)); 
            LeaseCar leasedCarA2 = new LeaseCar(2014, 2500000, new LeaseOptions(1000000, InstallmentPlan.FiveYears, 10000)); 
            LeaseCar leasedCarB = new LeaseCar(2016, 2500000, new LeaseOptions(1000000, InstallmentPlan.FiveYears, 10000)); 

  

            Console.WriteLine(carA == carA2); 
            Console.WriteLine(carA == carB); 
            Console.WriteLine(leasedCarA == leasedCarA); 
            Console.WriteLine(leasedCarB == carB); 


        } 

    } 

Now we can observe form the console output that our objects are getting evaluated not on the basis of reference but using the values contained in the Field/Properties that we have dictated the type to use when comparing for equality. 



Summary

In this post, we learned the following things: 
  • We saw that how we can implement equality behavior for reference types so that they can act as value-types when comparing two objects. 
  • Due to inheritance feature that is supported in Reference Types it's more complex than Value Types to implement our Equality check behavior.
  • Another thing to remember is that it is not always a good idea to implement Equality for Reference types as by default they are compared using the object reference but in case of Value Types we should be implementing as that will give us performance hit as we will be able to eliminate the default behavior which uses reflection for custom Value Types. 
  • For implementing equality following are the thing to be done: 
    • Override the Equals() method of Object class in the Reference Type 
    • Override the GetHashCode() method of Object class in the Reference Type
    • Implement overloads for == and != operator for the type 



First .NET Core Console Application using Command Prompt

Udemy

Introduction

In this post, we will create our very first console application in .NET Core, we will see how we can build .NET Core based applications without using any IDE or Visual Studio. We will be using Command Line to create, build and run the application. If we don’t need all the fancy features that Visual Studio and Visual Studio Code offers, then we can build a .NET Core application with just a note pad, the only thing we would need is the .NET Core SDK installed on the machine, and all other actions that we do with Visual Studio all can be invoked using the CLI which we will see how it can be done.


Checking .NET Core Installation

Before creating the .NET Core project, it is obvious thing that we should have .NET Core installed on our machine which can be checked by opening a Command Prompt Window or Powershell window and typing in it the dotnet command, if the .NET Core is not already installed on the machine we will get a error as it will not be able to recognize the command:

Installing .NET Core SDK on Windows

As .NET Core is  all about cross platform, so the SDK is available for different platforms which includes Windows 32-bit and 64-bit, MacOS and Linux, if we go to the official download link we can see multiple options available from which can choose as per our need or convenience.


The following is the list taken from official .NET Core download link :


.NET Core List.PNG


We will be creating the application using Windows so let’s download the sdk installer executable for Windows, i downloaded the Installer of Windows (x64) as on my machine i have 64-bit Windows installed.


.NET SDK x64.png
After downloading the installer, proceed to install the SDK :





This installer will install all the necessary components need to develop .NET Core application and running it which includes .NET Core RunTime, SDK and other things as well. The installation will take 2 - 3 minutes to do the installation, and if all the things go right in installation you will see the following window acknowledging the successful installation :



As we were able to install the SDK successfully, now open the command prompt again and type dontnet command again, i am using powershell for this and executing the command gives you back some output that means .NET Core is being setup correctly:




.NET Core CLI provides different commands to create new project, build, clean and all other commands that we normally invoke using Visual Studio, there is a complete list of commands documented on the official documentation page and all the commands can be seen at this link.

Creating Console Application

Now let’s create the simplest famous Hello World console application using command prompt in .NET Core. If all the previous steps have been completed correctly, open the Command Prompt and create a new directory which will contain the source code for the application.


Write the following command on cmd to create the directory:


mkdir First DotNetCoreApp




Now open the directory using the following command:


cd First DotNetCoreApp




Fromt the above image we can verify that we have opened the correct directory.


Adding Project Template

.NET Core comes with it’s own CLI tools enables to create new project using commands in Command Prompt or Powershell without even opening up the IDE either Visual Studio or VS Code.


We will type dotnet new on command line and press enter which will list down all the templates that can be created using this command.


After running the command, we will see few things listed which includes the different flags which are available to do different things which are also available within Visual Studio but the support is added via Command Line too which is great.




If we go little down, we can see all the templates listed which are available via CLI tools:




Now let’s run the command for creating a new Console Application, so write dotnet new and press enter key and this will create new Console Application project in our working directory:




Our project has been created successfully, but to double check and make sure the command worked fine, we can list the directory content and we should be able to see csproj, Program.cs and other files for the application.




Now let’s run the application by executing the dotnet run command in CMD:




One thing to remember here is that if you are creating the project using .NET Core 1.0 SDK, then before the dotnet run command you would need to execute the dotnet restore command which will restore all the NuGet package dependencies of the project, but for .NET Core 2.0 we don’t need to execute this command as calling the dotnet run makes sure to restore the NuGet package dependencies before running the code.


In actual the restore command was called when we execute the command dotnet new and NuGet packages were restored that time, but it is also called on run as well, which can be verified from this GitHub announcement .

Resources




Implement Equality for Value Types in C#

Udemy

Introduction

This post is to focus on implementing Equality in Value Types i.e. overriding Equality behavior for our own implemented Value Types which is basically defining that how to decide two objects of a type are equal or not. 

Background

As we are now aware of the fact that the technique for checking equality for Value Types and Reference Types is different, so it would be better if we discuss both of them separately, that’s why we will be focusing on each of them in separate posts to have clear understanding on how we can override the Equality for both of these.

This post will particularly focus on the Value Types and for Reference Types we will see in some future post.

Why we need it?

The first question that might come in mind is “Why we should override the Equality for Value Type”, we will see with a simple example and it will help you understand that fact that overriding the Equality behavior for Value Types is always a good idea indeed. We will define a struct later down the road and will implement the Equality of it.

Steps to Implement Equality for Value Type

For overriding the Equality for a Value Type, there are some necessary steps that should be performed which are mentioned below.

We will need to:
  • override the virtual Equals method of Object
  • implement IEquatable<T> interface and provide the implementation of Equals() method of it
  • provide the overloaded implementation for == and != operator method
  • override the GetHashCode method of Object class

Possible Reasons for implementing Equality

So before we start discussing how we can implement Equality for a Value Type, let’s think a little on what are the possible reasons that would make us think that we should define our own Equality behavior for a Value Type instead of using the default one that framework already provides.
So why would you want to override it, the following are the main reasons for that:
  • We want to be able use == operator for comparing the objects of our Value Type. If you remember we discussed previously that == operator does not work for value types and to make it work we need to do some implementation (i.e. overload == operator) in our particular Value Type
  • We have also seen previously that the framework provided implementation uses Reflection for checking the values of each field of that type which is obviously affect the performance as Reflection is slow which results in poor performance of code.
  • We also need sometimes different behavior for comparison of a particular type, though this is not usually required but can be needed in some cases, as the default behavior for Value Types considers two objects to be equal if all of their fields also have the same content which is absolutely fine most of the time.

It is recommended approach to implement Equality for your own defined Value Types that would be used further in your code base. Other developers using your defined Value Type would not get surprised or frustrated when trying to compare two objects of it by using == operator and came to know that they can’t do it.

We can skip overriding the equality for those types that we know we will be using internally in the code base and won’t be exposed to complete code base for usage and we know what we wouldn’t be needing to compare the objects frequently, so implementing equality for those types is not that much needed and would be a waste of time as a result.

Example

We will create an example struct named Employee to illustrate about implementing Equality for a Value Type. This is how our Employee struct looks like now:

    public struct Employee
    {
        public string Name { get; }

        public Gender Gender { get; set; }

        public Department Department { get; set; }

        public Employee(string name, Gender gender, Department department)
        {
            Name = name;
            Gender = gender;
            Department = department;
        }

        public override string ToString()
        {
            return Name;
        }

    }

    public enum Department
    {
        HumanRecource,
        QualityAssurance,
        SoftwareDevelopment,
        ProjectManagement,
        ITOperations
    }

    public enum Gender
    {
        Male,
        Female
    }



We have a very simple Employee type as example which has a String property which will contain the name of employee and one enumeration property to hold the gender of employee and another enumeration for Department which will be used to track the Department of the employee. We will define our own implementation later to dictate that how to decide if two employee instances are equal or not.

There are multiple things that we need to take care and implement in our Employee type for implementing Equality. The first thing that we need to do is override the Object.Equals() method so that instead of default implementation getting invoked which is obviously slow because of Reflection involved, by providing implementation for this method it will enhance the performance of the Type, so overriding Equals method will eliminate the equality check using Reflection and will make it efficient and we will be able to see significant performance improvement.

But wait, Object.Equals() method takes parameter of type Object which means that boxing will happen and we know it also hurts the performance of our code, as boxing and unboxing has its own cost involved, so here we would want to avoid that one as well some way.

For avoiding both Reflection and boxing we will need to implement the IEquatable<Employee> interface for our type Employee. Now we will have efficient implementation of Equals() method in comparison with the framework provided one and another plus point of doing this is that now we have a much better implementation which is also type safe.

We will need to provide the overloaded implementation for == and != operators as it is normally considered a good practice to do all of the following things when overriding Equality:
  • Object.Equals method overriding
  • Implementing IEquatable<T> interface for that type
  • Implementing == and != overloaded methods
  • Object.GetHashCode method overriding
This is important to do because it will make sure that checking for equality for two objects of that type will give the same result, otherwise it can be confusing for the calling code who will be utilizing our type and can cause problems in future.

For Example, if we just implement the overloads for == and != operator and we don’t provide the override for Object.Equals method then what will happen is that the result of Equals method can be different from the result of == operator which will be troublesome for the code that will be utilizing our types.

There is also another method in Object class called GetHashCode, whenever we override the Object.Equals method for a type then another thing that must be done is overriding the GetHashCode method as well.

Step1 - Implementing IEquatable<T> Interface

Now let’s jump in to the Visual Studio and let’s start implementing the IEquatable<Employee> interface for out Person type. We will need to inherit our struct from IEquatable<Employee> and using the code refactoring feature of Visual Studio:

It will add the Equals method without any implementation for the IEquatable<Employee> which would look like:

        public bool Equals(Employee other)
        {
            throw new NotImplementedException();
        }


Now we just need to provide the logic which would be used to identify that the two objects of Employee are equal or not which for this particular example we will do by checking the name and department of the employee is same, or we can also add the Gender if we like as this is just for getting understanding how we can implement it so it doesn’t matter much.

After implementing the Equals method, here is how the method now looks like:


        public bool Equals(Employee other)
        {
            var IsEqual = this.Name == other.Name && this.Department == other.Department;

            return IsEqual;
        }


So the two objects of Employee will be considered Equal if they both contain in Name field and Department field same value. Our one field is of type String which does the value equality for == operator and the other is Enum which is a primitive type in C# so we know that in case of primitive type also == operator checks for value Equality, so the both operations will check for value equality which is what we are trying to do here.

Step 2 - Overriding Object.Equals Method

As we are done with the IEquatable<Employee> part, let’s now override the Equals method so that it also returns the same result that we would get when checking for equality via IEquatable<Employee>, the implementation for which would be:

        public override bool Equals(object obj)
        {
            var IsEqual = false;

            if(obj is Employee)
            {
                IsEqual = Equals((Employee)obj);
            }

            return IsEqual;
        }


What we are doing here is that first we need to make sure that the object that is passed in as parameter is of type Employee which totally makes sense as Object.Equals is not type safe and it is possible to pass an object of type Person instead of Employee and the compiler will not give any compile time error but the code would fail at run-time in that case, but adding that if block would save us from breaking the code at run-time and the method will simply return false which is the correct result as object of type Person and Employee can never be equal.

The thing to note here is that this Object.Equals override will be less efficient than Equals method implementation of IEquatable<T> because the former one has cost of Boxing when it will get called and then we are unboxing it back to Employee which IEquatable<Employee> implementation saves us from these.

What we can do is try to always call using the IEquatable<T> method, if we are concerned about performance and memory cost.

Step 3 - Overloading == and != Operator

Now let’s also implement the == and != operator for Employee which would make sure that checking for Equality using these will return consistent result what we were getting using Object.Equals or IEquatable<Employee> Equals method. So let’s add the implementation for == operator first which is:

        public static bool operator ==(Employee employee,Employee otherEmployee)
        {
            var IsEqual = employee.Equals(otherEmployee);

            return IsEqual;
        }


The method is pretty simple, it is also reusing the Equals method implementation that we did for IEquatable<Employee>, if we build the code it would not build and will give error saying that it hasn’t found the implementation of  != operator, in C# if we overload == operator for a type it is mandatory to provide the implementation for inverse of it i.e. != operator implementation as well, otherwise we will get the following compile time error:

Error CS0216: The operator 'Employee.operator ==(Employee, Employee)' requires a matching operator '!=' to also be defined

 If we have overloaded any one of the operator either == or != we would need to implement the other one as well, so let’s implement the other one as well:

        public static bool operator !=(Employee employee, Employee otherEmployee)
        {
            var IsNotEqual = !employee.Equals(otherEmployee);

            return IsNotEqual;
        }

We can see that it is just inverting the result returned the Equals method of IEquatable<Employee> and passing it back to the caller. Now if we again build our Solution we will be able to build it successfully without any errors.

 Step 4 - Implementing GetHashCode

It is a practice and considered mandatory that if we override the Equals method for a type then we must also provide the overridden implementation for GetHashCode().
If we peek in to the implementation of Object we will see that there is a virtual method present in it named GetHashCode, its purpose is to return the 32-bit hash of the value which is contained in the object itself.



you might be wondering what is the purpose of this code, the GetHashCode method is used by types that internally use HashTables to store the objects which are normally Collections so they consume this method and get the hash value of the object to be used in the hash table as HashTables utilize the hash codes of the objects. In Framework Class Libraries the Dictionary<TKey,TValue> also uses HashTable internally.
Hash Codes is a complete topic on which a full article can be written to cover its aspects and we will not not be focusing in details on it. How Hash Tables work is that if two objects return true when called Equals method on them, then the Hash Codes for both objects should also be returned same when we call GetHashCode method on both which in our case would mean that the following line should return true as well.
So what it actually means is that If employee.Equals(OtherEmployee) results in true then employee.GetHashCode() == otherEmployee.GetHasCode() should also return true as result. If the GetHashCode method is not implemented how it is required then the using Dictionary on our type wouldn’t work properly and can cause problems.

Now let’s add the implementation for our Employee type GetHashCode method which would be:
        public override int GetHashCode()
        {
            return Name.GetHashCode() ^ Department.GetHashCode();
        }


So it is quite simple to understand that what we are doing above, we are just taking the HashCode for our String field Name and Department Enumeration and combining them using XOR as both the framework provided types so there is already implementation presentation for generating the Hash Code for these types, so we are just reusing the Hash Codes that are already available and provided by framework.

Now let’s add some code in the Main method to verify what we have implemented is working as expected, add the following code in the Main and run it:


        static void Main(string[] args)
        {


            Employee ehsan = new Employee("Ehsan Sajjad", Gender.Male, Department.SoftwareDevelopment);
            Employee ehsan2 = new Employee("Ehsan Sajjad", Gender.Female, Department.SoftwareDevelopment);

            Employee bilal = new Employee("Bilal Asghar", Gender.Male, Department.QualityAssurance);

            object ehsanObj = ehsan;

            Console.WriteLine(ehsan.Equals(ehsan2));
            Console.WriteLine(ehsanObj.Equals(ehsan2));
            Console.WriteLine(ehsan == ehsan2);

            Console.WriteLine(ehsan.Equals(bilal));
            Console.WriteLine(ehsanObj.Equals(bilal));
            Console.WriteLine(ehsan == bilal);

            Console.ReadKey();

      }


The following is the result which was printed on the Console:


We can observe the for ehsan and ehsan2 objects all the three conditions have evaluated to return true which of course means that both are equal which was expected as this is how we defined to check for equality in our type, though we defined Gender field different in both objects but it has evaluated that both are equal as we are not considering Gender field when deciding that if two are equal or not.

Summary

Following are the points that we learned in this post:
  • We learned how to provide Custom implementation for Equality checking of Value Types
  • Implementing Equality for Value Types is normally good to do as it would improve performance by eliminating boxing/unboxing and reflection cost which can make our code inefficient.
  • There are multiple things to take care of when overriding equality for Value Types which includes:
    • Implementing IEquatable<T> interface of that Value Type which will have type safe Equals method for checking two object of a type T
    • Overriding the Object.Equals method which in turn calls the Equals method which we implemented for IEquatable<T>
    • Implementing the == and != operator overloads which also call the Equals method on IEquatable<T>
    • Implementing GetHashCode of Object for our value type T
  • This is the recommended approach for implementing Equality for Value Types and this is not recommended way in case of Reference Types.