Check email count on mailbox with C#

Below is an example of .Net core 3.1 Console App that is reading a mailbox on Exchange and checking the count of mails. If the mail count cross a certain threshold, it’ll check for an e-mail older than 2 hours to send an alert.

Such an example can be used to schedule alerts or log information if you’re tracking mails in a mailbox.

Install Nuget package Microsoft.Exchange.WebServices to use ExchangeService class.

using Microsoft.Exchange.WebServices.Data;

public static void Main(string[] args)
{
	string TextlogMessage;
	string Subject = "";
	string sUsername = ConfigurationManager.AppSettings.Get("UserName");
	var section = ConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
	string vCount = ConfigurationManager.AppSettings.Get("Count");
	int Count = Convert.ToInt32(vCount);
	string sPassword = ConfigurationManager.AppSettings.Get("Password");
	
	string sDomain = ConfigurationManager.AppSettings.Get("Domain");
	TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
	DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
	DateTime comparedate = indianTime.AddHours(-2);
	DateTime MailDateTime = comparedate;
	ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
	exchange.Credentials = new WebCredentials(sUsername, sPassword, sDomain);
	
	exchange.Url = new Uri(ConfigurationManager.AppSettings.Get("ExchangeUrl"));
	Folder inbox = Folder.Bind(exchange, WellKnownFolderName.Inbox);
	var oSendemail = 0;
	TextlogMessage = "Start With count:" + inbox.TotalCount;




	if (inbox.TotalCount > Count)
	{

		Console.WriteLine("Count " + inbox.TotalCount);

		ItemView view = new ItemView(1);

		view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
		
		var findResults = exchange.FindItems(WellKnownFolderName.Inbox, view);


		foreach (Item item in findResults.Items)
		{

			Console.WriteLine("Test: " + item.DateTimeReceived + " %" + comparedate);
			DateTime newdate = TimeZoneInfo.ConvertTimeToUtc(item.DateTimeReceived);

			int Dresult = DateTime.Compare(newdate, comparedate);
			if (Dresult < 0)
			{
				Console.WriteLine("Alert " + "Sub" + item.Subject + newdate + " %" + comparedate);
				oSendemail = 1;
				MailDateTime = newdate;
				Subject = item.Subject;


			}

		}
		if (oSendemail > 0)
		{
			Program p = new Program();
			//To Do Send Email Logic..
			p.SendEmail(exchange, oSendemail, inbox.TotalCount, TextlogMessage);
			TextlogMessage = TextlogMessage + " EmailTime: " + MailDateTime + "CompareTime " + comparedate + "  Alert Sent Subject : " + Subject;

		}

	}

	//To Do logging..
	log(TextlogMessage);

}

Call .Net core API from Console with App Bearer token

In the following example, we’re using a .Net Core 3.1 Console App that will call API with POST request that requires Authentication with a bearer token in Authrorization Header. The token is generated by passing credentials to another API endpoint.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace ConsoleApp1
{

    class Credentials
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    class Token
    {
        public string token { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string ResponseString = "";
            HttpWebResponse response = null;
            HttpWebResponse response2 = null;
            IConfiguration Config = new ConfigurationBuilder()
                .AddJsonFile("appSettings.json")
                .Build();

            try
            {
                var baseURL = Config.GetSection("baseURL").Value;
                var request = (HttpWebRequest)WebRequest.Create(baseURL + "/token");
                request.Accept = "application/json"; //"application/xml";
                request.Method = "POST";

		//Get credentials from config.
                var dusername = EncryptionService.Decrypt(Config.GetSection("credentials")["username"]);
                var dpassword = EncryptionService.Decrypt(Config.GetSection("credentials")["password"]);

                Credentials cred = new Credentials()
                {
                    username = dusername,
                    password = dpassword
                };

                var myContent = JsonConvert.SerializeObject(cred);

                var data = Encoding.ASCII.GetBytes(myContent);

                request.ContentType = "application/json";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                }

		//Get the token from the /token end-point and call another end-point.
                Token token = JsonConvert.DeserializeObject<Token>(ResponseString);

                var request2 = (HttpWebRequest)WebRequest.Create(baseURL + "/ProcessData");
                request2.Accept = "application/json"; //"application/xml";
                request2.Method = "POST";
				
		//Pass token in Authorization Header.
                request2.Headers["Authorization"] = "Bearer " + token.token;

                using (response2 = (HttpWebResponse)request2.GetResponse())
                {
                    ResponseString = new StreamReader(response2.GetResponseStream()).ReadToEnd();
                }

                Console.WriteLine(ResponseString);
                Environment.Exit(0);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)ex.Response;
                    ResponseString = "Some error occured: " + response.StatusCode.ToString();
                }
                else
                {
                    ResponseString = "Some error occured: " + ex.Status.ToString();
                }
            }

        }
    }

}

Dependency Injection example C#

Dependency Injection is decoupling the usage of an object from it’s creation. An abstraction is created between a higher level class and it’s dependencies.

In the below example, the Notification service (lower level module) is abstracted from the higher level class User.

Create Interface as below:

public interface INotification
{
    void SendNotification(User user);
}

Create a class that implements the above interface:

public class ConsoleNotification: INotification
{   
    public void SendNotification(User user)
    {
        Console.WriteLine($"Changed name to: {user.username}");
    }
}

There can be other classes like EmailNotification that implements this interface.

Now, create a class called User that would require to send notification to a user:

public class User
{
    public string username { get; private set; }
    INotification _notify;

    public User(string name, INotification notify)
    {
        username = name;
        _notify = notify;
    }

    public void changeName(string name)
    {
        username = name;
        _notify.SendNotification(this);
    }
}

In the above code, if the User class was itself creating the ConsoleNotification object, that would have been tight coupling between the 2 classes. So, if we wanted to change the Notification service to EmailNotification, we would have to change the User class directly.

The client which in our case is the Program.cs code, will pass the ConsoleNotification object to the user object in the Constructor which is called Constructor injection.

class Program
{
    static void Main(string[] args)
    {
        var notify = new ConsoleNotification();

        //Passing ConsoleNotification type, could be any other type implementing INotification..
        var user1 = new User("Tim", notify);

        Console.WriteLine($"User Name: {user1.username}");
        user1.changeName("Jim");
        Console.ReadKey();
    }
}

Output:

User Name: Tim
Changed name to: Jim

So, the User class is not directly creating a dependency on a particular type of notification Service. Rather the client is telling at run-time what instance of notification service the User class should use which is also called inversion of control (IoC). We’re creating the object of the dependency first and then injecting it into the higher level object.

Facade Pattern C#

This is a structural design pattern that only exposes a simplified interface to the outside world while hiding the complex subsystems. The facade keeps the unwanted dependencies to one place. Its own behaviour takes care of the internal complexities of the subsystems.

A car acts like a facade to the outside world which exposes it’s own behaviour like on, accelerate, brake, off etc. But you are not aware of how it all works internally.

Let’s take a small example of an online Shopping cart where you add an item to a cart which is the only behaviour exposed for the Client. Once you add the item to the cart, a few things happen internally which are not directly controlled by the user action like checking availability of item, calculation of tax, locking the item for availability and calculating the cost etc.

Create a Console Application which is the Client in this example that will only add the Item to cart. Also, add a class library Shopping that will do all of the above described operations but only expose the Cart to the Client.

public interface IShoppingCart
    {
        bool addItemToCart(int itemid, int qty);
    }

internal interface IStock
    {
        bool checkStockItemsByID(int itemID);
        bool lockItemsTemp(int itemID, int qty);
    }

internal interface IItemCost
    {
        string getItemCostByID(int itemid);
    }

internal interface ITaxes
    {
        string getStateTax(string statecode);
    }

Now, implement the above behaviours while keeping only the ShoppingCart class public:

internal class Stock : IStock
    {
        public bool checkStockItemsByID(int itemID)
        {
            Console.WriteLine($"Item Id: {itemID} is available");
            return true;
        }

        public bool lockItemsTemp(int itemID, int qty)
        {
            Console.WriteLine($"Item Id: {itemID}, quantity: {qty} is locked");
            return true;
        }
    }


internal class ItemCost : IItemCost
    {
        public string getItemCostByID(int itemid)
        {
            Console.WriteLine($"Item Id: {itemid} cost is $25");
            return "25";
        }
    }


internal class Taxes : ITaxes
    {
        public string getStateTax(string statecode)
        {
            Console.WriteLine($"{statecode} state tax is 3.5%");
            return string.Empty;
        }
    }

//Exposed class
public class ShoppingCart : IShoppingCart
    {
        public bool addItemToCart(int itemid, int qty)
        {
            IStock stock = new Stock();
            stock.checkStockItemsByID(itemid);
            stock.lockItemsTemp(itemid, qty);

            IItemCost itemCost = new ItemCost();
            itemCost.getItemCostByID(itemid);

            ITaxes taxes = new Taxes();
            taxes.getStateTax("NY");

            return true;
        }
    }

The console Application only performs the action to add the Item to the cart:

class Program
    {
        static void Main(string[] args)
        {
            IShoppingCart item = new ShoppingCart();
            item.addItemToCart(123, 2);
            Console.ReadKey();
        }
    }


Output:
Item Id: 123 is available
Item Id: 123, quantity: 2 is locked
Item Id: 123 cost is $25
NY state tax is 3.5%

Singleton pattern C#

A Singleton class in OOP allows only one instance of itself to be created. While a conventional class can have any number of instances created. Below is the thread-safe implementation of Singleton class.

using System;
namespace SingletonPattern
{
    // thread-safe way.
    public sealed class Singleton
    {
        private static Singleton obj = null;
        // mutex lock used for thread-safety.
        private static readonly object mutex = new object();
        private int var = 0;

        private Singleton()
        {
        }

        public static Singleton getObj
        {
            get
            {
                lock (mutex)
                {
                    //lazy loading..
                    if (obj == null)
                    {
                        obj = new Singleton();
                    }
                    return obj;
                }
            }
        }

        public void doSomething()
        {
            var += 1;
            Console.WriteLine($"Current Value: {var}");
        }
    }
}

Now, when we call the Singleton class object using getObj from anywhere, it’ll return the same instance of obj.

using System;

namespace SingletonPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton instance = Singleton.getObj;
            instance.doSomething();
            instance.doSomething();
        }
    }
}

Output:

Current Value: 1
Current Value: 2

An example of a Singleton class can be a Database which returns only 1 instance of itself from wherever we connect to it.

How is it different from a Static class?

  1. A Singleton class can inherit other classes and can also implement interfaces.
  2. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded.

Abstract Factory pattern C#

Let’s begin with a story of 2 brothers Bill and Steve. Both love Pizza and Ice Cream. They go to a Food Court which has Pizza outlets like Pizza Hut and Dominos Pizza and Ice Cream Parlours like Baskin Robbins and Mikey.

Taking this real world pattern into our Software design by creating classes. In this context, Food Court will be our FoodFactory abstract class that creates 2 abstract Products Pizza and Ice Cream. The Food Court has 2 sections Fun and Frolic. Bill goes for Fun and Steve goes to Frolic.

public abstract class FoodFactory
{
    public abstract Pizza BakePizza();
    public abstract IceCream MakeIceCream();
}

Create an Abstract Products folder and add the following 2 classes:

public class Pizza {

}

public class IceCream {

}

Create a Products Folder and add the following classes:

public class DominosPizza: Pizza
{
    public DominosPizza()
    {
    }
}
public class PizzaHut: Pizza
{
    public PizzaHut()
    {
    }
}
public class Mikey: IceCream
{
    public Mikey()
    {
    }
}
public class BaskinRobbins: IceCream
{
    public BaskinRobbins()
    {
    }
}

Now, suppose Fun section has Pizza Hut and Mikey and Frolic has Dominos Pizza and Baskin Robbins. Create a folder Factories and under that add the following classes:

class FunFoodFactory : FoodFactory
{
    public override Pizza BakePizza()
    {
        return new PizzaHut();
    }

    public override IceCream MakeIceCream()
    {
        return new Mikey();
    }
}
public class FrolicFoodFactory : FoodFactory
{
    public override Pizza BakePizza()
    {
        return new DominosPizza();
    }

    public override IceCream MakeIceCream()
    {
        return new BaskinRobbins();
    }
}

Now the 2 Good brothers start having fun. Create a class called GoodBrothers as below:

public class GoodBrothers
{
    private readonly Pizza _pizza;
    private readonly IceCream _icecream;

    public GoodBrothers(FoodFactory factory)
    {
        _pizza = factory.BakePizza();
        _icecream = factory.MakeIceCream();
    }

    public string WhatDidYouHaveToday()
    {
        return $"Today I ate at {_pizza.GetType().Name} and {_icecream.GetType().Name}";
    }
}

From the main class we ask them What did you have today?

class Program
{
    static void Main(string[] args)
    {
        GoodBrothers Bill = new GoodBrothers(new FunFoodFactory());
        Console.WriteLine($"Bill: {Bill.WhatDidYouHaveToday()}");

        GoodBrothers Steve = new GoodBrothers(new FrolicFoodFactory());
        Console.WriteLine($"Steve: {Steve.WhatDidYouHaveToday()}");

        Console.ReadKey();
    }
}

Output:

Bill: Today I ate at PizzaHut and Mikey
Steve: Today I ate at DominosPizza and BaskinRobbins

A similar example for Abstract Factory pattern can be for a Clothes Factory abstract class which creates abstract Products like Shirts and Trousers. A Businessman may buy from ElegantFactory and a student may buy from CasualFactory. Shirts can be of types Formal and PoloTs and Trousers can be of type Suit and Jeans.

The ElegantFactory will return types Formal Shirt and Suit Trousers. CasualFactory will return types PoloTs and Jeans. We can create a Client class like GoodBrothers that receives the ClothesFactory reference in it’s constructor to create a Shirt and Trouser for the Businessman and Student and so on.

Factory Pattern C#

Factory Design Pattern falls under the category of creational design pattern. It deals with the problem of creating objects without specifying the exact class of object that will be created. It is abstracting the process of object generation which is determined at run-time.

The behavior of a PizzaFactory class is to Bake a Pizza. So, the PizzaFactory class will create the object based on the choice provided by the customer of whether it is a Dominos Pizza or Pizza Hut.

interface IBake
{
    void Pizza();
}

public class DominosPizza: IBake
{
    public void Pizza()
    {
        Console.WriteLine("Dominos Pizza is Served!");
    }
}


public class PizzaHut: IBake
{
    public void Pizza()
    {
        Console.WriteLine("Pizza Hut is Served!");
    }
}

//The type of object created is determined at run-time.
class PizzaFactory
{
    public static IBake makePizza(int choice)
    {
        IBake objPizza = null;

        switch (choice)
        {
            case 1:
                objPizza = new DominosPizza();
                break;
            case 2:
                objPizza = new PizzaHut();
                break;
            default:
                objPizza = new DominosPizza();
                break;
        }
        return objPizza;
    }
}

Now suppose your Client is a Console Application in this case. The code will be as below:

class Program
{
    static void Main(string[] args)
    {
        IBake objPizza = null;
        Console.WriteLine("Enter your choice of Pizza!");
        int choice = Convert.ToInt32(Console.ReadLine());

        objPizza = PizzaFactory.makePizza(choice);
        objPizza.Pizza();
    }
}

Binary Search with C#

It is a divide and conquer approach to search an element in the Array. At each step, the search space is reduced to half.

The first part of the program is a recursive approach to write the Binary Search algorithm. The second approach focuses on the iterative model. The code will spit out the index of the element if found.

public class BinarySearch
    {
        //space complexity: O(log2 (n)).
        public int? fnRecursiveBinarySearch(int[] Arr, int k, int low, int high)
        {
            int mid = 0;
            if (low > high)
            {
                return null;
            }
            else
            {
                mid = (high + low) / 2;
                if (k==Arr[mid])
                {
                    return mid;
 //return position of found.
                }
                else if (k < Arr[mid])
                {
                    return fnRecursiveBinarySearch(Arr, k, low, mid - 1);
 //search in first half.
                }
                else
                {
                    return fnRecursiveBinarySearch(Arr, k, mid + 1, high);
 //search in second half.
                }
            }
        }

        //space complexity: O(n)
        public int? fnIterativeBinarySearch(int[] Arr, int k, int low, int high)
        {
            int mid = 0;
            do
            {
                mid = (low + high) / 2;
                if(k==Arr[mid]) { return mid; //return position of found. }
                else if(k<Arr[mid]) {
                    high = mid - 1;
 //search in first half.
                }
                else
                {
                    low = mid + 1;
 //search in second half.
                }
            } while (low <= high);
            return null;
        }

    }

To test the above 2 approaches, we use a simple call to both the functions:

class Program
    {
        static void Main(string[] args)
        {
            BinarySearch bs = new BinarySearch();
            int[] Arr = { 5, 6, 3, 1, 8, 10 };

            Console.WriteLine("Recursively Found element at index: {0}", bs.fnRecursiveBinarySearch(Arr, 8, 0, Arr.Length - 1));
            Console.WriteLine("Iteratively Found element at index: {0}", bs.fnIterativeBinarySearch(Arr, 8, 0, Arr.Length - 1));
        }
    }

Time complexity is log2 (n), for both approaches. For the space complexity,
Recursive may reach to log2 (n) space because of the stack, but in the iterative approach, it should be O(1) space complexity.

Write C# method that returns DataSet from Stored Procedure

Suppose you are writing a Helper class in your .Net Project that uses ADO.Net in the Data Layer. And you need to call Stored Procedures a lot. Writing a generic Helper method that takes in an Array of SqlParameters can be used so that you don’t have re-write the same code of calling the Stored Procedure again and again.

Below is the code that I’ve used as a general approach to call Stored Procedure and return DataSet:

public static DataSet ExecuteProcedureReturnDataSet(string connString, string procName,
            params SqlParameter[] paramters)
{
	DataSet result = null;
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			using (SqlDataAdapter sda = new SqlDataAdapter(command))
			{
				command.CommandType = System.Data.CommandType.StoredProcedure;
				command.CommandText = procName;
				if (paramters != null)
				{
					command.Parameters.AddRange(paramters);
				}
				result = new DataSet();
				sda.Fill(result);
			}
		}
	}
	return result;
}

Another way to call Stored Procedure would be to return a single value from the Stored Procedure like a string. You can use the below method to return only a String:

public static string ExecuteProcedureReturnString(string connString, string procName,
            params SqlParameter[] paramters)
{
	string result = "";
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			command.CommandType = System.Data.CommandType.StoredProcedure;
			command.CommandText = procName;
			if (paramters != null)
			{
				command.Parameters.AddRange(paramters);
			}
			sqlConnection.Open();
			var ret = command.ExecuteScalar();
			if (ret != null)
				result = Convert.ToString(ret);
		}
	}
	return result;
}

Example of SqlParameter array to be passed to the above methods can be as follows:

SqlParameter[] params =
{
	new SqlParameter("@name", name),
	new SqlParameter("@year", year)
};