October 2006 - Posts
Visual Studio Code Name "Orcas" - October CTP is now available for download!
Like the previous CTP release, this release is only available as a virtual machine in order to provide early access to software under development, without the overhead of updating setup each time. Once setup reaches a state that enables a smooth install and a clean uninstall, you'll start seeing CTP releases you can install yourself.
While you download the 4+ gigs for this release, be sure to review the content found on the download details page: Visual Studio Code Name "Orcas" - October CTP. This is where you'll find instructions for using this virtual machine and details on what's new in this CTP release.
Enjoy!
In Workflow Based projects, we often need to develop custom activities that have the exact set of parameters as an existing method from another class or interface. Since creating a specific activity for each method is a hard work and difficult to maintain, we usually look for a more generic solution.
Windows Workflow Foundation allows you to specify the exact method to use its signature, and can generate a parameter collection according to this signature. A good example for this is the HandleExternalMethodActivity, in which you specify an interface type and a method name, and than the parameters collection refreshes accordingly. Then, you can bind the parameters to values in your workflow.
I’ll take this post as a step-by-step guide to building such an activity: It will guide though creating the Type property, handle the MethodName property, and the dynamic parameters collections. The final activity that this guide builds actually has no logic on it, therefore it does nothing. The reader should implement logic such as calling WCF Services, handling events etc.
You can download a samples project from here.
Building a Dynamic Activity
First, start by creating a new Activity, and change it to inherit from System.Workflow.ComponentModel.Activity instead of inheriting from SequenceActivity. I will use the name DynamicActivity from now on.
public partial class DynamicActivity: Activity
{
...
}
Selecting an Interface Type
Start by creating a new DependencyProperty for the InterfaceType using the appropriate Code Snippet:
public static DependencyProperty TypeProperty =
System.Workflow.ComponentModel.DependencyProperty.Register("Type", typeof(Type), typeof(DynamicActivity));
[Description("Type of the interface")]
[Category("Bursteg")]
[Browsable(true)][Editor(typeof(TypeBrowserEditor), typeof(UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Type Type
{
get { return ((Type)(base.GetValue(DynamicActivity.TypeProperty))); }
set { base.SetValue(DynamicActivity.TypeProperty, value); }
}
Notice the EditorAttribute above the property. This attribute specifies the type of the UI Editor to use when the developer uses the ellipsis button of this property in the property grid. In this case, the attribute sets the TypeBrowserEditor which opend a new .Net Type Selection Dialog that ships with Windows Workflow Foundation.
Filter Selected Types
Usually you don’t want just to select any .Net type in the Class Browser Dialog. Sometimes you want to select only interfaces, exceptions or classes marked with a custom attribute. In order to control which types are displayed in the Class Browser Dialog and can be selected by the developer, the activity should implement the ITypeFilterProvider interface:
public interface ITypeFilterProvider
{
string FilterDescription { get; }
bool CanFilterType(Type type, bool throwOnError);
}
public
partial class DynamicActivity: Activity, ITypeFilterProvider
{
...
#region ITypeFilterProvider Members
public bool CanFilterType(Type type, bool throwOnError)
{
return type.IsInterface;
}
public string FilterDescription
{
get { return "Please choose an interface"; }
}
#endregion
}
Implementing the MethodName Property
While creating the MethodName dependency property I am placing a TypeConverterAttribute above it. The TypeConverter is this case is responsible to populate a list with the method names that are valid for selection. For this example, all method are valid, but one may want to filter methods according to some logic, such as attribute above methods (DataContractAttribute for example).
This approach is similar to the approach Microsoft had taken when implemented CallExternalMethodActivity. They had created a class called PropertyValueProviderTypeConverter which unfortunately marked an internal.
So, first, I will create the MethodName dependency property. Notice the TypeConverter attribute above it:
public
static DependencyProperty MethodNameProperty =
System.Workflow.ComponentModel.DependencyProperty.Register("MethodName", typeof(string), typeof(DynamicActivity));
[
Description("Method name")]
[Category("Bursteg")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[TypeConverter(typeof(MethodPropertyValueProviderTypeConverter))]
public string MethodName
{
get
{
return ((string)(base.GetValue(DynamicActivity.MethodNameProperty)));
}
set
{
base.SetValue(DynamicActivity.MethodNameProperty, value);
}
}
The core method of the MethodPropertyValueProviderTypeConverter which is the implementation of the TypeConverter that populates the methods names of the type can be found in the GetStandardValues method:
public class MethodPropertyValueProviderTypeConverter : TypeConverter
{
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
// Get the activity instance
Activity instance = null;
object[] instances = context.Instance as object[];
if (instances != null && instances.Length > 0)
{
instance = (Activity)instances[0];
}
else
{
instance = (Activity)context.Instance;
}
// Get the value of the type property
Type activityType = instance.GetType();
PropertyInfo interfaceTypeProperty = activityType.GetProperty("Type", typeof(Type));
if (interfaceTypeProperty == null)
{
throw new Exception("Cannot find property Type in activity " + activityType.Name);
}
StringCollection validMethods = new StringCollection();
Type type = (Type)interfaceTypeProperty.GetValue(instance, new object[] { });
if (type != null)
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo mi in methods)
{
// Add custom logic here...
validMethods.Add(mi.Name);
}
}
return new TypeConverter.StandardValuesCollection(validMethods);
}
}
Implementing the Parameters Property
In order to handle the event of MethodName property changes, I will implement a ActivityDesigner. This class is typically handles the visual representation of an Activity, but has the ability to handle and event when an activity changes. Additionally this class can dynamically control the properties displayed in the property grid. As an implementation, I will dynamically add parameters to the activity and finally refresh the property grid.
Adding the designer to the activity:
[
Designer(typeof(DynamicActivityDesigner), typeof(IDesigner))]
public partial class DynamicActivity: Activity, ITypeFilterProvider
{
...
}
Implementing the PreFilterProperties, which allows a designer to add items to the
set of properties that it exposes through a TypeDescriptor:
public
class DynamicActivityDesigner : ActivityDesigner
{
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
DynamicActivity activity = this.Activity as DynamicActivity;
if (activity != null && activity.Type != null && activity.MethodName != null)
{
MethodInfo mi = activity.Type.GetMethod(activity.MethodName);
if (mi != null)
{
//get the parameters and add them as properties
ParameterInfo[] pis = mi.GetParameters();
if (pis != null)
{
foreach (ParameterInfo pi in pis)
{
//add a new parameter
properties[pi.Name] =
new ParameterBindingPropertyDescriptor<DynamicActivity>(
pi.Name,
pi.ParameterType,
new Attribute[] {
new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden),
new BrowsableAttribute(true),
new CategoryAttribute("Parameters"),
new DescriptionAttribute(pi.ParameterType.FullName),
new EditorAttribute(typeof(BindUITypeEditor), typeof (UITypeEditor)) });
}
}
}
}
}
}
All together, we get a custom activity that exposes Type and Method properties. When method is selected, the parameters are dynamically appear on the property grid.
You can download a samples project from here.
Hope you find it useful. I did.
Enjoy!
Looking at the blogs statistics at the Control Panel, you can see both "Views" column and "AggViews" column. Have you ever wondered what does each of them mean actually?
Well, "Views" is the number of times someone viewed a post on the web via a browser, and "AggViews" is the number of times someone viewed the post via the RSS and Atom feeds...

Go see your statistics...
Enjoy!
Some time ago I posted about how to export Power Point slides to .png files. I used it when I wanted to write notes for a presentation and didn't want to use the Power Point editor.
Today I received a comment to this post from Sergei Gorlovetsky, (SRL Group) about another way to export a presentation to Word. The comment I received told how to do this in Office 2003, and I found the way to do it in Power Point 2007:
Just go to the Office Button, select Publish and Create Handouts in Microsoft Office Word.

No doubt, this is much easier. Thanks Sergei Gorlovetsky.
Enjoy!
Yesterday I gave my first talk in front of the Israeli Architects User Group. I had put a lot of effort into this talk (creating the presentation, creating the demos and stuff), and it was all worth it. It seemed that people had a nice time, the atmosphere was great, and a few people came to me after the presentation to tell that is was great. I got back home very satisfied and looking forward to my next talk…
I will go over the main issues of the talk here in this post for those who couldn't come or for those who had forgotten something:
Motivation
We pay a really high price both in development time and maintenance for the was our relational database is designed. When we talk about the conceptual model of our business applications we use terms like entities, inheritance and relations that cannot be naturally expressed in relational databases. So the way we make up for it causes our code (Stored Procedures, Database View or ad hoc queries in our code) to contain "deep knowledge" of the logical schema of the database.
Introducing ADO.Net Entity Framework
The next version of ADO.Net contains a new framework called ADO.Net Entity Framework that helps us to separate the way out application views the data from the way this data is represented in the database. The framework contains a new data model for design time and a run-time engine that supports this model. The framework uses a technology called Client Views which is a mapping technology that maps the conceptual schema (the way our application views the data) to the logical schema. What is important about this technology (and explains its name) is that it is implemented and executed on the client side. This gives each application a separate "view" of the data instead of polluting a central database with application-specific views or stored procedure which are harder to maintain.
Entity Data Model
In order to model the data at a higher level of abstraction we now use a new data model called Entity Data Model. This model is a new Entity Relationship Model that allows us to use all the terms we couldn’t use when we modeled data in the relational database. Key concepts that are used in this model are Entities, that are instances of Entity Types. EntityTypes are a structured record with a key. Entities are grouped into EntitySets.
Mapping Provider
After creating a model, we want to query it and get result in terms of the new model. So as a natural evolution of ADO.Net, we use the Provider Model. But instead using SqlCommand and SqlConnection, we can now use MapCommand and MapConnection instead.
With the Map Provider we can replace ADO.Net SQL Commands that targets the logical schema of the database such as this one:
using
(SqlConnection conn = new SqlConnection(Settings.Default.AWv3SqlConnectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = @"
SELECT HireDate, FirstName
FROM SalesPerson as sp
INNER JOIN Employee as e ON sp.SalesPersonID = e.EmployeeID
INNER JOIN Contact as c ON e.EmployeeID = c.ContactID
WHERE HireDate < @Date";
cmd.Parameters.AddWithValue("Date", date);
DbDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (r.Read())
{
Console.WriteLine(" {0:d}\t{1}", r["HireDate"], r["FirstName"]);
}
}
with another command that targets the conceptual schema. (The conceptual schema had an entity type called SalesPerson that was mapped to Contact, Employee and SalesPerson tables in the logical schema).
using
(MapConnection conn = new MapConnection(Settings.Default.AWv3MappingConnectionString))
{
conn.Open();
MapCommand cmd = conn.CreateCommand();
cmd.CommandText = @"
SELECT sp.HireDate, sp.FirstName
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
WHERE sp.HireDate < @Date";
cmd.Parameters.AddWithValue("Date", date);
DbDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (r.Read())
{
Console.WriteLine(" {0:d}\t{1}", r["HireDate"], r["FirstName"]);
}
}
Entity SQL
The motivation to create the new data model was to be able to use all the above terms that we couldn't use when working against the logical schema of the database. So in order to take advantage of those terms when we use the mapping provider, the SQL Statement we provide the MapCommand object is really a statement in a new query language called Entity SQL. This new language is a variation of SQL as we know, but let us query the model in terms of entities, relationships and inheritance. Since the Client Views run in the client side, the Entity SQL statement is processed and translated into actual SQL Statement on the client side. This behavior allows this query language to be store-independent. You can change the database you work against, but the Entity SQL statement stays the same.
Some examples to Entity SQL:
Selecting a full entity by using VALUE keyword:
using (MapConnection conn = new MapConnection(Settings.Default.AWv3MappingConnectionString))
{
conn.Open();
MapCommand cmd = conn.CreateCommand();
cmd.CommandText = @"
SELECT VALUE sp
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
WHERE sp.HireDate < @Date";
cmd.Parameters.AddWithValue("Date", date);
DbDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (r.Read())
{
Console.WriteLine(" {0:d}\t{1}", r["HireDate"], r["FirstName"]);
}
}
Navigating thourgh relations using NAVIGATE operator.
using (MapConnection conn = new MapConnection(Settings.Default.AWv3MappingConnectionString))
{
conn.Open();
MapCommand cmd = conn.CreateCommand();
cmd.CommandText = @"
SELECT VALUE sp
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
WHERE NAVIGATE(so, AdventureWorksModel.SalesPerson_Order).HireDate < @Date";
cmd.Parameters.AddWithValue("Date", date);
DbDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (r.Read())
{
Console.WriteLine(" {0:d}\t{1}", r["HireDate"], r["FirstName"]);
}
}
Getting entities according to thier type (using inheritance):
using (MapConnection conn = new MapConnection(Settings.Default.AWv3MappingConnectionString))
{
conn.Open();
MapCommand cmd = conn.CreateCommand();
cmd.CommandText = @"
SELECT VALUE sp
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
AND so IS OF(AdventureWorksModel.StoreSalesOrder);
cmd.Parameters.AddWithValue("Date", date);
DbDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (r.Read())
{
IExtendedDataRecord er = (IExtendedDataRecord)r;
Console.Write(er.DataRecordInfo.Metadata.Name);
Console.WriteLine(" {0:d}\t{1}", r["HireDate"], r["FirstName"]);
}
}
ADO.Net Object Layer
There is no doubt that using rows and columns is great for several scenarios such as Reporting or Business Intelligence. But, when you write heavy business logic against the results of your query, in most cases you would prefer working with objects.
Instead of building a new stack for Object Relational Mapping, the ADO.Net team has chosen to build a new object layer above the existing ADO.Net stack. As a matter of fact, your conceptual model should not be any different if you eventually want to get objects back or rows and columns.
While using the provider model on the mapping layer (using MapConnection and MapCommand), using the object layer is slightly different. This layer has a single entry point called ObjectContext. For example:
Using Object Context to query objects:
ObjectContext
ctx = new ObjectContext(Settings.Default.AWv3MappingConnectionString, "AdventureWorksModel.AdventureWorks");
Query<SalesPerson> query = ctx.GetQuery<SalesPerson>(@"
SELECT VALUE sp
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
WHERE sp.HireDate < @Date",
new QueryParameter("Date", date));
foreach (SalesPerson sp in query)
{
Console.WriteLine(" {0:d}\t{1}", sp.HireDate, sp.FirstName);
}
Using Object Context to reflect changes back to the database:
ObjectContext ctx = new ObjectContext(Settings.Default.AWv3MappingConnectionString, "AdventureWorksModel.AdventureWorks");
Query<SalesPerson> query = ctx.GetQuery<SalesPerson>(@"
SELECT VALUE sp
FROM AdventureWorksModel.AdventureWorks.SalesPeople as sp
WHERE sp.HireDate < @Date",
new QueryParameter("Date", date));
foreach (SalesPerson sp in query)
{
if (sp.FirstName == "Amy")
{
sp.Bonus += 10;
sp.MiddleName = "Guy";
sp.Title = "Senior Consultant";
}
Console.WriteLine(" {0:d}\t{1}", sp.HireDate, sp.FirstName);
}
ctx.SaveChanges();
Language Integrated Query and LINQ to Entities
In order to eliminate the impedance mismatch between programming languages and the way we communicate with the database (usually SQL), we can use LINQ. LINQ is a set of innovations for programming languages that allows us to integrate queries as part of the programming language we use to write our business logic. Using LINQ we can use intellisence, compilation checks, and pass typed parameters to our queries.
An example for LINQ query ober the conceptual model:
AdventureWorks db = new AdventureWorks();
var query = from sp in db.SalesPeople
where sp.HireDate.Year == 2006
select sp;
foreach (SalesPerson sp in query)
{
Console.WriteLine(" {0:d}\t{1}", sp.HireDate, sp.FirstName);
}
I hope you also enjoyed the presentation and demos. You can download the slide deck from here, and the demos from here.
Using the Demos:
Before you download and start playing with the demos, you should install:
LINQ May CTP
ADO.Net vNext August CTP
Entity Data Model Designer CTP
After installing, read further instructions here.
If you have any questions regarding the presentation or demos, I'd like to here them. More important, if you have any feedback you want to provide about the ADO.Net Entity Framework, I'd like to hear about it!
Enjoy!
Roy Osherove has made a list of Israeli bloggers you should read. I was really happy to find my name there between all other well known bloggers and MVP's...
I've been playing around with ADO.Net vNext for over a month now, and recently started answering questions in the related MSDN Forum. Today I noticed that I'm the one who gave the highest number of correct answeres this month...

Do you have any questions?
Just a reminder -
Tomorrow, October 22nd, I am presenting ADO.Net Entity Framework for the Architects User Group. Don't miss it!
For more details about the presentation, go here.
See you tomorrow!
Presentation Demo Tips
If you have a technical demo in your presentation you have to make sure that people can see what you are doing. If the presentation takes place in a large room, you should think about the person who sits at the last row and wants to see you.
So, I prepared a small list for things you must do before you demo:
Using Large Fonts
Go to your Desktop, right click and select Properties. On the Appearance tab, set the Font Size to Large.
In Visual Studio, change the font size of your code and text editors. Go to Tools -> Options, find the Fonts and Colors node under Environment, and change the following settings:
1. Set the Plain Text Font Size to 16 at least.
2. Use a Font that look good in large scales and designed for ClearType such as Lucida Console or much better Consolas. (You can download Consolas Fonts Pack from here.)
3. Change the Selected Text Background Color to Yellow, and the Foreground Color to Black. These settings look just great in demos.
If you are using the command prompt in you demo, you can set the default font and size as well.
Go to Start -> Run and run cmd. Right click the top left corner to show the Menu, and choose Defaults. On the Fonts Tab you can select Lucida Console font and size at least 16.
Make sure to change the fonts for each program or tool you will be using during your demos.
Screen Resolution
Although your computer may use a very high resolution, or even a wide-screen, you should take in mind that most projectors might not. So you should change your resolution to 1024x768. I also advise to prepare for your presentation and demos using this resolution. You might find out that your code lines are longer that what people may see.
Zoom / Magnify
Sometimes using large fonts is not enough and you want to enlarge some portion of your screen. I use a great tool by SysInternals called ZoomIt, that is very easy to use (activated with Alt +1).
Clean Your Desktop
No one has to see what's on your desktop during presentations. It takes the audience attention from you and may reveal yourself to some awkward situations. I usually create a new folder and drag all my desktop shortcuts to it. After the presentation is done, I can easily take them out to the desktop.
Another thing is changing your desktop wallpaper. Nobody has to know I am an Angelina Jolie's fan.
I hope the above Presentation Demo Tips were useful in your next presentation. Let me know if you have any more tips.
Enjoy!
Another new Web 2.0 site is out there: http://slideshare.net/
This site lets you share your slides instead of sending them to others by email.
We'll see how long it will take for google or another company to buy them.
In the mean time, watch this good example for sharing some slides...
Enjoy!
Embedding business rules is very powerful and useful. If you are using Windows Workflow Foundation you can model you business process and use a PolicyActivity. But If you don't want to model your business process with a workflow, but still want to execute rules in it?
The Windows Workflow Foundation Rules Engine has the API for it. I'll take this post to explore it a little bit and give some examples.
You can run a RuleSet against any object…
Typically you would execute your RuleSets against you workflow, to change the workflow state according to some properties. But, you can also execute rules againt any other .net object.
Create a RuleSet
The RuleSet Editor Dialog is exposed as part of the API, so you can use it to create RuleSets as part of your program:
// Create a RuleSet that waorks with Orders (just another .net Object)
RuleSetDialog ruleSetDialog = new RuleSetDialog(typeof(Order), null, null);
// Show the RuleSet Editor
ruleSetDialog.ShowDialog();
// Get the RuleSet after editing
RuleSet ruleSet = ruleSetDialog.RuleSet;
Serialize and Deserialize rules
Windows Workflow Foundation uses the WorkflowMarkupSerializer to Serialize and Deserialize rules.
// Serialize to a .rules file
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
XmlWriter rulesWriter = XmlWriter.Create(fileName);
serializer.Serialize(rulesWriter, ruleSet);
rulesWriter.Close();
// Deserialize from a .rules file.
XmlTextReader rulesReader = new XmlTextReader(fileName);
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
ruleSet = (RuleSet)serializer.Deserialize(rulesReader);
rulesReader.Close();
Execute RuleSet againt an object
Execute your RuleSet after editing, serializing and deserialising it, but first validate that the rules can be executed against the input object.
// Execute the rules and print the entity's properties
Order myOrder = new Order(...);
RuleValidation validation = new RuleValidation(typeof(Order), null);
RuleExecution execution = new RuleExecution(validation, myOrder);
ruleSet.Execute(execution);
Download a sample project that demonstrates creation, editing, serialization and execution of RuleSet against a custom object.
Enjoy!
I am an aerobics instructor!
At least, I used to be up until couple of month ago. I had taken the Aerobics Instructors Course about a year ago and had been working as an instructor for a few month.
Aerobics classes are very common in Israel, as there are also aerobics conventions (Just like Tech-Ed…) I participated one back in May, and took a film in one of the classes. Now that I can embed YouTube movies in my posts, you can watch my favorite instructor, Gil Gispan in the middle of a class.
[youtube]http://youtube.com/watch?v=qkFVjel6hOI[/youtube]
Enjoy!
Many of the demos seen of ADO.Net Entity Framework were built on top of AWv3 database, which is a subset of the AdventureWorks sample database that’s included in Microsoft SQL Server 2005.

So, based on Pablo's post on the ADO.NET Technology Preview MSDN Forum, I built a project (class library) that contains the entity data model of AWv3, which is available for download.

The solution contains:
· A SQL script for creating AWv3 database with data from the original AdventureWorks.
· Class Library project (AWv3Model) that contains the AWv3 Entity Data Model and related files (.ssdl, .csdl and .msl)
· Configuration file with CTP settings.
· A Console application with a working LINQ query to test the model.
You can download AdventureWorks sample database from here.
Enjoy!
blogs.microsoft.co.il blogs site was upgraded to Community Server 2.1, and has a brand new look. Check it out!
This upgrade brings up some few improvements for Israeli bloggers such as new themes, better post editor and anti-spam rules.
The next version of Community Server, code name "Calypso" was recently announced.
Enjoy blogging!
How To: Change PaperClip Theme Image and Width
After upgrading to Community Server 2.1, I liked the PaperClip family of themes the most. The problem with it is that the blog becomes too narrow for adding code snippets in my blog posts.
So, I decided to customize the theme a little bit, and while on it, replace the standard title image.
So here how it's done:
· Go to your blog's dashboard, and from the side menu select Global Settings -> Change how my blog looks.
· Pick one of the PaperClip themes.
· Go to the CSS Overrides tab and paste the following code. Notice that the #masthead background-image should point to a 996x221 pixel image. (You can adjust your width of the blog and image as you like…).
#content
{
width: 984px;
}
#masthead
{
background-image: url(…);
width: 996px;
}
#main
{
width: 726px;
}
#nav
{
width: 984px;
}
· To create your personal PaperClip Theme Image (with a paper clip mark above it), download this .psd file (Photoshop) with the layers you need. You can upload the image to your blog gallery or host it where ever, or you can use my top header image.
Enjoy!
More Posts
Next page »