Monday, 13 February 2017

Get file count from directory using C#



public static void Main()
        {
            var file =new  DirectoryInfo(@"E:\Your Folder path");
            var fileinfo = file.GetFiles("*", SearchOption.AllDirectories);
            foreach (var item in fileinfo)
            {
                Console.WriteLine("File Name => " + item.FullName);
            }
            Console.WriteLine("File total count => " + fileinfo.Length);
            Console.ReadLine();
        }

Note=> you will gave your Directory info path and it will find all find SubDirectory or Directory

//OR we can write in one line like that below .


int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;


but it will gave you how many file are  inside your folder path.

Generate random number using C#



       static object locker = new object();
        public static long Generate15DigitsUniqueNumber()
        {
            try
            {
                lock (locker)
                {
                    Thread.Sleep(100);
                    return Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssff"));
                }
            }
            catch (Exception ex)
            {
                return Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            }
           
        }

OutPut=> 2017021412354472

    // OR using string and byte

        public static string GenerateRandomString(Random rnd)
        {
            byte[] bytes = new byte[255];
            rnd.NextBytes(bytes);
            string szRandom = System.Text.Encoding.ASCII.GetString(bytes);
            char[] c = szRandom.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char cc in c)
            {
                if (Char.IsLetter(cc))
                {
                    sb.Append(cc);
                }
            }
            return sb.ToString();

        }

       public static void Main()
        {
             Random rnd = new Random();
            Console.WriteLine("RandomPassword={0}", GenerateRandomString(rnd));
        }


OutPut like that=> sEmVYckDVHXpCVkQHhNNbnKNeefGQaWzlvBjlAqQCosDLWzkflER


C# find repeated numbers in an array


Integer Array has  numbers ,some are repeated, if you want to find which number is repeated how many time., Here is the logic using LINQ.

       static   void FindRepeatedNumbers()
        {
             int[] arraytest = new int[] { 50, 20, 100, 10, 30, 10, 30, 20};

            var query = from d in arraytest
                        group d by d into test
                        select test;

            foreach (IGrouping<int, int> intagroup in query)
            {
                Console.WriteLine("Key={0},Repeated {1} Times", intagroup.Key, intagroup.Count());
            }
   }

  1. First group by  each number
  2. there will a unique groups ,then find each group has how many numbers.
Here is the output.

Number=50,Repeated 1 Times
Number=20,Repeated 2 Times
Number=100,Repeated 1 Times
Number=10,Repeated 2 Times
Number=30,Repeated 2 Times

Find unique characters from string in C#


       Below code will help out , how to find unique characters from string .

       char[] chars = "abdccddbbzcyxzwwwww"?.ToCharArray();
            {
             var dic = new Dictionary<char, int>();
                 foreach (var c in chars)
                {
                    if (!dic.ContainsKey(c))
                    {
                        dic[c] = 0;
                    }
                    dic[c]++;
                }
                foreach (var charCombo in dic)
                {
                    if (charCombo.Value == 1)
                    {
                        Console.WriteLine(charCombo.Key.ToString());
                    }
                }
             
            }

Exception handling in Xunit test case in C#





        [Fact]
        public void TestControllerTests()
        {
               Assert.ThrowsAny<ArgumentNullException>(() => new TestController(null, null));
             / / OR

          Exception ex = Assert.Throws<ArgumentNullException>(() =>
                                                                                                new TestController(null, null));
          Assert.Equal("Error message by Exception  class", ex.Message);
        }



Note => We can also use instated of  "ArgumentNullException" to Exception class or some costume class to check Exception  in xunit test case.

How to return list in Tuple using C#

public class TestTuple
    {
        static void Main()
        {
            var item= GeTuple();
            foreach (var item1 in item.Item1)
            {
                Console.WriteLine("Test one id {0} and value {1}", item1.Id,item1.Name);
            }
            Console.WriteLine("*******************************************");
            foreach (var item1 in item.Item2)
            {
                Console.WriteLine("Test Two id {0} and value {1}", item1.Id, item1.Name);
            }
            Console.ReadLine();
        }

        private static Tuple<List<TestOne>,List<TestTwo>> GeTuple()
        {
            var listone = new List<TestOne>()
            {
                new TestOne(){Id = 1,Name = "Ankit"},
                new TestOne(){Id = 2,Name = "Ankit"},
                new TestOne(){Id = 3,Name = "Ankit"}
            };
            var listTwo = new List<TestTwo>()
            {
                new TestTwo(){Id = 1,Name = "AnkitTwo"},
                new TestTwo(){Id = 2,Name = "AnkitTwo"},
                new TestTwo(){Id = 3,Name = "AnkitTwo"}
            };
            return new Tuple<List<TestOne>, List<TestTwo>>(listone, listTwo);
        }
    }

    public class TestOne
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class TestTwo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Poisonous Plants problem from hacker Rank

 public static   void Main()
        {
            var size =Convert.ToInt32(Console.ReadLine());
            var list=new List<string>();
            var input = Console.ReadLine();
            for (var i = 0; i < size; i++)
            {
                if (input != null && input.Split(' ').Length > size)
                {
                    Console.WriteLine("Please enter input again");
                    return;
                }
                if (input != null) list.Add(input.Split(' ')[i]);
            }
            var countdays = 0;
            list.RemoveAll(x => x == " ");
            var listupdate = new List<string>();
            var result = Check(true, list, listupdate, countdays).Result;
            Console.WriteLine(result);
            Console.ReadLine();
        }

        private static async Task<int> Check(bool flag, List<string> list, List<string> listupdate,int       countdays)
        {
           return  await Task<int>.Factory.StartNew(() =>
            {
                while (flag)
                {
                    if (list.Distinct().Count() == 1)
                    {
                        break;
                    }
                    for (var i = 0; i < list.Count - 1; i++)
                    {
                        if (list[i] != " ")
                        {
                            if (Convert.ToInt32(list[i]) - Convert.ToInt32(list[i + 1]) > 0)
                            {
                                if (i == 0)
                                {
                                    listupdate.Add(list[i]);
                                    listupdate.Add(list[i + 1]);
                                }
                                else
                                {
                                    listupdate.Add(list[i + 1]);
                                }
                            }
                            else
                            {
                                if (i == 0)
                                {
                                    listupdate.Add(list[i]);
                                }
                                else if (Convert.ToInt32(list[i]) - Convert.ToInt32(list[i + 1]) == 0)
                                {
                                    listupdate.Add(list[i + 1]);
                                }
                            }
                        }
                    }
                    if (list.Count == listupdate.Count)
                    {
                        flag = false;
                    }
                    else if (list.Count == 1)
                    {
                        flag = false;
                    }
                    else if (listupdate.Count == 0)
                    {
                        flag = false;
                    }
                    else
                    {
                        countdays++;
                    }
                    list.Clear();
                    list = listupdate.ToList();
                    listupdate.Clear();
                }
                return countdays;
            });
        }

AsNoTracking entity framework 6 example

What is AsNoTracking =>

1) When you use .AsNoTracking() you are basically telling the context not to track the retrieved information. 

2) This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.

3) basically is used to , when we are selecting  data from database.

4)It is important however not to use this tuning option when you intend to update the entity as this will mean that Entity Framework has no way of knowing that it needs to save your changes back to the database. 

Ex=>


  • Include .AsNoTracking() on your query
  • var items = Context.MyEntity.AsNoTracking().Where(e => e.ID);
   Now when you run above query , that entity don't  store result in cache memory.


   

Sunday, 12 February 2017

Auto Mapper with simple example

AutoMapper is a mapper between two objects. It maps two different entities by transforming an input object of one type to an output object of another type. It is very tough job to map two different entities and sometime it is even more hectic when it comes to testing. It can be anywhere in the application but in general it happens in UI/Domain or Service/Domain layers.

* Need to download from NuGet package manager, open the NuGet console and enter the following command to install the AutoMapper library:

PM>  Install-Package AutoMapper

Now create two class with same data type property in it but we can have different name , for different name we have to make changes in mapper class . i have declared  below =>

public class TestAutoMapperOne
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

    public class TestAutoMapperTwo
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Address { get; set; }
    }

* Now we have create one more class , where we can create Map for our class .

using AutoMapper;
namespace TestDemo
{
    public class TestMapper : Profile // this is inherit from AutoMapper dll to create Mapper 
    {
        public TestMapper()
        {
            CreateMap<TestAutoMapperOne, TestAutoMapperTwo>()
                .ForMember(des => des.FullName, map => map.MapFrom(src => src.Name));

            CreateMap<TestAutoMapperTwo, TestAutoMapperOne>()
               .ForMember(des => des.Name, map => map.MapFrom(src => src.FullName)); // this for Reverse mapping or we can also call it in below line like that 
        
        //************************OR***************************//
      CreateMap<TestAutoMapperOne, TestAutoMapperTwo>()
                .ForMember(des => des.FullName, map => map.MapFrom(src => src.Name)).ReverseMap();


           
ForMember=>  We have  different name in property class that we have to  map our class property in ForMember() of mapping.

  .ForMember(des => des.FullName, map => map.MapFrom(src => src.Name));

// First class will we destination and second class will be source  

For ex-> public class TestAutoMapperOne
    {
           public string Name { get; set; }
    }
    public class TestAutoMapperTwo
    {
        public string FullName { get; set; }
     }


    
* Now start mapping our class in Main method 

   public static void Main()
        {
            Console.WriteLine("Start AutoMapper!");
            var test = new TestAutoMapperOne()
            {
                Name = "Test",
                Id = 1,
                Address = "Bnagalore"
            };

         var config = new MapperConfiguration(cfg => cfg.AddProfile(new TestMapper()));
         // Here i have called my above class constructor "TestMapper" to configuration                         mapper 

            var mapper = config.CreateMapper();
            var item = mapper.Map<TestAutoMapperTwo>(test);

*   As first class inside Map its class "TestAutoMapperTwo" where we are going to map                with TestAutoMapperOne object .

            var item1 = mapper.Map<TestAutoMapperOne>(item); 
           // its for  ReverseMap class TestAutoMapperOne  to TestAutoMapperTwo
           Console.ReadLine();

        }