Prism For Windows Runtime Is Out
Prism for the Windows Runtime and the associated AdventureWorks Shopper reference implementation is now available on the Windows Dev Center.
You can read all about it on Blaine Wastell’s blog.
Brian Noyes has also released a Pluralsight course: http://tinyurl.com/prismrtcoursesummary
Feedback Requested: Usability Of The Remarks Section In Reference Topics
Microsoft is planning to expand the Remarks section of selected types in the .NET Framework Class Library to provide detailed usage information and code examples. (For an example, see the Remarks section for the System.String class.) In the current design, the Remarks section isn’t easily discoverable, because member tables take up a lot of screen real estate.
Some alternate page designs are proposed to address this problem.
Click here to provide your feedback.
Windows 8 SDK Customer Satisfaction Survey
Windows 8 introduces a number of innovations in the way information is delivered to developers. Microsoft would like to know how well these are working for you, and where they can make further changes to improve your experience.
To review the site before you complete the survey, visit the Windows 8 Dev Center. In particular, have a look at the section called Learn to build Metro style apps.
A few questions in the survey are about about how the Windows 8 site experience compares to the iOS and Android sites. If you aren’t an experienced iOS or Android developer, feel free to skip these parts. But, if you’ve made apps for those platforms, or if you’d like to compare site features based on just a browse through those sites, Microsoft would like to hear your opinion.
The survey will be available here until July 27, 2012.
Testing for Continuous Delivery with Visual Studio 2012 RC
Microsoft Patterns & Practices has released a book with guidance on Testing for Continuous Delivery with Visual Studio 2012 RC.
The book and its content can be found both in the MSDN site and the CodePlex site.
I’m deeply honored to have been part of the review panels.
Hydrating Objects With Expression Trees – Part III
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(), DateTimeOffset.Now, Guid.NewGuid() } ).ToArray();
The data bellow shows the time (in seconds) for different runs for different values of ObjectCount (in the same machine with approximately the same load) as well as it’s availability for different version of the .NET Framework and the C# programming language:
10000 | 100000 | 1000000 | Valid for | ||||||||
Setup | Hydrate | Total | Setup | Hydrate | Total | Setup | Hydrate | Total | Framework version | C# Version | |
Activation and Reflection setter | 0.060 | 0.101 | 0.161 | 0.055 | 0.736 | 0.791 | 0.054 | 6.822 | 6.876 | 1.0, 1.1, 2.0, 3.5, 4.0 | 1.0, 2.0, 3.0, 4.0 |
Activation and Expression Tree setter | 0.300 | 0.003 | 0.303 | 0.313 | 0.049 | 0.359 | 0.293 | 0.578 | 0.871 | 4.0 | none |
Member Initializer | 0.035 | 0.001 | 0.036 | 0.039 | 0.027 | 0.066 | 0.041 | 0.518 | 0.559 | 3.5, 4.0 | 3.0, 4.0 |
These values will vary with the number of the objects being hydrated and the number of its properties, but the method using the Member Initializer will be the most performant.
Code samples for this series of posts (and the one about object dumping with expression trees) can be found on my MSDN Code Gallery: Dump And Hydrate Objects With Expression Trees
TechDays 2010: What’s New On C# 4.0
I would like to thank those that attended my session at TechDays 2010 and I hope that I was able to pass the message of what’s new on C#.
For those that didn’t attend (or did and want to review it), the presentation can be downloaded from here.
Code samples can be downlaoded from here.
Here’s a list of resources mentioned on the session:
- The evolution of C#
- Covariance and contravariance
- Named and optional arguments
- Dynamic programming
- COM Interop Improvements
- Conclusion
C# 4.0: COM Interop Improvements
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 another way of passing value parameters.
Specifically for COM methods, the compiler allows to declare the method call passing the arguments by value and will automatically generate the necessary temporary variables to hold the values in order to pass them by reference and will discard their values after the call returns. From the point of view of the programmer, the arguments are being passed by value.
This method call:
object fileName = "Test.docx"; object missing = Missing.Value; document.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
can now be written like this:
document.SaveAs("Test.docx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
And because all parameters that are receiving the Missing.Value value have that value as its default value, the declaration of the method call can even be reduced to this:
document.SaveAs("Test.docx");
Dynamic Import
Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object form the context of the call, but has to explicitly perform a cast on the returned values to make use of that knowledge. These casts are so common that they constitute a major nuisance.
To make the developer’s life easier, it is now possible to import the COM APIs in such a way that variants are instead represented using the type dynamic which means that COM signatures have now occurrences of dynamic instead of object.
This means that members of a returned object can now be easily accessed or assigned into a strongly typed variable without having to cast.
Instead of this code:
((Excel.Range)(excel.Cells[1, 1])).Value2 = "Hello World!";
this code can now be used:
excel.Cells[1, 1] = "Hello World!";
And instead of this:
Excel.Range range = (Excel.Range)(excel.Cells[1, 1]);
this can be used:
Excel.Range range = excel.Cells[1, 1];
Indexed And Default Properties
A few COM interface features are still not available in C#. On the top of the list are indexed properties and default properties. As mentioned above, these will be possible if the COM interface is accessed dynamically, but will not be recognized by statically typed C# code.
No PIAs – Type Equivalence And Type Embedding
For assemblies indentified with PrimaryInteropAssemblyAttribute, the compiler will create equivalent types (interfaces, structs, enumerations and delegates) and embed them in the generated assembly.
To reduce the final size of the generated assembly, only the used types and their used members will be generated and embedded.
Although this makes development and deployment of applications using the COM components easier because there’s no need to deploy the PIAs, COM component developers are still required to build the PIAs.
C# 4.0: Dynamic Programming
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 reflection, but its main goal was never to be a dynamic programming environment and there were some features missing. The DLR is built on top of the CLR and adds those missing features to the .NET platform.
The Dynamic Language Runtime is the core infrastructure that consists of:
-
Expression Trees
The same expression trees used in LINQ, now improved to support statements.
-
Dynamic Dispatch
Dispatches invocations to the appropriate binder.
-
Call Site Caching
For improved efficiency.
Dynamic languages and languages with dynamic capabilities are built on top of the DLR. IronPython and IronRuby were already built on top of the DLR, and now, the support for using the DLR is being added to C# and Visual Basic. Other languages built on top of the CLR are expected to also use the DLR in the future.
Underneath the DLR there are binders that talk to a variety of different technologies:
-
.NET Binder
Allows to talk to .NET objects.
-
JavaScript Binder
Allows to talk to JavaScript in SilverLight.
-
IronPython Binder
Allows to talk to IronPython.
-
IronRuby Binder
Allows to talk to IronRuby.
-
Allows to talk to COM.
Whit all these binders it is possible to have a single programming experience to talk to all these environments that are not statically typed .NET objects.
The dynamic Static Type
Let’s take this traditional statically typed code:
Calculator calculator = GetCalculator(); int sum = calculator.Sum(10, 20);
Because the variable that receives the return value of the GetCalulator method is statically typed to be of type Calculator and, because the Calculator type has an Add method that receives two integers and returns an integer, it is possible to call that Sum method and assign its return value to a variable statically typed as integer.
Now lets suppose the calculator was not a statically typed .NET class, but, instead, a COM object or some .NET code we don’t know he type of. All of the sudden it gets very painful to call the Add method:
object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 }); int sum = Convert.ToInt32(res);
And what if the calculator was a JavaScript object?
ScriptObject calculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res);
For each dynamic domain we have a different programming experience and that makes it very hard to unify the code.
With C# 4.0 it becomes possible to write code this way:
dynamic calculator = GetCalculator(); int sum = calculator.Add(10, 20);
You simply declare a variable who’s static type is dynamic. dynamic is a pseudo-keyword (like var) that indicates to the compiler that operations on the calculator object will be done dynamically.
The way you should look at dynamic is that it’s just like object (System.Object) with dynamic semantics associated. Anything can be assigned to a dynamic.
dynamic x = 1; dynamic y = "Hello"; dynamic z = new List<int> { 1, 2, 3 };
At run-time, all object will have a type. In the above example x is of type System.Int32.
When one or more operands in an operation are typed dynamic, member selection is deferred to run-time instead of compile-time. Then the run-time type is substituted in all variables and normal overload resolution is done, just like it would happen at compile-time.
The result of any dynamic operation is always dynamic and, when a dynamic object is assigned to something else, a dynamic conversion will occur.
Code | Resolution | Method |
---|---|---|
double x = 1.75;
double y = Math.Abs(x);
|
compile-time |
double Abs(double x) |
dynamic x = 1.75;
dynamic y = Math.Abs(x);
|
run-time |
double Abs(double x) |
dynamic x = 2;
dynamic y = Math.Abs(x);
|
run-time |
int Abs(int x) |
The above code will always be strongly typed. The difference is that, in the first case the method resolution is done at compile-time, and the others it’s done ate run-time.
IDynamicMetaObjectObject
The DLR is pre-wired to know .NET objects, COM objects and so forth but any dynamic language can implement their own objects or you can implement your own objects in C# through the implementation of the IDynamicMetaObjectProvider interface. When an object implements IDynamicMetaObjectProvider, it can participate in the resolution of how method calls and property access is done.
The .NET Framework already provides two implementations of IDynamicMetaObjectProvider:
-
DynamicObject : IDynamicMetaObjectProvider
The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.
-
ExpandoObject : IDynamicMetaObjectProvider
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember, instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
C# 4.0: Alternative To Optional Arguments
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 such pattern in their Create methods, since version 2.0:
XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Auto; XmlReader.Create("file.xml", settings);
With this pattern, you don’t have to maintain a long list of overloads and any default values for properties of XmlReaderSettings (or XmlWriterSettings for XmlWriter.Create) can be changed or new properties added in future implementations that won’t break existing compiled code.
You might now argue that it’s too much code to write, but, with object initializers added in C# 3.0, the same code can be written like this:
XmlReader.Create("file.xml", new XmlReaderSettings { ValidationType = ValidationType.Auto });
Looks almost like named and optional arguments, doesn’t it? And, who knows, in a future version of C#, it might even look like this:
XmlReader.Create("file.xml", new { ValidationType = ValidationType.Auto });
Recent Comments