Posts

Showing posts from November, 2012

C# Generic Lambda Comparer

public class LambdaComparer<T> : IComparer<T> { public enum Direction { Asc = 1, Desc = -1 } private readonly Comparison<T> _comparison; public LambdaComparer(Comparison<T> comparison) { _comparison = comparison; } int IComparer<T>.Compare(T x, T y) { return _comparison(x, y); } public static LambdaComparer<T> IgnoreSortComparer() { return IgnoreSortComparer(Direction.Asc); } public static LambdaComparer<T> IgnoreSortComparer(Direction direction) { return new LambdaComparer<T>((x, y) => x.Equals(y) ? 0 : ( int )direction); } } public class Data { public int X; public int Y; } [Test] public void TestLambdaComparer() { var data = new Data[] { new Data() { X = 1, Y = 1 }, new Data() { X = 3, Y = 2 }, new Data() { X = 5, Y = 3 }, new Data() { X = 2, Y = 4 }, new Data() { X = 4, Y = 5 } }; Console.WriteLine(&quo

C# string parameter replacement with simple date arithmetic

[Test] public void FindAndReplace() { var sql = @" SELECT * FROM Table_{@AsOf} WHERE Date='{@AsOf-1}' "; Console.WriteLine(" BEFORE: {0} ", sql); var asOf = DateTime.Today; //(?: )+ means repeat the inner groups var regexExpr = @" (?:{@(?<parameter>\w+)(?<operation>\S)?(?<number>\d+)?})+ "; var regex = new Regex(regexExpr); foreach (Match match in regex.Matches(sql)) { sql = sql.Replace(match.Value, Substitute(match.Value, asOf)); } Console.WriteLine(" AFTER : {0} ", sql); } private string Substitute( string parameterText, DateTime asOf) { var regexExpr = @" {@(?<parameter>\w+)(?<operation>\S)?(?<number>\d+)?} "; var regex = new Regex(regexExpr); var match = regex.Match(parameterText); if (match.Success) { var parameter = match.Groups[" parameter "].Value; if (match.Groups[" operation "].Success &&a

Script to create SqlServer Table, Stored Procedure and View

PRINT ' CREATE TABLE ' GO IF EXISTS ( SELECT * FROM dbo.sysobjects where id = object_id(N' [Table1] ') and OBJECTPROPERTY(id, N' IsUserTable ') = 1) DROP TABLE [ Table 1] GO CREATE TABLE [dbo].[ Table 1]( [Id] [ uniqueidentifier ] NOT NULL , [Name] [ varchar ](50) NULL , [DateUpdated] [ datetime ] NULL , CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( [Id] ) ) GO GRANT SELECT , INSERT , UPDATE , DELETE ON [ Table 1] TO [SampleUser] GO PRINT ' CREATE STORED PROCEDURE ' GO IF EXISTS ( SELECT * FROM dbo.sysobjects where id = object_id(N' [StoredProcedure1] ') and OBJECTPROPERTY(id, N' IsProcedure ') = 1) DROP PROCEDURE [dbo].[StoredProcedure1] GO CREATE PROCEDURE [dbo].[StoredProcedure1] AS SET NOCOUNT ON UPDATE dbo. Table 1 SET [DateUpdated]=GETDATE() GO GRANT EXECUTE ON [StoredProcedure1] TO [SampleUser] GO PRINT ' CREATE VIEW ' GO