Posts Tagged ‘C#’
The T4 templates are great tool for use. You can generate literally anything with it with comfort of using any .NET code you have available. Code generation (i.e. POCO classes in EFv4), web service proxies, simple DALs, …, all easily available.
But what if your scenario is one step further? You don’t want to use T4 template to generate i.e. code you’ll later compile into your application, but use the T4 template in runtime to generate result your application will later use (i.e. email based on template). Good news is you can do it, and it’s not hard either.
Easiest way is to start with Preprocessed Text Template file type adding to your solution. The file itself is ordinary T4 template you’re familiar with. But if you build your project the result produced isn’t output from template, but the C#/VB code that produces the result if called. Same result can be done by changing Custom Tool into TextTemplatingFilePreprocessor in Properties window of your current T4 template file.
Then you can create instance of this class (it has same name as your template file), setting up properties, if any and calling TransformText method. Pretty easy, isn’t it?
Most of the time you’re using properties in objects that are also in database. But sometimes you may need to create property in object that’s not in database – it’s used only in this application or it’s there custom logic. Then, if you wanna use it in queries, you’re out. You can use only those properties declared in table, obviously.
But there’s a solution. First, the property has to be created from some other properties, so you’re able to do the same in database. And of course, functions used there needs to be translatable to store language too. This may limit you, but there’s nothing you can do about it, except evaluating query on client side.
Let’s have a table like this:
create table Foo (
ID int primary key,
IsAccepted bit,
IsPaid bit not null,
IsPacked bit not null,
);
And you wanna have property IsReadyToShip, in application. So you create:
public bool IsReadyToShip
{
get { return this.IsAccepted.HasValue && this.IsAccepted && this.IsPaid && this.IsPacked; }
}
But with this property you’re not able to query for all Foos ready to ship. Luckily the solution is pretty easy. First you’ll create expression for this:
public static Expression<Func<Foo, bool>> IsReadyToShipExpression = f => f.IsAccepted.HasValue && f.IsAccepted && f.IsPaid && f.IsPacked;
Then you’l prepare static compiled version of this expression, just for performance reasons, you can compile it in getter everytime too:
protected static Func<Foo, bool> IsReadyToShipFunc = IsReadyToShipExpression.Compile();
And finally the property:
public bool IsReadyToShip
{
get { return IsReadyToShipFunc(this); }
}
Right now we have the same result as before – working property. But because we also have the expressions of the property (and incidentally it’s translatable to store language
), so we can use it for querying. You can use it in an easy way (this is in this case ObjectContext used in Entity Framework):
public IQueryable<Foo> FoosReadyToShip
{
get { return this.Foos.Where(Foo.IsReadyToShipExpression); }
}
Not the shortest way to do it. But if you don’t wanna to write the condition again and again (and lower the maintainability) this is a way to do it.
Probably every developer sometimes heard about the singleton pattern. I’ll be not far from truth that you’re probably writing it like this:
class Foo1
{
private static Foo1 _instance;
public static Foo1 Instance
{
get
{
if (_instance == null)
_instance = new Foo1();
return _instance;
}
}
}
I do it same way. But today I seen little bit different way. It’s using the C# coalesing operator and some C-like magic syntax.
class Foo2
{
private static Foo2 _instance;
public static Foo2 Instance
{
get
{
return _instance ?? (_instance = new Foo2());
}
}
}
Looks cool, isn’t it? On the other hand I’ll probably use the first one, as it’s more readable, at least for me.
Today I was writing some code, where I needed create initially empty array. I wondered if the array[0] vs. array[] { } is the same. Alike with the string concatenation.
Without writing further text. Lines:
private static void Test1()
{
string[] s1 = new string[0];
Console.WriteLine(s1);
}
private static void Test2()
{
string[] s2 = new string[] { };
Console.WriteLine(s2);
}
resulted in this IL:
.method private hidebysig static void Test1() cil managed
{
// Code size 14 (0xe)
.maxstack 1
.locals init ([0] string[] s1)
IL_0000: ldc.i4.0
IL_0001: newarr [mscorlib]System.String
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(object)
IL_000d: ret
} // end of method Program::Test1
.method private hidebysig static void Test2() cil managed
{
// Code size 14 (0xe)
.maxstack 1
.locals init ([0] string[] s2)
IL_0000: ldc.i4.0
IL_0001: newarr [mscorlib]System.String
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(object)
IL_000d: ret
} // end of method Program::Test2
As you (and I) can see, the code is the same (I was kind of expecting that – but what’s better proof than IL?). So you don’t need to worry using the first or the other syntax.
.NET Framework 4 comes with (among others) with two new interfaces. IStructuralEquatable and IStructuralComparable. These are implemented (right now in Beta 1) by Array and Tuple(s).
With this new implementations and StructuralComparisons you can check arrays and tuples for structural equality (or compare these).
object[] o1 = new object[] { 1, "2" };
object[] o2 = new object[] { 1, "2" };
Console.WriteLine(o1.Equals(o2));
Console.WriteLine(o1.Equals(o2, StructuralComparisons.StructuralEqualityComparer));
The code above writes first false and then true. The first one is classic “old-school” Equals. Following line is using new structural comparison, thus the true as result. Neat, isn’t it?
By the way, F# is now using these interfaces too.
Po diskuzi v postu if, else, return jsem si uvědomil, že mám v kapse ještě jeden případ, který je podobně sporný-zajímavý. Tyto dvě konstrukce vídávám a opět v zásadě stejné – nebo ne?
Foo x = (y as Foo);
if (x != null)
{
x...
}
else
{
// <error>
}
resp. (samozřejmě můžeme i přiřadit do x)
if (y is Foo)
{
(y as Foo)...
}
else
{
// <error>
}
Osobně používam druhý způsob, opět spíše pocitově něž pro nějaký fakt (myslím, že z toho is je výsledek mého snažení lépe čitelný). A co vy? Případně máte nějaký argument proč používat jedno nebo druhé?
Občas vidím ve zdrojácích funkce s konstrukcí:
if (<condition>)
{
x = DoSomething(y);
return x;
}
return z;
Což je víceméně to samé jako:
if (<condition>)
{
x = DoSomething(y);
return x;
}
else
{
return z;
}
Osobně používám druhý zápis. Přijde mi o něco přehlednější a explicitnější. Pravděpodobně vliv Delphi/ObjectPascalu.
Je však v těchto zápisech nějaký rozdíl? Nějaký praktický aspekt, který mi uniká?
I was writing some return type from function when I got brilliant dumb idea to start playing with braces, question marks etc.
And I came with some self-competition to write a lot of different characters into a valid type definition (in C#, of course). And simple repeating doesn’t count. But why not to create this as a public competition.
With the short first try I ended up with this:
IEnumerable<KeyValuePair<int, int?>?[,]>
That’s probably not the best what can be done. Do you have better idea? OK, it’s your turn. Use comments. The best – I’m the referee – will get the lolipop.
Sorry for all spanish speaking people if the word in title isn’t right.