Monday, 4 April 2016

Support for DB functions in Code first (Entity Framework 6.1)

Install-Package EntityFramework.CodeFirstStoreFunctions -Pre

After the package has been installed copy and paste the code snippet from below to your project. This code demonstrates how to enable store functions in Code First.
public class Customer
{
    public int Id { get; set; }
 
    public string Name { get; set; }
 
    public string ZipCode { get; set; }
}
 
public class MyContext : DbContext
{
    static MyContext()
    {
        Database.SetInitializer(new MyContextInitializer());
    }
 
    public DbSet<Customer> Customers { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new FunctionsConvention<MyContext>("dbo"));
    }
 
    [DbFunction("MyContext", "CustomersByZipCode")]
    public IQueryable<Customer> CustomersByZipCode(string zipCode)
    {
        var zipCodeParameter = zipCode != null ?
            new ObjectParameter("ZipCode", zipCode) :
            new ObjectParameter("ZipCode", typeof(string));
 
        return ((IObjectContextAdapter)this).ObjectContext
            .CreateQuery<Customer>(
                string.Format("[{0}].{1}", GetType().Name,
                    "[CustomersByZipCode](@ZipCode)"), zipCodeParameter);
    }
 
    public ObjectResult<Customer> GetCustomersByName(string name)
    {
        var nameParameter = name != null ?
            new ObjectParameter("Name", name) :
            new ObjectParameter("Name", typeof(string));
 
        return ((IObjectContextAdapter)this).ObjectContext.
            ExecuteFunction<Customer>("GetCustomersByName", nameParameter);
    }
}
 
public class MyContextInitializer : DropCreateDatabaseAlways<MyContext>
{
    public override void InitializeDatabase(MyContext context)
    {
        base.InitializeDatabase(context);
 
        context.Database.ExecuteSqlCommand(
            "CREATE PROCEDURE [dbo].[GetCustomersByName] @Name nvarchar(max) AS " +
            "SELECT [Id], [Name], [ZipCode] " +
            "FROM [dbo].[Customers] " +
            "WHERE [Name] LIKE (@Name)");
 
        context.Database.ExecuteSqlCommand(
            "CREATE FUNCTION [dbo].[CustomersByZipCode](@ZipCode nchar(5)) " +
            "RETURNS TABLE " +
            "RETURN " +
            "SELECT [Id], [Name], [ZipCode] " +
            "FROM [dbo].[Customers] " +
            "WHERE [ZipCode] = @ZipCode");
    }
 
    protected override void Seed(MyContext context)
    {
        context.Customers.Add(new Customer {Name = "John", ZipCode = "98052"});
        context.Customers.Add(new Customer { Name = "Natasha", ZipCode = "98210" });
        context.Customers.Add(new Customer { Name = "Lin", ZipCode = "98052" });
        context.Customers.Add(new Customer { Name = "Josh", ZipCode = "90210" });
        context.Customers.Add(new Customer { Name = "Maria", ZipCode = "98074" });
        context.SaveChanges();
    }
}
 
class Program
{
    static void Main()
    {
        using (var ctx = new MyContext())
        {
            const string zipCode = "98052";
            var q = ctx.CustomersByZipCode(zipCode)
                .Where(c => c.Name.Length > 3);
            //Console.WriteLine(((ObjectQuery)q).ToTraceString());
            Console.WriteLine("TVF: CustomersByZipCode('{0}')", zipCode);
            foreach (var customer in q)
            {
                Console.WriteLine("Id: {0}, Name: {1}, ZipCode: {2}",
                    customer.Id, customer.Name, customer.ZipCode);
            }
 
            const string name = "Jo%";
            Console.WriteLine("\nStored procedure: GetCustomersByName '{0}'", name);
            foreach (var customer in ctx.GetCustomersByName(name))
            {
                Console.WriteLine("Id: {0}, Name: {1}, ZipCode: {2}",
                    customer.Id, customer.Name, customer.ZipCode);  
            }
        }
    }

------------------------------------------------------------------------------------------------------------------------------------
This article is from: http://blog.3d-logic.com/2014/04/09/support-for-store-functions-tvfs-and-stored-procs-in-entity-framework-6-1/

}

Thursday, 8 October 2015

SQL Get top 1 row of each Group

I have a table which I want to get the latest entry for each group. Here's the table:
DocumentStatusLogs Table
|ID| DocumentID | Status | DateCreated |
| 2| 1          | S1     | 7/29/2011   |
| 3| 1          | S2     | 7/30/2011   |
| 6| 1          | S1     | 8/02/2011   |
| 1| 2          | S1     | 7/28/2011   |
| 4| 2          | S2     | 7/30/2011   |
| 5| 2          | S3     | 8/01/2011   |
| 6| 3          | S1     | 8/02/2011   |
The table will be grouped by DocumentID and sorted by DateCreated in descending order. For each DocumentID, I want to get the latest status.
My preferred output:
| DocumentID | Status | DateCreated |
| 1          | S1     | 8/02/2011   |
| 2          | S3     | 8/01/2011   |
| 3          | S1     | 8/02/2011   |

Answer:
;WITH cte AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC) AS rn
   FROM DocumentStatusLogs
)
SELECT *
FROM cte
WHERE rn = 1
If you expect 2 entries per day, then this will arbitrarily pick one. To get both entries for a day, use DENSE_RANK instead



--------------------------------------------------------------------------------------------------------------------------------

Monday, 31 August 2015

Destroy Kendo UI Widgets (KendoGrid)

Destroy Kendo UI Widgets

Every Kendo UI widget has a destroy method, which does the following:
  1. Deletes the widget instance (client object). It is no longer accessible and all its event handlers will stop working.
  2. Removes autogenerated HTML content, which is outside the widget, e.g. detached popups, dropdowns, etc. The main widget HTML remains intact and if needed, it should be removed from the DOM manually. The Window widget is an exception, as it represents a detached popup on its own.
  3. Destroys all child widgets with the help of kendo.destroy() method.

When to destroy widgets manually

A widget can be destroyed in several possible cases:
  • it is no longer needed;
  • it is placed inside a container, which will be updated via an Ajax request. Destroying widgets inside an Ajax container is strongly recommended to prevent memory leaks or other unexpected side effects;
  • the widget settings and behavior must be drastically changed, which cannot be achieved via available API methods;
Kendo UI widgets are destroyed automatically when the web page is unloaded.
Creating a new widget instance from the leftovers of a destroyed widget may work, but is not recommended. Please initialize new widgets from different (e.g. newly appended) DOM elements. In some cases it is also possible to empty the widget container and initialize a new instance from the empty element.

Example - destroying and removing a Grid widget

<div id="grid"></div>

<script>
    $("#grid").kendoGrid( { /* configuration */ } ); // create a Grid widget

    $("#grid").data("kendoGrid").destroy(); // destroy the Grid

    $("#grid").empty(); // empty the Grid content (inner HTML)
    // or 
    $("#grid").remove(); // remove all Grid HTML
</script>
In addition to destroying a particular Kendo UI widget, the Kendo UI framework provides a kendo.destroy() method, which can destroy multiple widgets, which are placed inside a given container.

------------------------------------------------------------------------------------------------------------------------------
E.g. If you create grid with dynamic columns, and after you search maybe the column count and column content will be changed, you need destroy and empty the grid content first, otherwise, you will receive error message.

This aticle is from:
http://docs.telerik.com/kendo-ui/framework/widgets/destroy