Friday, March 1, 2024

C# : Merge two sorted array

 int [] first=new int[]{1,3,5,9,11,15};

int [] second=new int[]{2,4,6,8};  

int n1=first.Length, n2=second.Length;
int [] third =new int[n1+n2];
Console.WriteLine($" n1={n1} and n2={n2}");
int i=0,j=0,k=0;

// Logic
// ==>i=0;j=0 =>1
// i=1,j=0 =>2
// i=1,j=1=>4
// i=1, j=2 => 5
// i=2, j=2 ==>6
// i=2, j=3 ==>8
// i=2,j=4 ==> exit lpoop ==>

while(i<n1 &&j<n2){  
    Console.WriteLine($" i={i} , j={j}, k={k}");
    if(first[i]>second[j]){
        third[k++]=second[j++];      
    }
    else{
        third[k++]=first[i++];        
    }    
}
while(i<n1){
    third[k++]=first[i++];
}
while(j<n2){
    third[k++]=second[j++];
}
foreach (var item in third)
{
    Console.WriteLine(item +"--");
}

Friday, July 2, 2021

Difference between object and dynamic in c# | Object Vs Dynamic

As we know that object is a base class for the the types in c# i.e. object is a class and all the classes in .net framework derived from object. we can assign any value (either ValueType or ReferenceType) to object, similarly we can assign any value to the dynamic. but there are few difference in dynamic and object 
  • dynamic is not a type it's just a keyword which tells compiler to ignore compile time type checking and infer dynamic declared variable's type at runtime.
  • when you assign a value to dynamic variable and then you assign this variable's value to another variable who's type is similar to assigned value's type you don't need type casting (see the example below) but in case of object you need to type caste object variable to particular type otherwise you will get compile time error.
      public static void ObjectVsDynamic()
        {
            dynamic a = "hello";
            string str = a; // no casting
          
            Console.WriteLine(str);

            object b = "hello";
            string str1 = (string)b;// in case of object explicit casting required.
            Console.WriteLine(str1);
            Console.ReadLine();
        }

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


A 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");
            }

        }


Friday, July 26, 2019

WPF : How To Set Focus on another window (MVVM)


 How To Set Focus on another window (MVVM)?

I have two window (Parent-Child). Parent window opens Child window so child window is focused
(i.e. top most window) but when child replies to Parent, Parent window is not focused (i.e. it's not on top).

I have created a attached property in a separate class like:

class FocusAttched:DependencyObject
    {
        public static DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusAttched),
                new UIPropertyMetadata(false, OnIsFocusedChanged));
        public static bool GetIsFocused(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(IsFocusedProperty);
        }
        public static void SetIsFocused(DependencyObject dependencyObject, bool value)
        {
            dependencyObject.SetValue(IsFocusedProperty, value);
        }
        public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            ((FrameworkElement)dependencyObject).Focus(); //My Code-Niranjan
           
            // Removing hard coding
            //TextBox textBox = dependencyObject as TextBox;
            //bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
            //bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
            //if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
        }
    }

Now Attached this property to Parent window control (textbox)

                      VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" AcceptsReturn="True" HorizontalAlignment="Left"
                 Height="248" Margin="191,36,0,0"   VerticalAlignment="Top" Width="249"/>


I am binding this attached property with a new property in View Model, for this reason I am creating a new bool property in View model.

bool _setFoucs;
        public bool SetFocus {
            get { return _setFoucs; }
            set { _setFoucs = value; OnPropertyChanged(nameof(SetFocus)); }
        }

I will set this property in Callback method.

Summery : Idea is that when Child window sends a message to Parent window, callback method will get called by Child, in this Callback I am setting this 'SetFocus' Property which is attached to TextBox of Parent window, OnPropertyChnage callback of Attached/Dependency property I am calling Focus() method of FrameworkElement( TextBox is Framework element).

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 ...