Keyboard short-cut to get your lost Google Chrome tabs back

Issues:

You just accidentally closed your Google Chrome browser, and oh boy, you lost all your open tabs and windows. Google Chrome has a really helpful short-cut to get them all back. You also have similar options in Firefox and other browsers but have to use their menu system to “Reopen closed tabs”.

The Solution:

In Google Chrome simply use this sort-cut keyboard hotkey:

Ctrl+Shift+T

If you’re not using Google Chrome, my question is: “Why not?” Smile

JavaScript–Adding months or days to a date

Goal:

Add moths or days (or other increments) to a date in JavaScript.

Solution:

var current = new Date();

var threeMonthsInTheFuture =  new Date(new Date(current).setMonth(current.getMonth() + 3));

for days use:

getDate()

for hours use:

getHours().

 

and so on….

EF Code First Migrations–Create Index with INCLUDE

The problem:

Using Entity Framework code first migrations to create a complex index that defines “INCLUDES” as part of the index. Yeah, good luck doing that using Entity Frameworks fluent notation using LINQ ModelBuilder. Btw, the example below is an ASP.Net Core 1.0 implementation.

The solution:

Plug into the Code First migrations pipeline by simply defining your own custom sql.

Create a “dummy” migration file and add the code below that is just using the model builder’s SQL method to run any custom sql. Again you should have an empty Up and Down method unless you made other mapping changes, which is OK, just add the SQL statement below. Of course you need to rename the index and fields you want to include in the index.

To create migrations file via command line, make sure you are in the project folder that contains the EF DbContext.

dotnet ef migrations add CreateIndexForInvoice –c <my context name>

It will create the empty migrations file, now add your custom index as in the example below. Note that if you already have an index with that name you will not be able to apply the migration successfully to the DB. A safer implementation would be to first check if the index already exists inside the SQL statement.

public partial class CreatIndexesForInvoice : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"
            CREATE NONCLUSTERED INDEX [IX_Invoice_DateTime]
            ON [dbo].[Invoice] ([DateTime])
            INCLUDE ([Id],[Number])
        ");

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropIndex("IX_Invoice_DateTime");
    }
}

 

How to enumerate an ENUM (C#)

Goal:

You have a C# ENUM and for some reason you would like to enumerate it. Perhaps you would like to return the enumerated list to the client’s ajax call rather than calling the DB table that represents the ENUM. For example you may have invoice statuses and want to build an anonymous list.

Result:

C# class:

public enum InvoiceStatus
{
    [Display(Name = "OPEN")]
    Open = 1,
    [Display(Name = "CANCELLED")]
    Cancel = 2,
    [Display(Name = "POSTED")]
    Posted = 3,
    [Display(Name = "VOIDED")]
    Void = 4,
    [Display(Name = "SUBMITTED")]
    Submitted = 5
}

MVC Controller:

[Route("getinvoiceStatuses")]

[HttpGet]

public IList<object> GetInvoiceStatuses()

{

var list = new List<object>();

foreach (var status in Enum.GetValues(typeof(InvoiceStatus)))
{
    list.Add(new
    {
        Id = (int)status,
        Description = status.ToString()
    });
}

return list;

}

JSON:

[{"Id":1,"Description":"Open"},

{"Id":2,"Description":"Cancel"},

{"Id":3,"Description":"Posted"},

{"Id":4,"Description":"Void"},

{"Id":5,"Description":"Submitted"}]

Entity Framework DbSet Attach() vs Add()

Issue:

Two options are available in EF to let it know an object exists, “Attach” and “Add”, not sure when to use which.

Answer:

“Add” as the verb suggests is for adding new objects to the EF context in order for them to be created/inserted in the database when calling “SaveChanges”. Without using “add” they float around as orphans as it were. The goal of “Add” is NOT to “tell EF about an object that already exists in the DB”. That is what “Attach” is used for: “Hey EF, you didn’t retrieve this object from the DB you lazy bum, but I am going to let you know that this object now exists as I programmatically instantiated it in custom code”.

So why on earth would you manually/programmatically instantiate an object that you could just as well have retrieved from the DB? Because its cheaper, and if you are like my wife you’re going to love saving money. If you’re the government you will make this pattern illegal. I quite often use ENUMs for keys of reference tables, like 1 = Male and 2 – Female. For example I have two Gender classes, one is part of the EF DbSet and the other just a plain old ENUM. In stead of making a DB call to get the object, if I need it on another object where it is a navigation property (like a Person class that has a navigation property of Gender), when a create a new Person object I don’t have to retrieve the Gender set from the DB, all I have to do is new up “Gender” and assign ENUM 1 to the ID to indicate a “Male”. Attach the new Gender object to the context, _dbSet.Attach(gender). Assign it to the Person object’s Gender property. EF will not try to insert it in the DB and sets the FK on the owning class (Person) relationship. Nice!

var male = new Gender();

male.ID = (int)Enums.Gender.Male;

_dbSet.Attach(male); //add to EF context indicating that it already exists in the DB

var person = new Person();

person.Gender = male;

_dbSet.Add(person); // insert into DB on SaveChanges

_context.SaveChanges(); //insert person but do nothing to the Gender table

 

Remember, behind the scenes when EF retrieves an object from the DB it calls “Attach” on its own context.

Cause-effect of SaveChanges:

- Attach: updates DB if DetectChanges in ChangeTracker observes a modification to the object.

- Add: insert into DB