Wednesday, 2 September 2015

How to use ContinueWith method in Task using C#

// What ever we will get from task , its going to cal task value in task1 and process the final result.

 var task = Task<int>.Run(() => {
                 return  Enumerable.Range(1, 1000).Count(n => n / 2 == 2);
           });
            task.ContinueWith((task1) =>
            {
                if (task1.Result < 10)
                {
                 
                    Console.WriteLine(task1.Result);
                }
                else
                {
                    if (task1.IsFaulted == true) // Is IsFaulted used to check Exception in Task
                    {
                       foreach(var d in task1.Exception.Flatten().InnerExceptions)
                       {
                           Console.WriteLine(d.Message);
                       }
                   
                    }
                    else
                    {
                        Console.WriteLine(task1.Result);
                    }
                   
                }
            }).Wait(); // Wait going to wait finished his work and comeback with final result.
                              suppose if am not going to put wait here , that task is not going wait finished his work and he move to next line , with out giving output. 

How to ping ip address or by url in c#

 static void Main(string[] args)
        {
           string url = "http://stackoverflow.com/";
            Ping p = new Ping();
            PingReply p1 = p.Send("IP address or site url", 3000);
           //3000 -> it is time out time
            if (p1.Status == IPStatus.Success)
            {
                Console.WriteLine("working fine");
            }
            Console.ReadLine();
        }

Thread-Safe Collection using blockingcollection and Task in C#

// Thread-Safe Collection using blockingcollection and Task

static void Main(string[] args)
        {
         
            BlockingCollection<int> block = new BlockingCollection<int>();
         
            var task1 = Task.Factory.StartNew(() => {
                foreach (int i in block.GetConsumingEnumerable()) // GetConsumingEnumerable is used to take element from collection and deleted it
                {
                    Console.WriteLine("Task 1 data {0}", i);
                }

             
               
            });
            var task2 = Task.Factory.StartNew(() =>
            {
                foreach (int i in block.GetConsumingEnumerable())
                {
                    Console.WriteLine("Task 2 data {0}", i);
                }

               
            });

            var task3 = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    block.Add(i);
                }
                block.CompleteAdding(); //Its used to check , BlockingCollection list is added or not
               
            });
         
            task3.Wait(); // why we add task3.Wait() , becoz first of all we are going to add item into BlockingCollection  list then we are going to loop on this list at a same time
            Task.WaitAll(task1, task2); // after finished task3 , these task1 and task2 is going to wait until they finished work
            Console.ReadLine();
        }

OutPut->Task 1 data 0
Task 2 data 1
Task 1 data 2
Task 2 data 3

find duplicate value in array using C#

//find duplicate value in array using C#

static void Main(string[] args)
        {

            Console.WriteLine("Please enter limit of arry");
            int i = Convert.ToInt32(Console.ReadLine());
            int[] arry = new int[i];
            for (int j = 0; j < arry.Length; j++)
            {
                Console.Write("\nEnter your number:\t");
                arry[j] = Convert.ToInt32(Console.ReadLine());

            }
            ArrayList list = new ArrayList();
            Console.WriteLine("\n\n");
       
            for (int k = 0; k < arry.Length; k++)
            {
                for (int l = k; l < arry.Length - 1; l++)
                {
                    if (arry[k] == arry[l + 1])
                    {
                        list.Add(arry[k]);
                    }
                }
            }

            if (list.Count == 0)
            {
                Console.WriteLine("No dulicate value");
            }
            else
            {
                foreach (var _list in list)
                {
                    Console.WriteLine("No of value {0}", _list);
                }
            }

         
            Console.ReadKey();
        }

Delete file depend on time using C#

          //to delete file from folder  
           string FileLocation=@"G:\File delete";
           DirectoryInfo source = new DirectoryInfo(FileLocation);
           foreach (FileInfo file in source.GetFiles())
            {
                var creationTime = file.CreationTime;
               //or
                var lasttime = file.LastAccessTime;

                if (creationTime < DateTime.Now)
                {
                  file.Delete();
                }
            }

Find Max value in array and secondMax using C#

            int[] arr = new int[] { 1, 5, 6, 3, 9, 23 };
            int maxvalue = arr[0];
            int secondmaxvalue = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (maxvalue < arr[i])
                {
                    secondmaxvalue = maxvalue;
                    maxvalue = arr[i];
                 
                }
                else if (secondmaxvalue < arr[i])
                {
                    secondmaxvalue = arr[i];
                }

            }
            Console.WriteLine(maxvalue);
            Console.WriteLine(secondmaxvalue);

Or else we can use linq or lemda exp like this

By Linq->
    var checksecondlagestnumber = (from ITEM in arr orderby ITEM descending select ITEM).Skip(1).FirstOrDefault();

By Lemda->
            var checksecondlagestnumber= arr.OrderByDescending(ITEM => ITEM).Select(ITEM => ITEM).Skip(1).FirstOrDefault();

Reverse word and make first element in Upper case

 public static void Revrseword()
        {
            string str = "ankit Panwar frOm muzaFFarnagar";
            StringBuilder sb = new StringBuilder();
            string[] arry = str.Split(' ');
            for (int i = 0; i < arry.Length; i++)
            {
                string check = arry[i];
                for (int j = check.Length - 1; j >= 0; j--)
                {
                    if (j == check.Length - 1)
                    {
                        sb.Append(check[j].ToString().ToUpper());
                    }
                    else
                    {
                        sb.Append(check[j].ToString().ToLower());
                    }
                }
                sb.Append(" ");
            }
            Console.WriteLine(sb.ToString());
        }

OutPut like -> Tikna Rawnap Morf Raganraffazum