Tuesday, June 2, 2020

ASP.NET Core 3.0 (C# ) : Send email via outlook host

Below code shows how to send email via outlook host using SMTP client in C#

     public interface IOutlookMailClient
    {
        void SendMail(string recipient, string subject, string message);
    }

public class OutlookMailClient : IOutlookMailClient
    {
        private readonly string sender;
        private readonly string password;
        private readonly string host;
        private readonly int port;
        private readonly OutlookMailServiceOptions emailOptions;
        private readonly ILogger<OutlookMailClient> logger;
       
public OutlookMailClient(IOptions<OutlookMailServiceOptions>                   mailOptions,ILogger<OutlookMailClient> logger)
        {
            this.emailOptions = mailOptions.Value; ;
            this.password = emailOptions.Password;
            this.host = emailOptions.Host;
            this.port = emailOptions.Port;
            this.sender = emailOptions.Sender;
            this.logger = logger;
        }
        public void SendMail(string recipient, string subject, string message)
        {
            logger.LogInformation("Enter : OutlookMailClient.SendMail");
            logger.LogInformation("Mail recipient :" +recipient +" Subject : "+subject);
            SmtpClient client = new SmtpClient(host);//new SmtpClient("outlook.office365.com");
            client.Port = port;
            //client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            System.Net.NetworkCredential credentials =
            new System.Net.NetworkCredential(sender, password);
            client.EnableSsl = true;
            client.Credentials = credentials;
            try
            {
                var mail = new MailMessage(sender.Trim(), recipient.Trim());
                mail.Subject = subject;
                mail.Body = message;
                client.Send(mail);
                logger.LogInformation("Exit : OutlookMailClient.SendMail");
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw ex;
            }
        }
    }
}

IOptions<OutlookMailServiceOptions> is a asp.net core feature to read data from appsetting.json using a model. here OutlookMailServiceOptions is a POCO class used to keep mail settings from Json config file. you can use any alternative if you are not using asp.net core.

 public class OutlookMailServiceOptions
    {   
            public string Sender { get; set; }
            public string Host { get; set; }
            public int Port { get; set; }
            public string Password { get; set; }
    
    }
put this configuration in appsetting.json

"OutlookMailServiceOptions": {
    "Sender": "sender mail id",
    "Host": "outlook.office365.com",
    "Port": 587,
    "Password": "your password"
  }

Now you have to call this api in your code, to call first you need to inject this api via dependency injection in ConfigureService method of Startup.cs like :

 services.Configure<OutlookMailServiceOptions>(Configuration.GetSection(nameof(OutlookMailServiceOptions))).AddSingleton(x => x.GetRequiredService<IOptions<OutlookMailServiceOptions>>().Value);

            services.AddScoped<IOutlookMailClient, OutlookMailClient>();

Now, you can inject this API in your Controller via constructor :

private readonly IOutlookMailClient emailClient
DefaultController (IOutlookMailClient emailClient) //Constructor
{
this.emailClient=emailClient;
}
 
//mail api injected , now simply call sendMail() method from any method like:

  emailClient.SendMail("To mail address", "Subject", "Body");

All the other required details (Sender, Host, Port, etc.) to send mail, API will read from AppSetting.Json via IOption mechanism.

Friday, February 21, 2020

Multi Threading in C# : Returning a value from thread via shared variable.


Objective : We want to perform a long running operation in a separate thread and want result back from that thread.To achieve this we can use a shared/global variable,  thread will perform desired operation and then update global variable. please see below example for more clarity:

Note : variable and method used in below program is static, because we want to call them inside Main() which is static method.

 public class Program
  {
      static int resultFromThread = 0;
      #region Returing value from Thread

      public static void Main()
      {
          // if we want to call method with multiple paramter, we can use lambda expression to pass params to thread, like:

          Thread child = new Thread(() => Add(5, 4));
          child.Start();
          
          // some dummy operation performed by main
          for (int i = 0; i < 10; i++)
          {
              Thread.Sleep(100);
              Console.WriteLine("Some opeation performed by Main, side by side Child is doing it's own opeartion");
          }

          child.Join(); // Main will wait until child thread finished.
          Console.WriteLine("Child Thread has finished it's operation, now we can check resultFromThread");
          Console.WriteLine("value of resultFromThread "+ resultFromThread);
          Console.Read();

      }
      public static void Add(int a, int b)
      {
          Thread.Sleep(3000); //pausing thread for 3 sec.and then updating global variable resultFromThread.
          resultFromThread= a + b;
      }
      #endregion
  }

Multi Threading in C# (using Thread class)


MultiThreading in C# : Now a days multiple ways we have to create thread in C#, Thread class is present in
C# from inception.Thread class takes a ThreadStart/ParameterisedThreadStart delegate, or simply we can pass a parameterised or non parameterised method which returns void.
In case of parameterised method we can pass a single parameter of type Object.
Please see the below example for more clarity:

public class Program
    {
        static void Main(string[] args)
        {
            // calling non-parameterised method in Thread class 
            Thread child = new Thread(ThreadOperation);
            child.Start();

            // calling parameterised method in Thread class 
            Thread paramterisedChild = new Thread(ThreadParamterisedObject);
            paramterisedChild.Start("Niranjan"); //--- Any object we can pass to thread---//

            // additional work done by main thread
            for(int i=0;i<10 font="" i="">
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Main Thread " + i);
            }
            Console.WriteLine(" Good bye from Main");
            Console.ReadLine();
        }
        //---This method will be called by child thread---.
        public static void ThreadOperation()
        {
            for (int i = 0; i < 10; i++){
                
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Child Thread " + i);
            }
        }
        //---This method need one paramter of type object---.
        public static void ThreadParamterisedObject(object obj)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500); //pausing thread for 500 milisecond.
                Console.WriteLine(" Child Thread " + obj.ToString());
            }
        }
    }



Sunday, January 12, 2020

C# Palindrome Program


palindrome is a word, phrase, number or sequence of words that reads the same backward as forward. For Example Madam, Nitin, RAGGAR etc.
below is a C# program which checks given string is palindrome or not:

program logic : suppose we have a string of length 5, we will check first char of string is equal to last char of string, second char of string is equal to second last char of string and so on. like
char[0]==char[4]
char[1]==char[3]
char[2]==char[2]
if all matched then string is palindrome.

        public static void IsPalindrome(string s)
        {
          
            char[] cArr = s.ToCharArray(); // Converting string to char array
            bool isPalindrome = true; //a flag 
            
            for (int i = 0; i < s.Length / 2; i++)
            {
               // Console.WriteLine("Iteration i=" + i);// to get iteration count

                if (cArr[i] != cArr[(s.Length - 1 - i)])
                {
                    isPalindrome = false;
                    Console.WriteLine("Not Palindrome");
                    break;
                }
                
            }
            if (isPalindrome)
            {
                Console.WriteLine("Palindrome");
            }

        }


C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...