Wednesday, January 2, 2019

Debugging ToolTip


{ position: { my: "left+15 center", at: "right center" } }
$("[data-toggle='tooltip']").tooltip({ position: { my: "left+15 center", at: "right center" } });


Ctrl + Shift + C = debug ToolTip / any hover

How to Avoid If - else-if or nested IFELSE

using Rule or by defining the Rules in an array
example below

 var carryOverRules = new[]
            {
                //Full Time
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.FullTime==true && x.MaxCarryOver403020==true),
                    Value = 40.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.FullTime==true && x.MaxCarryOver604530==true),
                    Value = 60.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.FullTime==true && x.MaxCarryOver806040==true),
                    Value = 80.00m
                },

                // PartTime 75
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime75==true && x.MaxCarryOver403020==true),
                    Value = 30.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime75==true && x.MaxCarryOver604530==true),
                    Value = 45.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime75==true && x.MaxCarryOver806040==true),
                    Value = 60.00m
                },

                 // PartTime 50
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime50==true && x.MaxCarryOver403020==true),
                    Value = 20.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime50==true && x.MaxCarryOver604530==true),
                    Value = 30.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => x.PartTime50==true && x.MaxCarryOver806040==true),
                    Value = 40.00m
                },
                new
                {
                    Rule = (Func<dynamic, bool>) (x => true),
                    Value = 0.00m // Default Rule value if not match with any criteria
                },
            };       
            carryOver = carryOverRules.FirstOrDefault(x =>x.Rule(timeOffFlags)).Value;

Thursday, February 22, 2018

How do I do a patch request using HttpClient in dotnet core?

Thanks to Daniel A. White's comment, I got the following working.
using (var client = new HttpClient())
{       
    var request = new HttpRequestMessage(new HttpMethod("PATCH"), "your-api-endpoint");

    try
    {
        response = await client.SendAsync(request);
    }
    catch (HttpRequestException ex)
    {
        // Failed
    }
}


https://stackoverflow.com/questions/36023821/how-to-pass-the-following-json-to-a-c-sharp-patch-method-w-or-w-o-javascript-ser/36027802#36027802

Thursday, June 29, 2017

Entity Framework Working with Transactions

https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx


Entity Framework Working with Transactions (EF6 Onwards)

 
Updated: October 23, 2016
EF6 Onwards Only - The features, APIs, etc. discussed in this page were introduced in Entity Framework 6. If you are using an earlier version, some or all of the information does not apply.
This document will describe using transactions in EF6 including the enhancements we have added since EF5 to make working with transactions easy.
In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.
Starting with EF6 Database.ExecuteSqlCommand() by default will wrap the command in a transaction if one was not already present. There are overloads of this method that allow you to override this behavior if you wish. Also in EF6 execution of stored procedures included in the model through APIs such as ObjectContext.ExecuteFunction() does the same (except that the default behavior cannot at the moment be overridden).
In either case, the isolation level of the transaction is whatever isolation level the database provider considers its default setting. By default, for instance, on SQL Server this is READ COMMITTED.
Entity Framework does not wrap queries in a transaction.
This default functionality is suitable for a lot of users and if so there is no need to do anything different in EF6; just write the code as you always did.
However some users require greater control over their transactions – this is covered in the following sections.
Prior to EF6 Entity Framework insisted on opening the database connection itself (it threw an exception if it was passed a connection that was already open). Since a transaction can only be started on an open connection, this meant that the only way a user could wrap several operations into one transaction was either to use a TransactionScope or use the ObjectContext.Connection property and start calling Open() and BeginTransaction()directly on the returned EntityConnection object. In addition, API calls which contacted the database would fail if you had started a transaction on the underlying database connection on your own.
Note: The limitation of only accepting closed connections was removed in Entity Framework 6. For details, see Connection Management (EF6 Onwards).
Starting with EF6 the framework now provides:
  1. Database.BeginTransaction() : An easier method for a user to start and complete transactions themselves within an existing DbContext – allowing several operations to be combined within the same transaction and hence either all committed or all rolled back as one. It also allows the user to more easily specify the isolation level for the transaction.
  2. Database.UseTransaction() : which allows the DbContext to use a transaction which was started outside of the Entity Framework.

Combining several operations into one transaction within the same context

Database.BeginTransaction() has two overrides – one which takes an explicit IsolationLevel and one which takes no arguments and uses the default IsolationLevel from the underlying database provider. Both overrides return a DbContextTransaction object which provides Commit() and Rollback()methods which perform commit and rollback on the underlying store transaction.
The DbContextTransaction is meant to be disposed once it has been committed or rolled back. One easy way to accomplish this is the using(…) {…}syntax which will automatically call Dispose() when the using block completes:
using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Transactions; 
 
namespace TransactionsExamples 
{ 
    class TransactionsExample 
    { 
        static void StartOwnTransactionWithinContext() 
        { 
            using (var context = new BloggingContext()) 
            { 
                using (var dbContextTransaction = context.Database.BeginTransaction()) 
                { 
                    try 
                    { 
                        context.Database.ExecuteSqlCommand( 
                            @"UPDATE Blogs SET Rating = 5" + 
                                " WHERE Name LIKE '%Entity Framework%'" 
                            ); 
 
                        var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
                        foreach (var post in query) 
                        { 
                            post.Title += "[Cool Blog]"; 
                        } 
 
                        context.SaveChanges(); 
 
                        dbContextTransaction.Commit(); 
                    } 
                    catch (Exception) 
                    { 
                        dbContextTransaction.Rollback(); 
                    } 
                } 
            } 
        } 
    } 
}

Note: Beginning a transaction requires that the underlying store connection is open. So calling Database.BeginTransaction() will open the connection if it is not already opened. If DbContextTransaction opened the connection then it will close it when Dispose() is called.

Passing an existing transaction to the context

Sometimes you would like a transaction which is even broader in scope and which includes operations on the same database but outside of EF completely. To accomplish this you must open the connection and start the transaction yourself and then tell EF a) to use the already-opened database connection, and b) to use the existing transaction on that connection.
To do this you must define and use a constructor on your context class which inherits from one of the DbContext constructors which take i) an existing connection parameter and ii) the contextOwnsConnection boolean.
Note: The contextOwnsConnection flag must be set to false when called in this scenario. This is important as it informs Entity Framework that it should not close the connection when it is done with it (e.g. see line 4 below):
using (var conn = new SqlConnection("...")) 
{ 
    conn.Open(); 
    using (var context = new BloggingContext(conn, contextOwnsConnection: false)) 
    { 
    } 
}

Furthermore, you must start the transaction yourself (including the IsolationLevel if you want to avoid the default setting) and let the Entity Framework know that there is an existing transaction already started on the connection (see line 33 below).
Then you are free to execute database operations either directly on the SqlConnection itself, or on the DbContext. All such operations are executed within one transaction. You take responsibility for committing or rolling back the transaction and for calling Dispose() on it, as well as for closing and disposing the database connection. E.g.:
using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Data.SqlClient; 
using System.Linq; 
sing System.Transactions; 
 
namespace TransactionsExamples 
{ 
     class TransactionsExample 
     { 
        static void UsingExternalTransaction() 
        { 
            using (var conn = new SqlConnection("...")) 
            { 
               conn.Open(); 
 
               using (var sqlTxn = conn.BeginTransaction(System.Data.IsolationLevel.Snapshot)) 
               { 
                   try 
                   { 
                       var sqlCommand = new SqlCommand(); 
                       sqlCommand.Connection = conn; 
                       sqlCommand.Transaction = sqlTxn; 
                       sqlCommand.CommandText = 
                           @"UPDATE Blogs SET Rating = 5" + 
                            " WHERE Name LIKE '%Entity Framework%'"; 
                       sqlCommand.ExecuteNonQuery(); 
 
                       using (var context =  
                         new BloggingContext(conn, contextOwnsConnection: false)) 
                        { 
                            context.Database.UseTransaction(sqlTxn); 
 
                            var query =  context.Posts.Where(p => p.Blog.Rating >= 5); 
                            foreach (var post in query) 
                            { 
                                post.Title += "[Cool Blog]"; 
                            } 
                           context.SaveChanges(); 
                        } 
 
                        sqlTxn.Commit(); 
                    } 
                    catch (Exception) 
                    { 
                        sqlTxn.Rollback(); 
                    } 
                } 
            } 
        } 
    } 
}

Notes:
  • You can pass null to Database.UseTransaction() to clear Entity Framework’s knowledge of the current transaction. Entity Framework will neither commit nor rollback the existing transaction when you do this, so use with care and only if you’re sure this is what you want to do.
  • You will see an exception from Database.UseTransaction() if you pass a transaction:
    • When the Entity Framework already has an existing transaction
    • When Entity Framework is already operating within a TransactionScope
    • Whose connection object is null (i.e. one which has no connection – usually this is a sign that that transaction has already completed)
    • Whose connection object does not match the Entity Framework’s connection.
This section details how the above transactions interact with:
  • Connection resiliency
  • Asynchronous methods
  • TransactionScope transactions

Connection Resiliency

The new Connection Resiliency feature does not work with user-initiated transactions. For details, see Limitations with Retrying Execution Strategies.

Asynchronous Programming

The approach outlined in the previous sections needs no further options or settings to work with the asynchronous query and save methods. But be aware that, depending on what you do within the asynchronous methods, this may result in long-running transactions – which can in turn cause deadlocks or blocking which is bad for the performance of the overall application.

TransactionScope Transactions

Prior to EF6 the recommended way of providing larger scope transactions was to use a TransactionScope object:
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Transactions; 
 
namespace TransactionsExamples 
{ 
    class TransactionsExample 
    { 
        static void UsingTransactionScope() 
        { 
            using (var scope = new TransactionScope(TransactionScopeOption.Required)) 
            { 
                using (var conn = new SqlConnection("...")) 
                { 
                    conn.Open(); 
 
                    var sqlCommand = new SqlCommand(); 
                    sqlCommand.Connection = conn; 
                    sqlCommand.CommandText = 
                        @"UPDATE Blogs SET Rating = 5" + 
                            " WHERE Name LIKE '%Entity Framework%'"; 
                    sqlCommand.ExecuteNonQuery(); 
 
                    using (var context = 
                        new BloggingContext(conn, contextOwnsConnection: false)) 
                    { 
                        var query = context.Posts.Where(p => p.Blog.Rating > 5); 
                        foreach (var post in query) 
                        { 
                            post.Title += "[Cool Blog]"; 
                        } 
                        context.SaveChanges(); 
                    } 
                } 
 
                scope.Complete(); 
            } 
        } 
    } 
}

The SqlConnection and Entity Framework would both use the ambient TransactionScope transaction and hence be committed together.
Starting with .NET 4.5.1 TransactionScope has been updated to also work with asynchronous methods via the use of theTransactionScopeAsyncFlowOption enumeration:
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Transactions; 
 
namespace TransactionsExamples 
{ 
    class TransactionsExample 
    { 
        public static void AsyncTransactionScope() 
        { 
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) 
            { 
                using (var conn = new SqlConnection("...")) 
                { 
                    await conn.OpenAsync(); 
 
                    var sqlCommand = new SqlCommand(); 
                    sqlCommand.Connection = conn; 
                    sqlCommand.CommandText = 
                        @"UPDATE Blogs SET Rating = 5" + 
                            " WHERE Name LIKE '%Entity Framework%'"; 
                    await sqlCommand.ExecuteNonQueryAsync(); 
 
                    using (var context = new BloggingContext(conn, contextOwnsConnection: false)) 
                    { 
                        var query = context.Posts.Where(p => p.Blog.Rating > 5); 
                        foreach (var post in query) 
                        { 
                            post.Title += "[Cool Blog]"; 
                        } 
 
                        await context.SaveChangesAsync(); 
                    } 
                } 
            } 
        } 
    } 
}

There are still some limitations to the TransactionScope approach:
  • Requires .NET 4.5.1 or greater to work with asynchronous methods.
  • It cannot be used in cloud scenarios unless you are sure you have one and only one connection (cloud scenarios do not support distributed transactions).
  • It cannot be combined with the Database.UseTransaction() approach of the previous sections.
  • It will throw exceptions if you issue any DDL (e.g. because of a Database Initializer) and have not enabled distributed transactions through the MSDTC Service.
Advantages of the TransactionScope approach:
  • It will automatically upgrade a local transaction to a distributed transaction if you make more than one connection to a given database or combine a connection to one database with a connection to a different database within the same transaction (note: you must have the MSDTC service configured to allow distributed transactions for this to work).
  • Ease of coding. If you prefer the transaction to be ambient and dealt with implicitly in the background rather than explicitly under you control then the TransactionScope approach may suit you better.
In summary, with the new Database.BeginTransaction() and Database.UseTransaction() APIs above, the TransactionScope approach is no longer necessary for most users. If you do continue to use TransactionScope then be aware of the above limitations. We recommend using the approach outlined in the previous sections instead where possible.

Wednesday, June 21, 2017

Export List To Excel

 public static void ExportToExcel(List<T52DataModel> myList)
        {
            string fileName = $"C:\\T52{DateTime.Now.Date.ToString("yyyyMMdd")}.xls";

            List<string> result = new List<string>();
            result.Add(String.Join(String.Empty, typeof(T52DataModel).GetProperties().Select(i => String.Format("{0}\t", i.Name)))); // Headers
            result.AddRange(myList.Select(i => String.Join("\t", i.GetType().GetProperties().Select(t => t.GetValue(i, null))))); // Lines

            File.WriteAllLines(fileName, result);

        }

How to return a list of weekend dates between 2 dates

Use the DateTime.DayOfWeek property.

https://msdn.microsoft.com/en-US/library/system.datetime.dayofweek(v=vs.110).aspx

static public List<string> GetDates(DateTime start_date, DateTime end_date)
    {
        List<string> days_list = new List<string>();
         for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
        {
            if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
                 days_list.Add(date.ToShortDateString());
        }

        return days_list;

Wednesday, April 12, 2017

How to work with Hangfire in C# Take advantage of Hangfire, an open source job scheduling framework, to schedule fire-and-forget, recurring tasks in Web applications sans the need of a Windows Service



Scheduling jobs in Web applications is a challenge, and you can choose from many frameworks for the task. A popular open source library, Hangfire is one framework that can be used for scheduling background jobs in .Net.

Why should I use Hangfire?

There are many job scheduling frameworks available today. Why then should you use Hangfire instead of, say, Quartz.Net, which is another popular framework that has long been in use? Well, one of the major drawbacks of Quartz.Net is that it needs a Windows Service. On the contrary, you don't need a Windows Service to use Hangfire in your application. The ability to run without a Windows Service makes Hangfire a good choice over Quartz.Net. Hangfire takes advantage of the request processing pipeline of ASP.Net for processing and executing jobs.
Note that Hangfire is not limited to Web applications; you can also use it in your Console applications. The documentation for Hangfire is very detailed and well structured, and the best feature is its built-in dashboard. The Hangfire dashboard shows detailed information on jobs, queues, status of jobs, and so on.

Getting started

To create a new project in Visual Studio that leverages Hangfire, follow these steps:
  1. Open Visual Studio 2015
  2. Click on File > New > Project
  3. Select Visual C# > Web from the list of the project templates displayed
  4. Select ASP.Net Web application from the list of the Web project templates
  5. Save the project with a name
The next step is installing and configuring Hangfire in your application; the process is quite straightforward. You can install Hangfire via the NuGet Package Manager in Visual Studio. Alternatively, you can also use the Package Manager Console to install the Hangfire library. The default installation of Hangfire uses SQL Server for storing scheduling information. Additionally, you can install Hangfire.Redis if you use Redis instead for storage.
Note that Hangfire stores your jobs in a persistent storage -- you need to configure the storage before you start using Hangfire. To do this, create a database and specify the database credentials in the connection string in the configuration file. You don’t need to create the tables in your database; Hangfire will do that for you automatically. We will see how and when it will be done later.
Now that the database has been created and the connection string information specified in the configuration file of the application, the next step is to modify the Startup.cs file and provide the necessary connection string information. The following code listing illustrates how the Startup.cs file looks after the configuration details have been specified.
using Hangfire;
using Microsoft.Owin;
using Owin;
using System;
[assembly: OwinStartupAttribute(typeof(HangFire.Startup))]
namespace HangFire
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            GlobalConfiguration.Configuration
                .UseSqlServerStorage("DefaultConnection");
            BackgroundJob.Enqueue(() => Console.WriteLine("Getting Started with HangFire!"));
            app.UseHangfireDashboard();
            app.UseHangfireServer();
        }
    }
}
You're all set. When you run the application and suffix the URL with "/hangfire", you can see the Hangfire dashboard. When you execute this the very first time, a new table is created in the database. The tables that are created include AggregatedCounter, Counter, Hash, Job, JobParameter, JobQueue, List, Schema, Server, Set, and State. Creating a fire-and-forget background in Hangfire is quite simple. You can create a background job using the Enqueue() method of the BackgroundJob class. Here's an example:
BackgroundJob.Enqueue(() => Console.WriteLine("This is a fire-and-forget job that would run in the background."));
A delayed background job is one that waits (for the delay interval), then executes much the same way as a normal fire-and-forget background job. The following code snippet illustrates how you can create a delayed background job using the Schedule() method of the BackgroundJob class.
BackgroundJob.Schedule(() => Console.WriteLine("This background job would execute after a delay."), TimeSpan.FromMilliseconds(1000));
If you were to execute jobs that would execute after a specific interval of time, you would need to create recurring jobs in Hangfire. To create a recurring job, you would have to leverage the RecurringJob class. Note that you can also specify “cron” expressions when scheduling jobs in Hangfire. The following code snippet illustrates how you can create a recurring job using the Hangfire library.
RecurringJob.AddOrUpdate(() => Console.WriteLine("This job will execute once in every minute"), Cron.Minutely);
Check out the Hangfire Highlighter tutorial for more information.