Monday, 13 February 2017

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();

        }

Wednesday, 13 April 2016

Filter ArrayList value depend on datatype In C#


To get only specific Datatype value in ArrayList you can used below code .

OfType<DataType> ==> this is used to filter arraylist  value depend on DataType passed in.



          ArrayList list = new ArrayList();

            list.Add(1);
            list.Add(1.2);
            list.Add("StringValue");
            list.Add("StringValueOne");
            list.Add(true);

            foreach(var item in list.OfType<String or Int or Bool>()) // Here you can passed string,int ext  .
            {
                Console.WriteLine(item);
            }


Output: StringValue,StringValueOne

Monday, 4 April 2016

Find element whose id has a particular pattern in Jquery

Basically we have pattern to match with ID in jquery .


1) That selector matches all Button that have an id attribute and it starts with  "Test"

            $('input[id^="Test"]').css('background-color', 'red');
        

2)  That selector matches all Button that have an id attribute and it ends with "Test".

            $('input[id$="Test"]').css('background-color', 'red');
          

3) That selector matches all Button that have an id attribute  anywhere  with "Test" id.

            $('input[id*="Test"]').css('background-color', 'red');
         
Ex -> <asp:Button ID="Test" runat="server" Text="Button"  />
         <asp:Button ID="Test1" runat="server" Text="Button1" />
         <asp:Button ID="Test2" runat="server" Text="Button2" />
         <asp:Button ID="NotTest3" runat="server" Text="Button3" OnClick="Button1_Click"                   OnClientClick="return test();"/>

Output for 1 , 2 and 3 Pattern)