Site: http://msmvps.com/blogs/paulomorgado/archive/tags/C_2300_/default.aspx Link: http://msmvps.com/blogs/paulomorgado/rss.aspx?Tags=C_2300_&AndTags=1
by Paulo Morgado via Paulo Morgado : C# on 8/18/2010 1:27:14 AM
To finalize this series on object hydration, I’ll show some performance comparisons between the different methods of hydrating objects. For the purpose of this exercise, I’ll use this class: class SomeType { public int Id { get; set; } public string Name { get; set; } public DateTimeOffset CreationTime { get; set; } public Guid UniqueId { get; set; } } and this set of data: var data = ( from i in Enumerable.Range(1, ObjectCount) select new object[] { i, i.ToString( ...
[ read more ]
by Paulo Morgado via Paulo Morgado : C# on 8/16/2010 10:19:50 PM
In my previous post I showed how to hydrate objects by creating instances and setting properties in those instances. But, if the intent is to hydrate the objects from data, why not having an expression that does just that? That’s what the member initialization expression is for. To create such an expression we need the constructor expression and the property binding expressions: var properties = objectType.GetProperties(); var bindings = new MemberBinding[properties.Length]; var valuesArray ...
by Paulo Morgado via Paulo Morgado : C# on 8/16/2010 12:55:31 AM
After my post about dumping objects using expression trees, I’ve been asked if the same could be done for hydrating objects. Sure it can, but it might not be that easy. What we are looking for is a way to set properties on objects of an unknown type. For that, we need to generate methods to set each property of the objects. Such methods would look like this expression: Expression<Action<object, object>> expression = (o, v) => ((SomeType)o).Property1 = (PropertyType)v; Unfor ...
by Paulo Morgado via Paulo Morgado : C# on 8/6/2010 12:40:39 AM
Following my last post, I received lots of enquiries about how got to master the creation of expression trees. The answer is: .NET Reflector On that post I needed to to generate an expression tree for this expression: Expression<Func<object, object>> expression = o => ((object)((SomeType)o).Property1); I just compiled that code in Visual Studio 2010, loaded the assembly in .NET Reflector, and disassembled it to C# without optimizations (View –> Options –> Disassembler –& ...
by Paulo Morgado via Paulo Morgado : C# on 8/3/2010 12:36:00 AM
No. I’m not proposing to get rid of objects. A colleague of mine was asked if I knew a way to dump a list of objects of unknown type into a DataTable with better performance than the way he was using. The objects being dumped usually have over a dozen of properties, but, for the sake of this post, let’s assume they look like this: class SomeClass{ public int Property1 { get; set; } public long Property2 { get; set; } &nbs ...
by Paulo Morgado via Paulo Morgado : C# on 8/2/2010 12:06:26 AM
In a previous post, I went through how arrays have are covariant in relation to the type of its elements, but not safely covariant. In the following example, the second assignment is invalid at run time because, although the type of the objectArray variable is array of object, the real type of the array is array of string and an object cannot be assigned to a string. object[] objectArray = new string[] { "string 1", "string 2" }; objectArray[0] = "string 3"; objec ...
by Paulo Morgado via Paulo Morgado : C# on 4/19/2010 12:59:01 AM
Dynamic resolution as well as named and optional arguments greatly improve the experience of interoperating with COM APIs such as Office Automation Primary Interop Assemblies (PIAs). But, in order to alleviate even more COM Interop development, a few COM-specific features were also added to C# 4.0. Ommiting ref Because of a different programming model, many COM APIs contain a lot of reference parameters. These parameters are typically not meant to mutate a passed-in argument, but are simply an ...
by Paulo Morgado via Paulo Morgado : C# on 4/18/2010 6:45:29 PM
The major feature of C# 4.0 is dynamic programming. Not just dynamic typing, but dynamic in broader sense, which means talking to anything that is not statically typed to be a .NET object. Dynamic Language Runtime The Dynamic Language Runtime (DLR) is piece of technology that unifies dynamic programming on the .NET platform, the same way the Common Language Runtime (CLR) has been a common platform for statically typed languages. The CLR always had dynamic capabilities. You could always use re ...
by Paulo Morgado via Paulo Morgado : C# on 4/18/2010 1:11:03 AM
Like I mentioned in my last post, exposing publicly methods with optional arguments is a bad practice (that’s why C# has resisted to having it, until now). You might argument that your method or constructor has to many variants and having ten or more overloads is a maintenance nightmare, and you’re right. But the solution has been there for ages: have an arguments class. The arguments class pattern is used in the .NET Framework is used by several classes, like XmlReader and XmlWriter that use ...
by Paulo Morgado via Paulo Morgado : C# on 4/16/2010 1:07:29 AM
As part of the co-evolution effort of C# and Visual Basic, C# 4.0 introduces Named and Optional Arguments. First of all, let’s clarify what are arguments and parameters: Method definition parameters are the input variables of the method. Method call arguments are the values provided to the method parameters. In fact, the C# Language Specification states the following on §7.5: The argument list (§7.5.1) of a function member invocation provides actual values or variab ...
by Paulo Morgado via Paulo Morgado : C# on 4/14/2010 11:50:42 PM
In my last post, I went through what is variance in .NET 4.0 and C# 4.0 in a rather theoretical way. Now, I’m going to try to make it a bit more down to earth. Given: class Base { } class Derived : Base { } Such that: Trace.Assert(typeof(Base).IsClass && typeof(Derived).IsClass && typeof(Base).IsGreaterOrEqualTo(typeof(Derived))); Covariance interface ICovariantIn<out T> { } Trace.Assert(typeof(ICovariantIn<Base>).IsGreaterOrEqual ...
by Paulo Morgado via Paulo Morgado : C# on 4/13/2010 1:25:58 AM
C# 4.0 (and .NET 4.0) introduced covariance and contravariance to generic interfaces and delegates. But what is this variance thing? According to Wikipedia, in multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.(*) But what does this have to do with C# or .NET? In type theory, a the type T is greater (>) than type S if S is a s ...
by Paulo Morgado via Paulo Morgado : C# on 4/12/2010 1:08:25 AM
The first release of C# (C# 1.0) was all about building a new language for managed code that appealed, mostly, to C++ and Java programmers. The second release (C# 2.0) was mostly about adding what wasn’t time to built into the 1.0 release. The main feature for this release was Generics. The third release (C# 3.0) was all about reducing the impedance mismatch between general purpose programming languages and databases. To achieve this goal, several functional programming features were added to ...
by Paulo Morgado via Paulo Morgado : C# on 4/9/2010 1:32:53 AM
On my last post, I introduced the PredicateEqualityComparer and a Distinct extension method that receives a predicate to internally create a PredicateEqualityComparer to filter elements. Using the predicate, greatly improves readability, conciseness and expressiveness of the queries, but it can be even better. Most of the times, we don’t want to provide a comparison method but just to extract the comaprison key for the elements. So, I developed a SelectorEqualityComparer that takes a method ...
by Paulo Morgado via Paulo Morgado : C# on 4/8/2010 1:18:04 AM
Today I was writing a LINQ query and I needed to select distinct values based on a comparison criteria. Fortunately, LINQ’s Distinct method allows an equality comparer to be supplied, but, unfortunately, sometimes, this means having to write custom equality comparer. Because I was going to need more than one equality comparer for this set of tools I was building, I decided to build a generic equality comparer that would just take a custom predicate. Something like this: public class Predic ...
by Paulo Morgado via Paulo Morgado : C# on 3/19/2010 2:34:00 AM
C# 4.0 introduces a new type: dynamic. dynamic is a static type that bypasses static type checking. This new type comes in very handy to work with: The new languages from the dynamic language runtime. HTML Document Object Model (DOM). COM objects. Duck typing … Because static type checking is bypassed, this: dynamic dynamicValue = GetValue(); dynamicValue.Method(); is equivalent to this: object objectValue = GetValue(); objectValue .GetType() .InvokeMember( ...
by Paulo Morgado via Paulo Morgado : C# on 1/27/2010 2:22:00 AM
Today, my friend Nuno was writing some code to get the PropertyInfos of a class implementation of an interface. Given this interface: public interface ISomeInterface { int IntProperty { get; set; } string StringProperty { get; } void Method(); } and this class: public class SomeClass : ISomeInterface { int ISomeInterface.IntProperty { get; set; } public int IntProperty { get; private set; } public string StringProperty { get; private set; } public void Method( ...
by Paulo Morgado via Paulo Morgado : C# on 1/19/2010 12:26:00 AM
Visual Studio uses Publicize to create accessors public for private members and types of a type. But when you try to set elements of a private array of elements of a private type, things get complicated. Imagine this hypothetic class to test:public static class MyClass { private static readonly MyInnerClass[] myArray = new MyInnerClass[10]; public static bool IsEmpty() { foreach (var item in myArray) { if ((item != null) && (!string.IsNullOrEmpty( ...
by Paulo Morgado via Paulo Morgado : C# on 10/13/2009 12:51:43 AM
LINQ brought developers a very user friendly and domain independent style of writing queries. The fact that the way queries are written is domain independent doesn’t mean that any query will compile the same way or even run the same way. You’ll always need to know how the provider will behave. LINQ To Objects, for example, will compile queries as a Func<> delegate and the query methods will return IEnumerable(T) implementations. On the other hand, LINQ To SQL will compile queries as ...
by Paulo Morgado via Paulo Morgado : C# on 9/18/2009 12:03:12 AM
Some time ago I needed to have the validationKey of the machineKey element of an ASP.NET application changed and found out that ASP.NET doesn’t provide a command-line tool (or any other) to do this. Looking around I found several applications and code samples to do it, but to have a system administrator do this I needed to test and document the application and it was to much work for such task. I’ve always been a supporter of the idea of PowerShell but I never used it my self. Just because I a ...
by Paulo Morgado via Paulo Morgado : C# on 5/17/2009 11:39:51 PM
It’s finally out! The LINQ Com C# (LINQ With C#) book that Luís and I wrote is out. Well, mostly Luís than I. This book, published by FCA, is targeted at anyone that already knows C# 2.0 and wants to know learn the new features introduced with C# 3.0 that made possible LINQ (Language INtegrated Query). The examples in the book are written in C#, but Visual Basic get be get from the book’s site. Title: LINQ Com C# Authors: L ...
by Paulo Morgado via Paulo Morgado : C# on 12/3/2008 1:17:00 AM
If you were able to attend this session at PDC or Tech-Ed EMEA Developers, you were presented with a first class presentation of the future of C#, presented, respectively, by Anders Hejlsberg and Mads Torgersen. For the near future (.NET 4.0) C# will have: Dynamically Typed Objects Optional and Named Parameters Improved COM Interoperability Co- and Contra-variance A preview of the compiler as a service was shown, but that’s not for the .NET 4.0 / Visual Studio 2010 timeframe. Probably, not ...
by Paulo Morgado via Paulo Morgado : C# on 8/28/2008 10:41:36 PM
Clone Detective is a tool that integrates with Visual Studio and uses the ConQAT (Continuous Quality Assessment Toolkit) to analyze C# projects and search for duplicated source code. Watch the videos and see if this is the tool you were looking for. ...
by Paulo Morgado via Paulo Morgado : C# on 8/11/2008 12:47:50 AM
In the past I presented another possible use for the using keyword: as hints on LINQ. I’ve been giving some thought about this lately and refined my proposal. var q = from person in personCollection using MyEnumerableExtensions group person by person.LastName into g using new MyOtherComparer() orderby g.Key using new MyComparer() select person; The above query would be converted to: var q = MyEnumerableExtensions.OrderBy<string, Person>( MyEnumerableEx ...
by Paulo Morgado via Paulo Morgado : C# on 8/10/2008 11:27:22 PM
C# 3.0 introduced object and collection initializers. It is now easier to initialize objects or collections: var person = new Person { FirstName = "Paulo", LastName = "Morgado" }; var persons = new List<Person> { new Person { FirstName = "Paulo", LastName = "Morgado" }, new Person { FirstName = "Luís", LastName = "Abreu" } }; var personDirectory = new Dictionary<string, Person> { { "Lisboa", new P ...
by Paulo Morgado via Paulo Morgado : C# on 8/4/2008 12:23:00 AM
(This was pointed out to me by Frans Bouma and explained by Jon Skeet) Imagine you have this set of classes:public class A { public virtual string P { get { return "A"; } } } public class B : A { } public class C : B { public override string P { get { return "C"; } } } And this class:public static class Reporter { public static void Report<T>(T target, Expression<Func<T, string>> expression) { Consol ...
by Paulo Morgado via Paulo Morgado : C# on 4/22/2008 12:35:00 AM
Note: Code in italics is not actual C# 3.0 syntax. Local Variable Type Inference C# 3.0 brought us local variable type inference mainly because of LINQ. The output of a query can vary from an IEnumerable<T> or an IQueryable<T> to a single instance of T where T can even be a projection which means that its type is an anonymous type. Take the following query as an example:from p in persons select new { Name = p.FirstName + " " + p.LastName, Age = p.Age }; If persons is an IEn ...
by Paulo Morgado via Paulo Morgado : C# on 10/7/2007 10:56:00 PM
Visual Studio's Unit Test generator generates a call to Assert.Inconclusive but, usually generates a call to another method of the Assert class. I find that very annoying because, some times, this makes the test fail instead of being reported as inconclusive. To comment out these extra calls to Assert methods, the following regular expression can be used: Find what: {:b*}{Assert\.~(Inconclusive).*\n:b*Assert\.Inconclusive} Replace with: \1//\2 Check out the complete list. ...
by Paulo Morgado via Paulo Morgado : C# on 7/8/2007 11:31:35 PM
I've been searching high and low for a TypeConverter for Types and only found private or internal implementations. It wasn't a hard task, but I think that the .NET Framework should provide one out of the box. Here is the one I wrote: /// <summary> /// Provides a type converter to convert <see cref="T:System.Type"/> objects to and from various other representations. /// </summary> public class TypeTypeConverter : System.ComponentModel.TypeConverter { /// &l ...
by Paulo Morgado via Paulo Morgado : C# on 6/18/2007 11:59:04 PM
A discussion has started in Eric Gunnerson's blog around the subject of To m_ or no to m_, that is the question.... A lot has been said on this (here is my opinion), but Peter Ritchie has a well written post on this. ...
by Paulo Morgado via Paulo Morgado : C# on 5/23/2007 11:29:32 PM
Following up on a previous post, this time I'll give you my naming conventions for partial class files. There are two main reasons for me to break a class definition into more than one file. The main one is when I have inner classes and the other is when the file is getting too big. How should I name the files? The usual tendency is to use a “.” as separator. This looks nice until you came across something like this: public class MyComponent { private class Activation &n ...
by Paulo Morgado via Paulo Morgado : C# on 5/23/2007 10:27:20 PM
You can download here. Before you get too excited, according to Tom Hollander, this is really just a maintenance release addressing a small number of issues discovered since the release of 3.0. Here is a summary of the main changes: Policy Injection Application Block The default Remoting Policy Injector can now be replaced with alternative interception mechanisms via configuration without modifying the application block code Call Handler attributes are now honored correctly when ...
by Paulo Morgado via Paulo Morgado : C# on 5/20/2007 10:28:43 PM
I'm a firm supporter of coding conventions (at least of my coding conventions). Software factories [^] [^] [^] and other code generation tools have been taking care of writing the tedious (and, sometimes, ugly) code but, at some point, some code must be written and read by human developers. That's why (in my opinion) the way the code is written is as much important as the language it is written in. There are several resources about coding conventions for the .NET framework: Naming ...
by Paulo Morgado via Paulo Morgado : C# on 5/14/2007 10:28:19 PM
Looks like I was way wrong in here and here. I had thought that from the top of my head because I tried to use Array.IndexOf as an extension method and was surprised to see that it wasn't an extension method. It presented a good opportunity to play around with extension methods, so I wrote a class to extend the Array class: public static class ArrayUtils { public static int IndexOf<T>(this T[] array, T value) { &nbs ...
by Paulo Morgado via Paulo Morgado : C# on 5/13/2007 10:30:25 PM
I like to always qualify all instance fields with the this keyword. this.someInstanceField; this.GetType(); I would like to do the same for static fields, but there's no keyword for that. I've been thinking about this for a while and I think I found a solution: the static keyword. typeof(); // no need for the static keyword static.someStaticField; ...
by Paulo Morgado via Paulo Morgado : C# on 5/13/2007 6:51:48 PM
UPDATE: Extension methods Extension methods are a feature of the new C# language specification (also available in Visual Basic [^] [^]): This new feature should be used in existing classes like the Array class by making the folowing methods extension methods: public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T>(this T[] array); public static int BinarySearch<T>(this T[] array, T value); public static int BinarySearch(this Array array, object value ...
by Paulo Morgado via Paulo Morgado : C# on 5/13/2007 6:41:09 PM
UPDATE: Extension methods Extension methods are a feature of the new C# language specification (also available in Visual Basic [^] [^]): This new feature should be used in existing classes like the String class by making the folowing methods extension methods: public static int Compare(this string strA, string strB); public static int Compare(this string strA, string strB, bool ignoreCase); public static int Compare(this string strA, string strB, System.StringComparison comparisonType); public ...
by Paulo Morgado via Paulo Morgado : C# on 4/26/2007 11:50:50 PM
Yesterday I had to build a custom message encoder to be able to call a legacy POX service with iso-8859-1 encoding. It turned out that the service had another surprise to me: it needs an HTTP user-agent header. It's something quite simple to accomplish with WCF. All it's needed is to add the required header to the HTTP request message property of the request message. Something like this: HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty(); httpRequ ...
by Paulo Morgado via Paulo Morgado : C# on 4/15/2007 11:14:30 PM
In his show about Scenario Based Architecture Validation, Ron Jacobs talks with Dragos Manolescu (Architecture Evaluation in Practice) about how difficult it is to evaluate and validate an architecture. There are a few tools that can help you validate the architecture of your application or framework, though. Here are two of them. Lattix LDM 3.0 This tool from Lattix uses Dependency Structure Matrix (DSM) to communicate the architecture, identify critical dependencies, and define rules ...
by Paulo Morgado via Paulo Morgado : C# on 4/1/2007 10:59:13 PM
Master pages, in the Web Client Software Factory, act as equivalents to the Shell in the Smart Client Software Factory but, unlike their smart client counterpart, they don't benefit from dependency injection. I've just cooked up a quick way to add dependency injection to master pages in the Web Client Software Factory and, thus, add a Presenter (with the associated Controller). This can be done just by adding a few lines of code to the Microsoft.Practices.CompositeWeb.WebClie ...
by Paulo Morgado via Paulo Morgado : C# on 3/25/2007 8:58:31 PM
There are two uses for the C# using keyword: The using statement: Defines a scope, outside of which an object or objects will be disposed. using (TransactionScope transactionScope = new TransactionScope()) { // ... } The using directive: The using directive has two uses: To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace: using System.Text; To create an alias for a namespace or a type: using Text = System.Text; ...
by Paulo Morgado via Paulo Morgado : C# on 2/17/2007 11:51:15 PM
I'm not a big fan of Test Driven Development (TDD), but I love Unit Testing. But to be productive on unit testing I need a good framework for Mock Objects. I can't expect to be productive and have to build a lot of mock classes to test other classes. And, who tests the mock classes? Mock objects simulate the behavior of real objects when they are difficult or impossible to obtain. I've been testing a few mock frameworks and this is my opinion (*) on the ones I've tested. NMock I've bee ...
by Paulo Morgado via Paulo Morgado : C# on 2/5/2007 11:04:28 PM
Again, the lack of IIdentity in the API. With identities like the WindowsIdentity, the user's username (the name property) has no use for the system. The important part is the user's token. If you would follow the path (using Reflector) from the call to Roles.GetRolesForUser() until the reply from WindowsTokeRoleProvider.GetRolesForUser(string username), you would see the following steps: System.Web.Security.Roles.GetRolesForUser() gets the current user's username from the curren ...
by Paulo Morgado via Paulo Morgado : C# on 11/4/2006 11:15:34 PM
The application I'm currently working on has a rather complex UI. It's something like two tabbed work spaces and an outlook-like work space, that make one workspace by itself, that can have several instances inside another tabbed workspace, that can have several instances inside another tabbed workspace. Imagine something like Visual Studio, inside a tab. Each work space is controlled by its own work item and the same goes to every smart part. With a UI like this, the work item activation s ...
by Paulo Morgado via Paulo Morgado : C# on 10/29/2006 10:57:33 PM
As I understand it, the MVP (Model/View/Presenter) design pattern states that all presentation decisions are the Presenter's responsibility. In the CAB world, this should include the Smart Part Info. But the IWorkspace interface only allows you to provide the Smart Part Info (a class that implements the ISmartPartInfo interface and each work space uses a specific one), or the the smart part (the View in the MVP design pattern) should know what information to provide to the work space it lives in ...
by Paulo Morgado via Paulo Morgado : C# on 10/22/2006 9:45:52 PM
For those who don't know, the ManagedObjectCollection registers its elements using the objects running type as part of the key. Recently, I had the need to add and retrieve a component to the WorkItem's Items collection independently of its running. I only wanted to retrieve the component (using a ComponentDependency) with a specified name. Needless to say that I couldn't, because I was trying to retrieve an object, and that was not the running type of the object ad ...
by Paulo Morgado via Paulo Morgado : C# on 10/17/2006 10:06:43 PM
Yesterday a CodePlex project was created for the WebBrowserControl for the .NET Framework 2.0. I have been meaning to start this project for a long time. Let's see how it goes. Share this post: email it! | bookmark it! | digg it! | live it! ...
by Paulo Morgado via Paulo Morgado : C# on 10/10/2006 11:37:52 PM
Anyone who has ttried to add a service implemented through Remoting to the WorkItem's services collection was sadly surprised that it can't be done. But why? When we use the following code: WorkItem.Services.Add<IServiceContract>(serviceInstance); It comes to something like this:if (!typeof(IServiceContract).IsAssignableFrom(serviceInstance.GetType()) throw new ArgumentException(); And how do we solve this problem? easy: generics. All we need to do is make some changes to the Se ...
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.