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

        }


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

Thursday, July 25, 2019

WPF - Difference between ContentControl and ContentPresenter?



Difference between ContentControl and ContentPresenter?


ContentPresenter is a lightweight element. It's derived from FrameworkElements class. So, It has no Template property (i.e.) we can't set control Template for it, while we can set data template for it as it has Content property.

ContentPresenter has a addition property 'ContentSource' which is not present in Content Control.

Default value of 'ContentSource' property is content, So when we will put ContentPresenter inside of ControlTemplate we don't need to define binding explicitly.

ContentControl also uses ContentPrenseter in it's template to display data.

WPF - How to print Parent hierarchy of an element?



How to print Parent hierarchy of an element?

            DependencyObject _parent = myGrid.Parent;
            while (_parent != null)
            {
                System.Diagnostics.Debug.WriteLine(_parent);
                _parent = ((FrameworkElement)_parent)?.Parent;
            }

Every framework element has a Parent property, we can loop through like above code and print parent of particular element.

Tuesday, July 2, 2019

WCF : How to transfer large data via wcf service?


How to transfer large data from wcf service?

To transfer large data from wcf service, we need to change some configuration settings like:

MaxReceivedMessageSize
Transfer Mode
Max Depth (in ReaderQuotas)
MaxArrayLength

Above are necessary settings to transfer large data form WCF, apart from these settings, to increase performance you can change message encoding to "MTOM".

Complete binding configuration is :
 

    

Note : you need these settings in both Service and application config file (web.config and app.config).






Monday, June 24, 2019

Difference between Interface and Delegate in c#


Interface is a contract, a method declared inside of interface, class which implementing that Interface should provide definition for declared method inside interface.

In case of delegate, if a class (let's say A) method needs callback function as a parameter or exposing a delegate (same like event) to subscribe. you need to implement callback method with same signature as delegate to subscribe delegate/callback.

In both cases (in case of interface and in case of delegate) you need to define a method with declared signature by interface/delegate so, in case of single method interface seems there is no difference between interface and delegate.

let's dig in detail,

  • for an interface method implementation, it's necessary to declare it public.
  • if interface has more than one method, implementer of interface need to define all the methods of interface.
  • we can subscribe a private method, or anonymous method to delegate, which is not possible in case of interface.
  • In case of interface, we need to define method same as method declared in interface (same name) but in case of delegate we can assign any method whose signature is same as delegate signature.
  • delegate provide multicast functionality, we can subscribe multiple methods to delegate but not to interface.
* Please let me know your comments...

Tuesday, June 4, 2019

WPF : C# Async methods



Below example shows how to create and use async methods in WPF application.
In below example, There are two ways to create void returning async method as well string returning
Async method.

you can copy and paste relevance code in any new WPF application and check it's functionality(mainly responsiveness). I tried to create long running operations and application responsiveness during long running operation.



.CS File

 public partial class AsyncWithWPF : Window
    {

        string strGlobalVariable = "";
        public AsyncWithWPF()
        {
            InitializeComponent();
        }
     
        private async void BtnAsyncReturnVoid1_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            await LongRunningTaskReturnvoid1();
            lblResult.Content += "Finished LongRunningTaskReturnvoid1() " + strGlobalVariable;
        }
        public Task LongRunningTaskReturnvoid1()
        {
            lblResult.Content += "   inside LongRunningTaskReturnvoid1() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                strGlobalVariable += " Async Task has finished ";
            });
        }
        private  void BtnAsyncReturnVoid2_Click(object sender, RoutedEventArgs e)
        {
         
                lblResult.Content = "";
                lblResult.Content += " Starting..  ";
                LongRunningTaskReturnvoid2();
           
            lblResult.Content += "after LongRunningTaskReturnvoid2() call";
        }
        public async void LongRunningTaskReturnvoid2()
        {
         
                await Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
             

            });
                lblResult.Content += "  finished LongRunningTaskReturnvoid2()";
           
        }
        private async void BtnAsyncReturn1_Click(object sender, RoutedEventArgs e)
         {
            string result = "";
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            try
            {
                result = await LongRunningTask();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Handled");
            }
            lblResult.Content += result +" Finished LongRunningTaskvoid()";
         
        }
        public Task LongRunningTask()
        {
            lblResult.Content += "   inside LongRunningTask() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000); //throw new Exception("test");// uncomment to check exception handling.
                return "Hello";
            });

        }
     
        private void BtnTestResponsiveness_Click(object sender, RoutedEventArgs e)
        {
              MessageBox.Show("Hello");
        }
   

    }

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