Posts

Showing posts from 2012

C# Generic Lambda Comparer

publicclass LambdaComparer<T> : IComparer<T> { publicenum Direction { Asc = 1, Desc = -1 } privatereadonly Comparison<T> _comparison; public LambdaComparer(Comparison<T> comparison) { _comparison = comparison; } int IComparer<T>.Compare(T x, T y) { return _comparison(x, y); } publicstatic LambdaComparer<T> IgnoreSortComparer() { return IgnoreSortComparer(Direction.Asc); } publicstatic LambdaComparer<T> IgnoreSortComparer(Direction direction) { returnnew LambdaComparer<T>((x, y) => x.Equals(y) ? 0 : (int)direction); } }publicclass Data { publicint X; publicint Y; } [Test] publicvoid 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("BEFORE: "+string.Join(",",data.Select(x=>string.Format("{0}={1}",x…

C# string parameter replacement with simple date arithmetic

[Test] publicvoid 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); } privatestring 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 && match.Groups["number"].Success)…

Script to create SqlServer Table, Stored Procedure and View

PRINT 'CREATE TABLE' GOIFEXISTS (SELECT * FROM dbo.sysobjects where id = object_id(N'[Table1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) DROPTABLE [Table1] GOCREATETABLE [dbo].[Table1]( [Id] [uniqueidentifier] NOTNULL, [Name] [varchar](50) NULL, [DateUpdated] [datetime] NULL, CONSTRAINT [PK_Table1] PRIMARYKEYCLUSTERED ( [Id] ) ) GOGRANTSELECT, INSERT, UPDATE, DELETEON [

C# Deserialization and constructor initialization

This is an example how to recreate non serialized member of the class on deserialization.class TestSerialization { [Test] publicvoid Test() { var parent = new Parent(2,3); // serializebyte[] data = SerializationHelper.Serialize(parent); // deserialize var parentCopy = SerializationHelper.Deserialize(data) as Parent; Assert.AreEqual(2, parentCopy.Value1); //confirm that constructor is not called on deserialization Assert.AreEqual(6, parentCopy.Value2); } [Serializable] class Parent { public Parent(intvalue1, intvalue2) { _value1 = value1; _value2 = value2 * 2; //Child object is not serialized, so needs to be recreated on deserialization (see below) _child = new Child() { Value1 = _value1, Value2 = _value2 }; } privateint _value1; privateint _value2; [NonSerialized] private Child _child; publicint Value1 { get { return _child.Value1; } } publicint Value2 { get { return _child.Value2; } } [OnDeserialized] privatevoid Init(Streaming…

C# select data using join to temp table

This is useful if you want to select a lot of data by key and writing IN statement is not efficient (too much data etc..). You load the keys to temp table and then select data using a join.CREATETABLE [dbo].[Table_1]( [Id] [int] NOTNULL, [Name] [varchar](50) NULL)[TestFixture] publicclass TestSelectWithTempTableJoin { [Test] publicvoid Test() { conststring nbTempCreate = @" CREATE TABLE #Ids( Id INT ) "; conststring nbTempDrop = @" DROP TABLE #Ids "; conststring query = @" SELECT * FROM Table_1 t JOIN #Ids temp ON t.Id = temp.Id "; var ids = new List<int>(newint[]{1,3,4}); var rows = new List<KeyValuePair<int, string>>(); var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(); sqlConnectionStringBuilder.DataSource = "(local)"; sqlConnectionStringBuilder.InitialCatalog = "Tests"; sqlConnectionStringBuilder.ApplicationName = "TestTempTabl…

Get email address from active directory username in C#

* Add reference to System.DirectoryServicesstaticstring GetMail(string user) { using (var connection = new DirectoryEntry()) { using (var search = new DirectorySearcher(connection) { Filter = "(samaccountname=" + user + ")", PropertiesToLoad = {"mail"}, }) { return (string) search.FindOne().Properties["mail"][0]; } } }