Sunday, 26 March 2023

Bulk update and Delete in EF core 7 using C#

 EF Core7 released a new feature for Bulk updating and Delete.

Nuggets - Microsoft.EntityFrameworkCore.Relational

To delete a set of entities in bulk, filter out the entities that you want to delete by using the Where method Then, invoke the ExecuteDelete method on the collection of entities to be deleted.

using (var db = new BloggingContext())

{

var blogs = db.Blogs

.Where(b => b.Rating > 3)

.ExecuteDelete();

}

To update entities we need to use the new SetProperty method. The first argument of SetProperty selects the property that must be updated via a lambda, and the second argument is the new value of that property by using a lambda.

using (var db = new BloggingContext())

{

var delete= db.Blogs

.Where(p => p.Rating <= 1_000)

.ExecuteUpdate(p => p.SetProperty(x => x.Url, x => "Updated"));

}

Thursday, 21 June 2018

Working with Caching in C#

Caching - Caching enables you to store data in memory for rapid access. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. This can improve performance and scalability.

So First step to create cache class like below .

 public static class CacheManager

    {

       // its used clear cache depend on key value .

        public static void ClearCacheOf<T>(string key)
        {

            if (!string.IsNullOrEmpty(key) && HttpContext.Current != null)

                HttpContext.Current.Cache.Remove(typeof(T) + key);

        }

       /// Check if the key correponds to an object saved in cache. 

       /// <param name="timeToLive">The time to live in minutes (how long the cache will keep the data).</param>


        /// <param name="identifier">The object's identifier.</param>


        /// <param name="function">The function to apply if the object is not found in cache wich will do the external call.</param>


        
        public static T CacheVerification<T>(int timeToLive, string identifier, Func<T> function)

        {

            if (HttpContext.Current == null)

                return function();


            string key = typeof(T) + identifier;

            var requestedCachedItem = GetFromCache<T>(key);

            T response;


            if (requestedCachedItem != null)

            {

                response = requestedCachedItem;

            }

            else

            {

                response = function();

                AddToCache(key, response, timeToLive);

            }


            return response;
        }

       private static void AddToCache<T>(string key, T objectToAdd, int ttl)

        {

            if (objectToAdd != null)

            {

                HttpContext.Current.Cache.Insert(key, objectToAdd, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(ttl));

            }

        }

        // use existing cache depend on key value   

        private static T GetFromCache<T>(string key)

        {

            return (T)HttpContext.Current.Cache[key];

        }


}

So we can use above class method like this .

1-> case first we are going to save cache in memory .

public IDictionary<int, string> GetMyId(string id)

        {

            return CacheManager.CacheVerification(12, id, () =>  return CacheManager.CacheVerification(12, id, () => new Dictionary<int, string>());

            // or use call your method , i just return empty dictionary for example. 

        }

2-> remove cache 


           CacheManager.ClearCacheOf<List<yourclassname>>("KeyValue");

Sunday, 22 October 2017

Insert multiple rows in sql table using entity framework


There is two way to insert multiple record in Database using EF.

1) As below example,  we have to call AddRange method of DbSet class, here we can add multiple record as i have useEmpDetails  list for adding multiple record. 

using (var context = new DbContextDemo())
            {
                var item = context.EmpDetailsDbSet.ToList();
                //Insert multiple record in sql table using EF

                var list = new List<EmpDetails>(); // this is my Dbset class(EmpDetails) 
                EmpDetails obj = new EmpDetails()
                {
                    EmpID = 23123,
                    EmpName = "ABC",
                    EmpAddress = "Test1",
                    EmpMobile = 1442345,
                    EmpCompany = "ABC"

                };
                list.Add(obj);
                EmpDetails obj1 = new EmpDetails()
                {
                    EmpID = 233,
                    EmpName = "ABC Test",
                    EmpAddress = "Bangalore",
                    EmpMobile = 1435235,
                    EmpCompany = "ABC Test"
                };
                list.Add(obj1);

                context.EmpDetailsDbSet.AddRange(list); // Adding list of emp inside AddRange method 
                context.SaveChanges();

}

2) We will take same as above example, we will have list of EmpDetails and we are going to make foreach loop and add one by one record in Dbset class with Add method .

               var list = new List<EmpDetails>();
                EmpDetails obj = new EmpDetails()
                {
                    EmpID = 23123,
                    EmpName = "ABC",
                    EmpAddress = "Test2",
                    EmpMobile = 1442345,
                    EmpCompany = "ABC"

                };
                list.Add(obj);
                EmpDetails obj1 = new EmpDetails()
                {
                    EmpID = 233,
                    EmpName = "ABC Test",
                    EmpAddress = "Bangalore",
                    EmpMobile = 1435235,
                    EmpCompany = "ABC Test"
                };
                list.Add(obj1);

             foreach (var item1 in list)   // Adding record one by one 
                {
                    context.EmpDetailsDbSet.Add(item1);
                }

         and finally call SaveChanges() method of context class.

          context.SaveChanges();

Tuesday, 5 September 2017

Checked and Unchecked keyword in C#

Unchecked and checked words are used to control whether or not an overflow occurred during arithmetic operations.


Overflows: When a value exceeds the limitations of a data type, it is said to overflow. This can be an inconvenience where unexpected, causing incorrect results from calculations.



Checked Arithmetic :  To prevent the incorrect or dangerous results of unchecked calculations, checked arithmetic can be used instead. One way to achieve this is to use the "checked" keyword for specific sections of code. This keyword uses a code block to surround a series of items that should be processed in this way. If an overflow occurs within a checked code block, an exception of the type System.OverflowException is thrown.



In the above code snippet you can see that I have tried to add extra value to the "z" variable which is of "int" data type and it can hold only "2147483647" value.

This is somewhat we were not expecting your expectation was the compiler should throw some error (overflow) or exception.

Let add Checked Keyword  and see what happen inside program.







After adding checked keyword , we can able to see overflow exception in program. 
Unchecked Arithmetic :  When using the default C# compiler options, arithmetic is unchecked. This means that any overflowing data from arithmetic operations is simply truncated. In the following sample code this is demonstrated by setting an integer to its maximum value, then incrementing it. The resultant value is truncated and rather than being a larger number is actually the smallest permissible integer value.

Let see below screen shoot .




As we can see its work like before it was . we not getting any exception now. 


















Extension Methods in C#

Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface.

For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class, like this:


public class MyUtils
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now we check string by executive  above code like below

string test = "4";
if (MyUtils.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");


Note : However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

The IsNumeric() method is not a method of string data type . It is an extension method written by the programmer for the string data type. The IsNumeric() extension method will be available throughout the application by including the namespace in which it has been defined.


public static class MyExtensionMethods
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the IsNumeric() method directly on strings, like this:

string test = "4";
if (test.IsNumeric())
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");



Note : The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.


Please see below screen shoot .


Extension Methods

Different type of join in LINQ C#.

Different type of join in LINQ C#.

The following are four most common join types:

1) Inner Join 
2) Cross Join (Cross join is not equijoin)
3) Left Outer Join
4) Group Join

So i will explain you one by one , first of all we will start with Inner join.

Inner Join : A join clause takes two sequences as input  or many . The elements in each sequence must either be or contain a property that can be compared to a corresponding property in the other sequence. All joins performed by the join clause are equijoins.

please see below exp.

I have two type of collection class , CourseDetail and Course.

        private class Course
        {
            public string CourseId { get; set; }
            public string CourseName { get; set; }

        }

       private class CourseDetail
        {
            public string CourseId { get; set; }
            public string CourseDescription { get; set; }
            public long CourseSer { get; set; }
        }

Now we are going to bind some of data into list .

       var listCourse = new List<Course>()
            {
                new Course {CourseName = "Test", CourseId = "1"},
                new Course {CourseName = "Test2", CourseId = "2"},
                new Course {CourseName = "Test3", CourseId = "2"},
                new Course {CourseName = "Test4", CourseId = "5"}
            };

       var listCourseDetail = new List<CourseDetail>()
            {
                new CourseDetail {CourseDescription = "Test", CourseId = "1", CourseSer = 1234},
                new CourseDetail {CourseDescription = "Test2", CourseId = "2", CourseSer = 12345},
                new CourseDetail {CourseDescription = "Test3", CourseId = "3", CourseSer = 12346},
                new CourseDetail {CourseDescription = "Test4", CourseId = "4", CourseSer = 12347},
            };

Now will Perform inner join using LINQ as below

     var innerJoinResult = (from cd in listCourseDetail
                        join cour in listCourse on cd.CourseId equals cour.CourseId // here i am comparing CourseDetail list courseid to course list CourseId  , if it is match we will get result .
                        select new
                        {
                            cour.CourseName,
                            cour.CourseId,
                            cd.CourseDescription

                        }).ToList();
            foreach (var item in innerJoinResult)
            {
                 Console.WriteLine($"Course Name {item.CourseName} and its description                                                                         {item.CourseDescription}");
            }
below are output.





Cross Join: Cross join consists to perform a Cartesian product of two sets or sequences.
Cross join is not equijoin, means that no predicate expression of equality in the Join clause of the query.

Below is sample exp.

 var innerJoinResult = (from cd in listCourseDetail
                                   from cour in listCourse // here as you see i did not put any join keyword as its not a equijoin.
                                   select new
                                   {
                                       cour.CourseName,
                                       cour.CourseId,
                                       cd.CourseDescription

                                   }).ToList();
            foreach (var item in innerJoinResult)
            {
                Console.WriteLine($"Course Name {item.CourseName} and its description                                                 {item.CourseDescription}");
            }

below are output.


















Left Outer Join: In a left outer join, all the elements in the left source sequence are returned, even if no matching elements are in the right sequence. To perform a left outer join in LINQ, use the DefaultIfEmpty method in combination with a group join to specify a default right-side element to produce if a left-side element has no matches. You can use null as the default value for any reference type, or you can specify a user-defined default type. In the following example, a user-defined default type is shown:

 var leftJoinResult = (from cd in listCourseDetail
                join cour in listCourse on cd.CourseId equals cour.CourseId into coursegroup // before using DefaultIfEmpty , we have to use group join , if you put your query result into that we called group join. 
                from item in coursegroup.DefaultIfEmpty(new Course {CourseId = "0", CourseName = "None"}) // here i have provide some default value like  CourseName ="None", if above condition did not match up then we will get Courser Name as "None".
                select new
                {
                    item.CourseName,
                    item.CourseId,
                    cd.CourseDescription

                });
            foreach (var item in leftJoinResult)
            {
                Console.WriteLine($" Course Name {item.CourseName} and its description {item.CourseDescription}");
            }







Group Join: A join clause with an into expression is called a group join.
A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. Group Join sequence of object arrays.
If no elements from the right source sequence are found to match an element in the left source, the join clause will produce an empty array for that item. Therefore, the group join is still basically an inner-equijoin except that the result sequence is organized into groups.

Using lambda expressions: 

  var groupJoin = listCourse.GroupJoin(listCourseDetail, //inner sequence
                courseObj => courseObj.CourseId,  //outerKeySelector 
                courseDetailObj => courseDetailObj.CourseId,   //innerKeySelector
               (s, courseDetailGroup) => new  // resultSelector
                {
                    s.CourseName,
                    GroupArray = courseDetailGroup
                }) ;

Or Use Linq Query :

  var groupJoin =
                    from courseObj in listCourse
                    join courseDetailObj in listCourseDetail on courseObj.CourseId equals                                                     courseDetailObj.CourseId into courseDetailGroup 
                    select new { CategoryName = courseObj.CourseName, courseDetail =                                                    courseDetailGroup };

            foreach (var item1 in groupJoin)
            {

                Console.WriteLine(item1.CourseName);
              foreach (var item in item1.GroupArray)
                    Console.WriteLine( $"Group data is {item.CourseDescription} for courseId                                               {item.CourseId}");
                Console.Write("\n");
            }

Below are out Put.












Thursday, 29 June 2017

Get start-date and last-date based on current date in C#

There is many way to find startDate and LastDate of the week , so i have used two way to find out and print it as below.

In first example i will use simple switch case to get startDate of the week.

       private void button3_Click_1(object sender, EventArgs e)
          {
            string dayOfWeek = DateTime.Today.DayOfWeek.ToString().ToLower();
            int getValue = 0;
            switch (dayOfWeek)
            {
                case "monday":
                    getValue = 0;
                    break;
                case "tuesday":
                    getValue = 1;
                    break;
                case "wednesday":
                    getValue = 2;
                    break;
                case "thursday":
                    getValue = 3;
                    break;
                case "friday":
                    getValue = 4;
                    break;
                case "saturday":
                    getValue = 5;
                    break;
                case "sunday":
                    getValue = 6;
                    break;
            }
            DateTime startWeek = DateTime.Now.AddDays(-getValue); // Need to subtract getValue
            DateTime endWeek = startWeek.AddDays(6); // Need to add

           // Print Date of the week.

           for (int i = 0; i <= 7; i++)
            {
                DateTime dt = startWeek;
                switch (i)
                {

                    case 0:
                        Label1.Text = dt.ToShortDateString();
                        break;
                    case 1:
                        Label2.Text = dt.AddDays(i).ToShortDateString();
                        break;
                    case 3:
                        Label3.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 4:
                        Label4.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 5:
                        Label5.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 6:
                        Label6.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 7:
                        Label7.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                }

            }

}

Here is second example to get  startDate and LastDate of the week, this below example is simple and sweet .

DayOfWeek dayOf = DateTime.Now.DayOfWeek;

/* DayOfWeek  => is a Enum , its come under System.Runtime.InteropServices Namespace*/

int day = dayOf - DayOfWeek.Monday; // here we are assuming starting day is Monday  and subtracting current day of the week .

DateTime startDateTime = DateTime.Now.AddDays(-day);

DateTime endDateTime = DateTime.Now.AddDays(day);

  WriteLine($"StartDate if Week is {startDateTime.ToLongDateString()} and End date of week is {endDateTime.ToLongDateString()}");