Friday, May 18, 2012

How to write a generic extension for ObjectSet<T> that works with entity types having common property names.

Sometimes you have the same properties in multiple entities.

It is possible to end up duplicating the same logic in the manner of the dreaded copy-modify monster.  I have learned to take it seriously when I find myself doing this because it has never not eventually come back to haunt me .

The key to making this work is to first deploy a couple of simple extension methods to make reflection a bit easier.

Then it is less daunting of a task to write a generic routine that acts on any entity set with common propertie(s).

public static class ObjectSetExtensions
{
public static int IdByName<T>(this ObjectSet<T> set, string name) where T : class
{
int id = set.ToList()
.Where(c => c.MemberValue<string>("name") == name)
.Select(c => c.MemberValue<int>("id"))
.FirstOrDefault();
if (id != default(int))
{
return id;
}
else
{
throw new Exception(string.Format("The {0} named {0} does not exist.", typeof(T).Name, name));
}
}
}

Sunday, May 6, 2012

Minimal Code to Demonstrate Entity Framework Code First

Before compiling this, to ensure your project has a reference to a version of Entity Framework that supports code first development, execute the following nuget command:

install-package EntityFramework

The following code listing contains:
  • POCO
  • Context
  • Static method to add an item
  • Application configuration (XML)
  • Unit test (not required)

using System;
using System.Data.Entity;
namespace EFCodeFirst
{
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model : DbContext
{
public DbSet<Thing> Things { get; set; }
}
public class AddThing
{
public static void Main()
{
var thing = new Thing { Name = @"Something" };
using (var model = new Model())
{
model.Things.Add(thing);
model.SaveChanges();
}
Console.WriteLine("saved changes");
Console.ReadLine();
}
}
}
view raw AddThing.cs hosted with ❤ by GitHub
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter
value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
view raw App.config hosted with ❤ by GitHub
using System.Data.SqlClient;
namespace EFCodeFirst.Test
{
public class AddThingTest
{
public void MainTest()
{
AddThing.Main();
int? rowCount = null;
using (var connection = new SqlConnection(@"Data Source=.\musicdb; Integrated Security=True;"))
using (var command = new SqlCommand("select count(*) from [EFCodeFirst.Model].dbo.Things", connection))
{
connection.Open();
try
{
rowCount = command.ExecuteScalar() as int?;
}
finally
{
connection.Close();
}
}
Assert.IsNotNull(rowCount);
Assert.IsTrue(rowCount > 0);
}
}
}
view raw Test.cs hosted with ❤ by GitHub

Friday, May 4, 2012

PowerShell script to delete files from a directory that are more than a given number of days old.

This PowerShell
  • deletes files created more than 3 days ago.
  • logs the files it deletes.
$d = "C:\db\backup"
$today = get-date -uformat "%Y_%m_%d"
$log = "C:\db\backup\" + "Purge_" + $today + ".log"
$a = Get-ChildItem $d -recurse
foreach($x in $a)
{
$y = ((Get-Date) - $x.CreationTime).Days
if ($y -gt 3 -and $x.PsISContainer -ne $True)
{
$deleted = "Deleting - " + $x.fullname + " - Last Write Time - " + $x.LastWriteTime
add-content $log -value $deleted
$x.Delete()
}
}
view raw gistfile1.txt hosted with ❤ by GitHub