Tuesday, June 30, 2009

CodeSmith templates for Xaf

Yes I know that is not the best practice. When using Xaf or Xpo you should first design your objects and let the framework create the database schema based on objects metadata (attributes). But there are many cases that the database is already design and you can not change it.

What about those projects?

Are you going to say to your customer that you do not want that project?

Are you going to sit down and write all classes by hand?

The best solution on this is to use some Template engine like Codesmith to create the initial implementation for you and then you can change them to meet your needs. You can also find a freeware version of Codesmith here

Devexpress also has a persistent class generation Util which ca be invoked from the add new item form
 

image image

 

but has limited functionality doesn’t create associations, tables with more than one primary keys, knows nothing on xaf and is not at all flexible .

Aristeidis the guy with the beers that day share also his codesmith xaf templates with me you can download them . These templates are not perfect we just share them with you and if you implement more features would could also share back with us.

I will try to apply those templates to Northwind sample database. Northwind has 3 intermediate tables which are CustomerCustomerDemo,Order Details and EmployeeTerritories and I am very interested to know how its going to behave for those. Aris told me that hides the itermediate table from xaf by creating custom collections lets see and usig the ManyToManyAlias attribute.

Download templates and see Video here

thnk you Aristeidis

ps: you can find some old xpo temlates here by Wolfgang Hauer

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Monday, June 29, 2009

TypeMock MVP

Since I am the first user of TypeMock!!!, Gil Zilberfeld which is a technology Evangelist at TypeMock offer me a TypeMock MVP title. Also that title gaves me access to see all future TypeMock exciting stuff before go official. Do not know if I can blog about them though.

typemock

Thank you Gil and TypeMock it is my honor to use such a great tool!!!

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Friday, June 26, 2009

eXpand Step 1 – refactoring and renaming

Related posts:
eXpand RWF = (Real world framework)--->First thoughts
eXpand Step 1 – refactoring and renaming
eXpand step 2-Singing assemblies with strong Names

Refactoring namespaces

I am going to start refactoring today and I am going to use Resharper and its rename NameSpace feature to accompish it.

I though it will be easy, but nothing is easy at this life. What happen ?

At my pc Core 2 Quad with 8G memory I tried to refactor directly the word XAFPoint which is the root namespace in all assemplies. Yes you can do that!!!

if you have for example a namespace like:

RootNameSpace.SubNameSpace1.SubSubNameSpace at assembly 1
RootNameSpace.SubNameSpace2.SubSubNameSpace at assembly 2

and you try to rename using ReSharper the RootNamepace to RenamedNameSpace you will end up with:

RenamedNameSpace.SubNameSpace1.SubSubNameSpace at assembly 1
RenamedNameSpace.SubNameSpace2.SubSubNameSpace at assembly 2

with a press of a keyboard shortcut!!!

That all are in theory of course. But for a large project like that when I try to rename the earth stop moving!!!!

See some metrics on the framework

image

see also some metrics on Xaf 

image

Ok I am not afraid of those numbers we can still do the renaming but we have to group our namespaces more in order ReSharper to hold

tip: ReSharper does not refactor projects that are not selected to be build with the active solution configuration so you have to be careful with that

Setting up project references

Projects that reference other projects should do from eXpand.dll folder so I have setup output path to that folder and by doing so I am minimizing any Visual studio designer defects since I m not referencing projects but assemblies

image

In order to to solve Unable to copy from obj\debug to bin\debug I put that script to all projects pre build event

And by clearing all build attributes from all projects in solution active configuration

image

I manage to have the ability to work and build one project at a time, imagine what will happen if I didn’t do that. My current solution has 89 projects!!! And why do I need to load on those projects? Because I need ReSharper to be aware of all code when refactoring

Renaming folders on file system

that was easy job even if they are a large number of folders

Versioning

You can enable versioning by using the following at your AssemblyInfo.cs of every project

[assembly: AssemblyVersion("1.0.0.*")]
So I put it in every project and try to build the solution again so versions will start raising

but many builds failed again!!!

but why? oops I forgot that I am referencing from eXpand.DLL so every time I build the assembly version changes. To overcome this one I should set the “Specific Version” attribute to false to all referenced assemblies

image

ok refactoring finished, now we are 1 step closer to release

_lac folder

_lac=local assembly cache. We are going to have a folder _lac alond with eXpand.DLL to store any third party library that we are going to use like mbunit,EnterpriseLibrary , etc

We hope to hear your suggestions, additions to the process taken

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Thursday, June 25, 2009

TDD, Xaf, Typemock and eXpand

If you do not know about TypeMock see some cool video tutorials here.
TDD is an software design approach that states:

In order to design your software from the correct angle and don’t get lost in the info you have first write down a test that describes a behavior and then by using tools like ReSharper to actually create the “at most as code as required to make that test past”

There is an excellent video from Gary and Oliver on how to TDD with Xaf. These guys know a lot but you have to analyze each word they say to get the real power out of it. Nice work guys!! and we love to see more videos like that but going deeper onto the “software design” stuff.

Test Driven Development Techniques

Now that I am sure that you know what is TDD is I am going to saw you the following

How do I test a viewController?

Gary and Oliver state that you should refactor your logic out of the controller. But also you can leave it there as well.
Suppose you have a case like : I want to create an abstract controller using BaseObject as a type argument that will implement the following functionality: When a user click on a row of a web list view of objects that belong to “directly edit group” then it should go directly to its equivalent detail view but in edit mode

lets write our test for that behavior

[Test]
public void Test_That_When_A_DetaiView_IsActivated_The_ViewEditMode_Property_Equals_Edit_FirstAttempt()
{
    //setup preconditions
    var viewController1 = new DomainObject1ViewEditModeController();
    viewController1.SetView(new DetailView(new DictionaryNode(""),new ObjectSpace(new UnitOfWork(),XafTypesInfo.Instance),
                                           null, null, true  ));
    viewController1.Active.Clear();

    //if we llok at viewcontroller source code we see that Onactivated is called when Active has change. So here we call OnActivated method
    viewController1.Active[""] = true;

    //setup assertions
    Assert.AreEqual(ViewType.DetailView, viewController1.TargetViewType);
    Assert.AreEqual(ViewEditMode.Edit,((DetailView)viewController1.View).ViewEditMode);

}

ugly code eh? what do you think? I think someone needs to think a “little“ in order to write this!!

now that we have define our bahaviour lets implement it.

public partial class DomainObject1ViewEditModeController : ViewEditModeController<DomainObject1>
{
    public DomainObject1ViewEditModeController()
    {
        InitializeComponent();
        RegisterActions(components);
    }
}

public abstract class ViewEditModeController<Target> : ViewController where Target:BaseObject
{
    protected ViewEditModeController()
    {
        TargetViewType=ViewType.DetailView;
        TargetObjectType = typeof (Target);
    }

    protected override void OnActivated()
    {
        base.OnActivated();
        ((DetailView) View).ViewEditMode=ViewEditMode.Edit;
    }
}

DomainObject1 will now have the expected behaviour. (of course you could implement that behaviour differently I am just doing a TDD,Typemock example here). 

Since the behavior does not change for different DomainObjects, I mean that for testing another object like DomainObject2 we would have to write the same code exactly. It would be very nicer if we could test directly the ViewEditModeController.

But how can we test an abstract class? How can we initialize?

We can use TypeMock Isolator for that. The code bellow I think is self describing

[Test]
public void Test_That_When_A_DetaiView_IsActivated_The_ViewEditMode_Property_Equals_Edit()
{
    //create fake instance of controller
    var controller = Isolate.Fake.Instance<ViewEditModeController<DomainObject1>>(Members.CallOriginal);
    //create fake instance of detailview
    var detailView = Isolate.Fake.Instance<DetailView>();
    Isolate.WhenCalled(() => controller.View).WillReturn(detailView);

    controller.Active.Clear(); 

    controller.Active[""] = true;

    //setup assertions
    Assert.AreEqual(ViewType.DetailView, controller.TargetViewType);
    Assert.AreEqual(ViewEditMode.Edit,((DetailView)controller.View).ViewEditMode);

}

is this code more elegant or what?

Download Sources

For this post I am using MbUnit, TestDriven.Net 

ps: TypeMock has provided an open source license with all features of commercial product for all contributors of eXpand. Also there is a free community version avaliable here

oops wrong again: It's not just for contributors. Anyone who downloads the source and wants to run the tests can get this license as well. The license limits it for non commercial use

thnks TypeMock

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Tuesday, June 23, 2009

AspxTreeList editor for Xaf

Thnks to my friend Aristeidis I have in my hands a WebPropertyEditors that contains an AspxTreeList implementation and I can share it with the community.

Since I didn’t write the code I cannot answer to many questions but from a first look I an IWebTreeNode interface that should be implemented by your persistent object along with ITreeNode.

image image

 

thnk you for sharing this one Aris

Download

ps: AspxTreeList editor is going to be released with Xaf 9.2 version. This one is for those that are in a hurry

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Monday, June 22, 2009

eXpand RWF = (Real world framework)--->First thoughts

Related posts:
eXpand RWF = (Real world framework)--->First thoughts
eXpand Step 1 – refactoring and renaming
eXpand step 2-Singing assemblies with strong Names

The last few months me and my friend John have been working on a framework build using Xaf. It is called XafPoint and has almost 40 generic modules!!!

What is it? What it does ?

It is build using the same architecture as Xaf and contains abstract modules like the Xaf one’s so we can build our every day scenario.

How it was build ?

Since I am  from the first beta day a Xaf user I managed to have a strong and abstract layer just above xaf. Then I met john that had a large project and he was using SharePoint services to implement it. But when I told him some cool stuff on Xaf he got very excited and he told me that he wanted to use Xaf as the data management feature of SharePoint so we tried and in a few months join our knowledge and tools and we build a well structure framework called XafPoint. But since we believe that this  project belongs to the public we  are going to release it as an open source project called eXpand

The problem is that we do not want that open source to fail but this will be for sure if we just release our code to public as it is. Not that its not of good quality but guess what? its undocumented and  all of you know that this is too bad. One more problem is that we know not much about how to coordinate an open source project so we need your help on this one also

So me and John sit down and make things we have to do in order our framework to be released in a descent form at open source community

How to setup Xaf open source project called eXpand

  1. Refactor all namespaces from XafPoint to eXpand, Rename projects, Rename folders on file system, Add versioning, Rename assembly names
  2. StrongKey file for the release version
  3. Import refactored code / modules to Google code and try with help of Google to understand better the process of creating an open source software
  4. Create build scripts
  5. Toolbox Creator for release version
  6. Setup some standards that modules have to fill in order to be hosted in eXpand
  7. Decide which modules will be released with version 1 beta
  8. Create a Visual studio project template that
  9. Create a post / wiki entry for each Module / Controller describing behaviors not how the code works but what is the behavior it supports

Of course we want your suggestions on this list please give it a try

I am going to blog about each entry on that list to keep you inform

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Sunday, June 21, 2009

one more secret reveal !!!!

 

if you do not know about ITreenode’s purpose read this

The problem

I just came back from my friend Aristeidis home . Aris told me that he want me to have a look a his brand new AspxTreelistEditor and have also some cold beers we can drink .

After some beers Aris ask was telling me how he solved the circularReferences between parent child relation. Because ITreenode implementation is too simple or you are lazy to search for the best practice you possibly implement like Aris and I do it up to today. But today is different cause while exploring Devexpress sources I found DevExpress.Persistent.BaseImpl.HCategory that solves that problem

circularreference

one more secret reveal !!!!

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Friday, June 19, 2009

Coderush plugins for Xaf update2

Steven Rasmussen found a bug at modeleditor plugin that was: if you have any of your modules saved at a directory that contain spaces in its name the modeleditor failed to open

the fixed version can be found here

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Wednesday, June 17, 2009

Coderush plugins for Xaf update1

Xaf addins won’t load if there was a special kind of project in your solution like Setup Project,DataBaseProject

I have fix that and you can download them again here

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Tuesday, June 16, 2009

Xpo Properties for Strongly Typed freaks!!!

Because XPbaseObject implements INotifyPropertyChanged property setters need to be implemented using a special way like

public string Name
{
    get
    {
        return name;
    }
    set
    {
        SetPropertyValue("Name", ref name, value);
    }
}

but if you are a strongly typed fun like me the you certainly will not like the string representation of the “Name” as a parameter of SetPropertyValue because if you rename the property then you should explicitly rename the string parameter as well.

I used to write my properties like

private string nameWithReflection;

public string NameWithReflection
{
    get
    {
        return nameWithReflection;
    }
    set
    {
        SetPropertyValue(MethodBase.GetCurrentMethod().Name.Replace("set_", ""), ref nameWithReflection, value);
    }
}

Not very elegant eh?

Of course we can use the approach described at those previous posts Static Reflection and at More Static Reflection

so using the following extension methods

public static class Extensions
{
    public static PropertyInfo GetPropertyInfo(this object target, Expression<Func<object>> property)
    {
        var info = target.GetMemberInfo(property) as PropertyInfo;
        if (info == null) throw new ArgumentException("Member is not a property");

        return info;
    }
    public static MemberInfo GetMemberInfo(this object target, Expression member)
    {
        if (member == null) throw new ArgumentNullException("member");

        var lambda = member as LambdaExpression;
        if (lambda == null) throw new ArgumentException("Not a lambda expression", "member");

        MemberExpression memberExpr = null;


        if (lambda.Body.NodeType == ExpressionType.Convert)
            memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
            memberExpr = lambda.Body as MemberExpression;

        if (memberExpr == null) throw new ArgumentException("Not a member access", "member");

        return memberExpr.Member;
    }

}

we can write our properties like

public string NameWithReflection
{
    get
    {
        return nameWithReflection;
    }
    set
    {
        SetPropertyValue(this.GetPropertyInfo(()=>NameWithReflection).Name, ref nameWithReflection, value);
    }
}
public XPCollection<Order> Orders
{
    get
    {
        return GetCollection<Order>(this.GetPropertyInfo(()=>Orders).Name);
    }
}

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Monday, June 15, 2009

More Static Reflection

Today we are going to speak about an implementation of the approach describe in this post.

INotifyPropertyChanged is responsible for notifying clients that a property value has changed.To implement INotifyPropertyChanged you should write a code similar to

public class Client : INotifyPropertyChanged
{
private string name;


public string Name
{
get { return name; }

set
{
if (name == value)
return;
name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
}


and the test of the behaviour that we want would be



[Test]
public void Notification_Event_Will_Raized_On_Property_Change()
{
var client = new Client();
bool raized = false;
client.PropertyChanged += (sender, args) => raized = true;

client.Name = "name";

Assert.AreEqual(true, raized);
}


but we can replace that ugly setter of Name property with a more strongly typed and elegant code using static reflection technic .



here are the extension methods that will help us



public static class ReflectionExtensions
{

public static void SetProperty<T>(this INotifyPropertyChanged source,
Expression<Func<T>> propExpr,
ref T propertyValueHolder,
T value, Action doIfChanged) where T : class
{
var prop = (PropertyInfo)((MemberExpression)propExpr.Body).Member;
var currVal = (T)prop.GetValue(source, null);
if (currVal == null && value == null)
return;
if (currVal == null || !currVal.Equals(value))
{
propertyValueHolder = value;
var eventDelegate = (MulticastDelegate)source.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic).
GetValue(source);
if (eventDelegate != null)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
var args = new PropertyChangedEventArgs(prop.Name);
foreach (Delegate dlg in delegates)
dlg.Method.Invoke(dlg.Target, new object[] { source, args });
}
doIfChanged();
}
}
public static void SetProperty<T>(this INotifyPropertyChanged source,
Expression<Func<T>> propExpr,
ref T propertyValueHolder,
T value) where T : class
{
source.SetProperty(propExpr, ref propertyValueHolder, value, () => { });
}


}


now we can replace our ugly setter with the SetProperty extension method and our test will continue to pass



private string name;


public string Name
{
get { return name; }

set
{

this.SetProperty(()=>Name,ref name,value);
}
}


You see?? Now our property does not contain any string or duplicate code



the only thing that concern me is what happen with the speed? are all that lamdas and expression trees going to slow down my code?



lets write some tests on this one also



[Test]
public void Notification_Event_Will_Raized_On_Property_Change()
{
var client = new Client();
bool raized = false;
client.PropertyChanged += (sender, args) => raized = true;
var stopwatch=new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000; i++)
client.Name = "name" + i;
long ticks = stopwatch.ElapsedMilliseconds;
stopwatch=new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000; i++)
client.NameWithSR = "name" + i;

Assert.AreApproximatelyEqual(ticks, stopwatch.ElapsedMilliseconds,ticks*30);
}


damn!!! almost 30 times slower I have to be careful with those lambas although for most apps I mean for those that do not insert thousands of records at one go that speed is more than acceptable



Of course one can speed that code more by moving those extension methods to a base class and creating a cached of PropertyChanged

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Static Reflection

We all get into situation where we need to access class metadata like properties,methods and fields and we use reflection to accomplish it

private class Customer
{
public string LastName { get; set; }
}
[Test]
public void Test()
{
Assert.IsNotNull(typeof(Customer).GetProperty("LastName"));
}


but what will happen if we change the property name of “LastName” to “SurnName” ??



Our test will fail.



But there is a rescue on this one using linq expression trees.



public static class ReflectionExtensions
{
public static MethodInfo GetMethod<TTarget>(this TTarget target, Expression<Action<TTarget>> method)
{
return GetMethodInfo(method);
}

private static MethodInfo GetMethodInfo(Expression method)
{
if (method == null) throw new ArgumentNullException("method");

var lambda = method as LambdaExpression;
if (lambda == null) throw new ArgumentException("Not a lambda expression", "method");
if (lambda.Body.NodeType != ExpressionType.Call) throw new ArgumentException("Not a method call", "method");

return ((MethodCallExpression) lambda.Body).Method;
}

public static PropertyInfo GetProperty<TTarget>(this TTarget target, Expression<Func<TTarget, object>> property)
{
var info = GetMemberInfo(property) as PropertyInfo;
if (info == null) throw new ArgumentException("Member is not a property");

return info;
}


public static FieldInfo GetField<TTarget>(this TTarget target, Expression<Func<TTarget, object>> field)
{
var info = GetMemberInfo(field) as FieldInfo;
if (info == null) throw new ArgumentException("Member is not a field");

return info;
}

private static MemberInfo GetMemberInfo(Expression member)
{
if (member == null) throw new ArgumentNullException("member");

var lambda = member as LambdaExpression;
if (lambda == null) throw new ArgumentException("Not a lambda expression", "member");

MemberExpression memberExpr = null;


if (lambda.Body.NodeType == ExpressionType.Convert)
memberExpr = ((UnaryExpression) lambda.Body).Operand as MemberExpression;
else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
memberExpr = lambda.Body as MemberExpression;

if (memberExpr == null) throw new ArgumentException("Not a member access", "member");

return memberExpr.Member;
}
}


Using the above class one can make the following tests pass

[TestFixture]
public class ReflectionExtensionsFixture
{

public string StringPropertyName { get; set; }

[Test]
public void Property_Info_Can_Be_Found()
{
PropertyInfo property = this.GetProperty(p=>p.StringPropertyName);

Assert.AreEqual("StringPropertyName", property.Name);
}
[Test]
public void Method_Info_Can_Be_Found()
{
MethodInfo methodInfo = this.GetMethod(p => p.PrivateMethod());

Assert.AreEqual("PrivateMethod", methodInfo.Name);
}
private void PrivateMethod()
{

}

public string field;
[Test]
public void FieldInfo_can_be_Found()
{
FieldInfo info = this.GetField(f=>field);
Assert.AreEqual("field", info.Name);
}
}


very cool!!! at my opinion. And you can find endless implementations of it.

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Thursday, June 11, 2009

DevExpress Rocks!!

These people are actually monitoring everything. Its been only one week of blogging and my efforts payed already see DevExpress official blog on this post How to master a language in less than 10,000 hours

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Wednesday, June 10, 2009

Xaf Exception Stack Explorer

Xaf has its own tracking system enabled by default . What it does? It tracks almost every from exception to button clicks and object states!!

What I want to saw you is how easy we can create a CodeRush addin that every time an exception occurs we could navigate through all the stack trace

We will accomplish that using Resharper’s stackTraceExplorer.

So all we need to do is to find startup project’s bin directory open expressAppFramework.log which is the file that Xaf writes all traces, find the last entry, copy it to memory and send to Visual studio a Resharper+ExploreStackTrace command

Lets do it. In fact we can easily extend the plugins project I posted here and have all in one package.

But we have to be careful when trying to read a log file cause it may be of a very large size, mu log often are over 30Mb!!!. So we need to use some special class to search inside that text file backwards to find the last exception

public class InverseReader
{
private readonly FileStream fileStream;

public InverseReader(string path)
: this(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{

}

public InverseReader(FileStream fs)
{
fileStream = fs;
fs.Seek(0, SeekOrigin.End);
}

public bool SOF
{
get { return fileStream.Position == 0; }
}

public string Readline()
{
var text = new byte[1];
fileStream.Seek(0, SeekOrigin.Current);

long position = fileStream.Position;
bool trailingNewLine = fileStream.Length > 1;
if (trailingNewLine)
{
var bytes = new byte[2];
fileStream.Seek(-2, SeekOrigin.Current);
fileStream.Read(bytes, 0, 2);
if (Encoding.ASCII.GetString(bytes).Equals("\r\n"))
{
//move it back
fileStream.Seek(-2, SeekOrigin.Current);
position = fileStream.Position;
}
}
while (fileStream.Position > 0)
{
text.Initialize();
//read one char
fileStream.Read(text, 0, 1);
string asciiText = Encoding.ASCII.GetString(text);
//moveback to the charachter before
fileStream.Seek(-2, SeekOrigin.Current);
if (asciiText.Equals("\n"))
{
fileStream.Read(text, 0, 1);
asciiText = Encoding.ASCII.GetString(text);
if (asciiText.Equals("\r"))
{
fileStream.Seek(1, SeekOrigin.Current);
break;
}
}
}

int count = int.Parse((position - fileStream.Position).ToString());
var line = new byte[count];
fileStream.Read(line, 0, count);
fileStream.Seek(-count, SeekOrigin.Current);
return Encoding.ASCII.GetString(line);
}


public void Close()
{
fileStream.Close();
}
}


see configuration/usage video





Download sources

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Thursday, June 4, 2009

CodeRush plugins for Xaf

To download sources see DxCore plugins for Xaf are moving

Updates

(10/6/09) (see Xaf Exception Stack Explorer)
(17/6/09) (see Coderush plugins for Xaf update1)
(19/6/09) (see Coderush plugins for Xaf update2)

ProjectConverter

Browsing and downloading from Devexpress support center often I find old projects with broken references

solutionexplorer

Old days when i see broken references at my solution due to version changes I had to go to my C:\Program files\pathToYourProjectConverter executable. Open it, browse to find my solution folder and convert it

Nowadays I am using a small CodeRush addin I wrote and I can convert any solution from with in Visual Studio By pressing a shortcut. You have to configure it by setting its path as shown in the image bellow

options1

if you use a recompile version of the assemblies you can also set at the PublicToken field

Then you go to shortcuts and assign a shortcut key for the convertProject command

shortcut 

now every time i need to convert a solution i just hit Ctrl+Shift+Alt+C and voila

solutionexplorerFixed

ModelEditor

Tired of seeing Visual studio errors like

Bug Report Details: XAF Model Designer issue: Possible reason: the assembly 'abc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d70b2af257f40453' has been loaded twice.

me and my friend John were tired also so one day in a half of our 5 hours long skype meeting we decide to write an CodeRush addin that will use the ModelEditor executable provided by Devexpress. So any time i want to use model editor at design time I use that addin

What it does ? It searches your solution for all projects that have a model.xafml file and shows them in a list where by pressing enter or double click will open the modified Model Editor (source included for this one also)

xafmodels

You should configure it using the same approach as project converter .

To install the addin download from here XafAddins(source,binary)  copy the assemblies to your community plugins folder or build the sources

comufol

the first time you will run it you have to configure it with an approach same to ProjectConverters

see video bellow

Enjoy!!!

Update 5/6/2009

After try to use it with a more complex solution like this one

complexsolution

i noticed that the plugin enumerates only root project

rootModels

Lets fix that. First i though that this is too basic and maybe i am missing something so lets ask DevExpress support .

List of Projects in a solution not a good answer eh? Maybe they didn’t understand me well or maybe they were too busy.

This shouldn’t be too hard to find so i search a little more on support center and i find this Find in Solution Explorer and also Enumerating projects in a Visual Studio solution

Now we know how to enumerate through all items in a solution and the type of each item !!! the next part is easy. Just write the code and adding it as an extension to EnvDTE.Solution class cause i think its an appropriate place to find there

public static class SolutionExtension
{
public static List<Project> GetAllProjects(this Solution solution)
{
var DTE = CodeRush.ApplicationObject;
var UIHSolutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object as UIHierarchy;
var projects = new List<Project>();
if (UIHSolutionExplorer != null && UIHSolutionExplorer.UIHierarchyItems.Count > 0)
ProcessSolutionExplorerItem(UIHSolutionExplorer.UIHierarchyItems.Item(1),projects);
return projects;
}

private static void ProcessSolutionExplorerItem(UIHierarchyItem item, List<Project> projects)
{
if (item.UIHierarchyItems.Count > 0)
for (int i = 1; i <= item.UIHierarchyItems.Count; i++)
{
UIHierarchyItem hierarchyItem = item.UIHierarchyItems.Item(i);
object o = hierarchyItem.Object;
if (o is Project && !isSolutionFolder(o))
projects.Add((Project) o);
else if (o is ProjectItem)
{
Project project = ((ProjectItem) o).SubProject;
if (project != null && !isSolutionFolder(project))
projects.Add(project);
}
ProcessSolutionExplorerItem(hierarchyItem, projects);
}
}

private static bool isSolutionFolder(object o)
{
return ((Project)o).Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
}


}


Limitation: if one assembly references another assembly in the project, you need to set 'Copy Local' = true for the referenced assemly otherwise a 'FileNotFound' error pops up when you try to view the model
thnks Steven :)




Collapse all items in solution Explorer



Since all my application are now heavily based on modularization i tend to have a solution template that i use to start a new solution. That solution project count is now roughly about 80 project and I often find myself lost in solution explorer.



bigsolution



So i decided to write a command for CodeRush to help me collapse all items by pressing a shortcut. The command name is collapseAllItemsInSolutionExplorer



collapseall



public static void CollapseAllFolders(this Solution solution)
{
var DTE = CodeRush.ApplicationObject;
var UIHSolutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object as UIHierarchy;
if (UIHSolutionExplorer== null||UIHSolutionExplorer.UIHierarchyItems.Count == 0)
return;
UIHierarchyItem rootItem = UIHSolutionExplorer.UIHierarchyItems.Item(1);
rootItem.DTE.SuppressUI = true;
Collapse(rootItem,UIHSolutionExplorer);
// Select the solution node, or else when you click
// on the solution window
// scrollbar, it will synchronize the open document
rootItem.Select(vsUISelectionType.vsUISelectionTypeSelect);
rootItem.DTE.SuppressUI = false;
}

private static void Collapse(UIHierarchyItem item, UIHierarchy solutionExplorer)
{
foreach (UIHierarchyItem hierarchyItem in item.UIHierarchyItems)
{
if (hierarchyItem.UIHierarchyItems.Count>0)
{
Collapse(hierarchyItem, solutionExplorer);
if (hierarchyItem.UIHierarchyItems.Expanded)
hierarchyItem.UIHierarchyItems.Expanded = false;
}
}
}




Enjoy!!!



Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Wednesday, June 3, 2009

Multiple inheritance for .Net is here!!!

I though i should post on this one cause its far more than interesting

suppose you have a Customer that is a Person

public class Person
{
public string Name { get; set; }
}

public class Customer : Person
{

}


and implements 2 interfaces ICustomUser,ICustomer



public interface ICustomUser
{
string Title { get; set; }
}

public interface ICustomer
{
string Title { get; set; }
}


one could write



public class Customer : Person,ICustomUser,ICustomer
{

string ICustomUser.Title { get; set; }
string ICustomer.Title { get; set; }

}


But in order to access the values of the properties Customer should be extended to something like



public class Customer : Person,ICustomUser,ICustomer
{
private string customUserTitle;
public string CustomUserTitle
{
get { return customUserTitle; }
set
{
customUserTitle = value;
}
}
private string customerTitle;
public string CustomerTitle
{
get { return customerTitle; }
set
{
customerTitle = value;
}
}

string ICustomUser.Title
{
get { return customUserTitle; }
set { customUserTitle = value; }
}


string ICustomer.Title
{
get { return customerTitle; }
set { customerTitle = value; }
}
}


Test]
public void Test_Customer_Interface_Implementations()
{
var customer = new Customer {CustomerTitle = "CustomerTitle", CustomUserTitle = "CustomUserTitle"};

Assert.AreEqual("CustomerTitle", customer.CustomerTitle);
Assert.AreEqual("CustomUserTitle", customer.CustomUserTitle);
}


PostSharp changes all that by allowing you to achieve compile time inheritance. What i mean by that? That we can use PostSharp to omit IL instructions to your assembly so after compilation it will be like you actually implement those Interaces based on some Types that already implement that.



Maybe i still sound confusing so lets write some code lets create the implementations of the events for some other type than customer



public class CustomUser:ICustomUser
{
public string Title { get; set; }
}

public class BaseCustomer:ICustomer
{
public string Title { get; set; }
}


wouldn’t be perfect if we could write our Customer like



public class Customer : Person, BaseCustomer, ICustomer
{



}


of course this do not compile. But PostSharp allows us to write it like



[SimpleCompositionAttribute(typeof(ICustomer),typeof(BaseCustomer))]
[SimpleCompositionAttribute(typeof(ICustomUser),typeof(CustomUser))]
public class Customer : Person
{

}


to be conviced open up Reflector and see what code PostSharp generate for your Customer class



reflector



and in order to acces the Value of the properties since they do not exist at design Time PostSharp provides the casting method Post.Cast<TSource,TTarget> which is both safe and efficient because it is checked and transformed at compile time.



[Test]
public void Test_Customer_Interface_Implementations()
{
var customer = new Customer ();
ICustomer iCustomer = Post.Cast<Customer, ICustomer>(customer);
iCustomer.Title = "CustomerTitle";
ICustomUser iCustomUser = Post.Cast<Customer, ICustomUser>(customer);
iCustomUser.Title = "CustomUserTitle";

Assert.AreEqual("CustomerTitle", iCustomer.Title);
Assert.AreEqual("CustomUserTitle", iCustomUser.Title);
}


Ans here you can download a sample for all the above MultipleInheritance

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Validation Rule: At least one property is required

Today i stump again upon the same problem . I wanted to throw a validation exception only if both of my properties do not have value. So lets create a validation rule for this one. More info on how we create custom validation rules can be found here Validation Module Since we are talking about multiple property values i think we should go with an attribute that is applied to a class and not to a property.

Ok first we have to define that both our RuleBaseAttribute and RuleBaseProperties derived classes will implement .

public interface IRuleRequiredForAtLeast1PropertyProperties
{
string MessageTemplateMustNotBeEmpty { get; set; }
string Delimiters { get; set; }
string TargetProperties { get; set; }
}


ok that looks nice lets explain what we have here for a bit.


1. a MessageTemplateMustNotBeEmpty that will contain my validation text. Xaf Validation module when starts scan your RuleBaseProperties descendants for all properties that start with “MessageTemplate” and displays them in a special node for editing and localization 2. Delimiters will contain a list of how TargetProperties will be delimiter (,;|) whatever you want after a second look at that interface i got the idea to extract a super interface from this one containing Delimiters and TargetProperties cause they should be on a more generic context

public interface IRuleRequiredForAtLeast1PropertyProperties:IRuleMultiPropertiesValues
{
string MessageTemplateMustNotBeEmpty { get; set; }
}
public interface IRuleMultiPropertiesValues
{
string TargetProperties { get; set; }
string Delimiters { get; set; }
}


now i have my contract lets do the simple work first implement the RuleRequiredForAtLeast1PropertyProperties. Remember this one should implement IRuleRequiredForAtLeast1PropertyProperties interface



public class RuleRequiredForAtLeast1PropertyProperties : RuleBaseProperties, IRuleRequiredForAtLeast1PropertyProperties
{
public string MessageTemplateMustNotBeEmpty { get; set; }
[RulePropertiesRequired, RulePropertiesLocalized]
public string TargetProperties { get; set; }
public string Delimiters { get; set; }
}
that looks nice also. The last time i say that I did refactor my code so lets do it again move TargetProperties,Delimiters to a more appropriate class

public class RuleRequiredForAtLeast1PropertyProperties : RuleMultiPropertiesValues, IRuleRequiredForAtLeast1PropertyProperties
{
public string MessageTemplateMustNotBeEmpty { get; set; }
}
public abstract class RuleMultiPropertiesValues : RuleBaseProperties, IRuleMultiPropertiesValues
{
[RulePropertiesRequired, RulePropertiesLocalized]
public string TargetProperties { get; set; }
public string Delimiters { get; set; }
}


ok now for the next easy part the rule attribute



[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class RuleRequiredForAtLeast1PropertyAttribute : RuleBaseAttribute,IRuleRequiredForAtLeast1PropertyProperties
{
public RuleRequiredForAtLeast1PropertyAttribute(string id, string targetContextIDs, string targetProperties)
: base(id, targetContextIDs)
{
Properties.TargetProperties = targetProperties;
}

public RuleRequiredForAtLeast1PropertyAttribute(string id, DefaultContexts targetContexts,
string targetProperties)
: base(id, targetContexts)
{
Properties.TargetProperties = targetProperties;
}

protected override Type RuleType
{
get { return typeof(RuleRequiredForAtLeast1Property); }
}

protected override Type PropertiesType
{
get { return typeof(RuleRequiredForAtLeast1PropertyProperties); }
}

public new RuleRequiredForAtLeast1PropertyProperties Properties
{
get { return (RuleRequiredForAtLeast1PropertyProperties)base.Properties; }
}
public string MessageTemplateMustNotBeEmpty
{
get { return Properties.MessageTemplateMustNotBeEmpty; }
set { Properties.MessageTemplateMustNotBeEmpty = value; }
}
public string TargetProperties
{
get { return Properties.TargetProperties; }
set { Properties.TargetProperties = value; }
}
public string Delimiters
{
get { return Properties.Delimiters; }
set { Properties.Delimiters = value; }
}
}

next part is to create the rule itself so

[RulePropertiesDefaultValue("Delimiters", ";,.:")]
[RulePropertiesDefaultValue("SkipNullOrEmptyValues", false)]
public class RuleRequiredForAtLeast1Property : RuleBase
{
private static SimpleValueManager<string> defaultMessageTemplateMustNotBeEmpty;
private readonly List<string> properties = new List<string>();

public RuleRequiredForAtLeast1Property()
{
}

public RuleRequiredForAtLeast1Property(RuleSearchObjectProperties properties) : base(properties)
{
}


public RuleRequiredForAtLeast1Property(string id, ContextIdentifiers targetContextIDs, Type objectType)
: base(id, targetContextIDs, objectType)
{
}

public static string DefaultMessageTemplateMustNotBeEmpty
{
get
{
if (defaultMessageTemplateMustNotBeEmpty == null)
defaultMessageTemplateMustNotBeEmpty = new SimpleValueManager<string>();
if (defaultMessageTemplateMustNotBeEmpty.Value == null)
defaultMessageTemplateMustNotBeEmpty.Value =
@"""{TargetProperties}"" must not be empty.";
return defaultMessageTemplateMustNotBeEmpty.Value;
}
set { defaultMessageTemplateMustNotBeEmpty.Value = value; }
}

public override ReadOnlyCollection<string> UsedProperties
{
get
{
return
new ReadOnlyCollection<string>(Properties.TargetProperties.Split(Properties.Delimiters.ToCharArray()));
}
}

public new RuleRequiredForAtLeast1PropertyProperties Properties
{
get { return (RuleRequiredForAtLeast1PropertyProperties) base.Properties; }
}

public override Type PropertiesType
{
get { return typeof (RuleRequiredForAtLeast1PropertyProperties); }
}

protected override bool IsValidInternal(object target, out string errorMessageTemplate)
{
Dictionary<string, object> values = GetValues(target);
int emptyFound = 0;
foreach (var value in values)
{
if (Validator.RuleSet.IsEmptyValue(TargetObject, value.Key, value.Value))
emptyFound++;
}
errorMessageTemplate = Properties.MessageTemplateMustNotBeEmpty;
return !(emptyFound == values.Count);
}

private Dictionary<string, object> GetValues(object target)
{
var objects = new Dictionary<string, object>();
properties.Clear();
properties.AddRange(Properties.TargetProperties.Split(Properties.Delimiters.ToCharArray()));
ITypeInfo targetTypeInfo = XafTypesInfo.Instance.FindTypeInfo(Properties.TargetType);
foreach (string property in properties)
objects.Add(property, targetTypeInfo.FindMember(property).GetValue(target));
return objects;
}
}


Now its time to write some tests for the new rule here is the class that is applied to



[DefaultClassOptions]
[RuleRequiredForAtLeast1Property(null,DefaultContexts.Save, "PropertyName1,PropertyName2")]
public class DomainObject1 : BaseObject
{
public string PropertyName1 { get; set; }
public string PropertyName2 { get; set; }
}

the tests

[SetUp]
public void Setup()
{
XpoDefault.DataLayer =
new SimpleDataLayer(new InMemoryDataStore(new DataSet(), AutoCreateOption.DatabaseAndSchema));
}
[Test]
public void Test_That_Will_Not_Fail_When_At_Least_One_Property_Has_Value()
{
var domainObject1 = new DomainObject1 { PropertyName1 = "PropertyName1" };
Validator.RuleSet.Validate(domainObject1,ContextIdentifier.Save);
}
[Test][ExpectedException(typeof(ValidationException))]
public void Test_That_Will_Fail_When_Both_Properties_Do_Not_Have_Value()
{
var domainObject1 = new DomainObject1();
Validator.RuleSet.Validate(domainObject1,ContextIdentifier.Save);
}

and a visual proof that everything works

allok



sample can be downloaded here

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Tuesday, June 2, 2009

Automatic properties for Xpo

 

The problem

Xpo in order to support transactions implements some special kind of property setters like

private string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
string oldValue = lastName;
if (oldValue == value)
return;
lastName = value;
OnChanged("Name", oldValue, value);
}
}

Or a little more elegant like

private string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
SetPropertyValue("LastName", ref lastName, value);
}
}

Imagine you want to Design a fairly simple model like Customer –> Orders. A Customer should have LastName, FilrstName, Age and Orders as properties and Order only an Amount property. Using the above approach one could write the following code to describe the above model.

public class Customer : BaseObject
{
public Customer(Session session) : base(session) { }
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
SetPropertyValue("FirstName", ref firstName, value);
}
}

private string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
SetPropertyValue("LastName", ref lastName, value);
}
}

private int age;
public int Age
{
get
{
return age;
}
set
{
SetPropertyValue("Age", ref age, value);
}
}
[Association("CustomerOrders")]
public XPCollection<Order> Orders
{
get
{
return GetCollection<Order>("Orders");
}
}
}

public class Order:BaseObject
{
private int ammount;
public int Ammount
{
get
{
return ammount;
}
set
{
SetPropertyValue("Ammount", ref ammount, value);
}
}
private Customer customer;
[Association("CustomerOrders")]
public Customer Customer
{
get
{
return customer;
}
set
{
SetPropertyValue("Customer", ref customer, value);
}
}
}

Damn!!! That was too long for describing that simple model. Wouldn’t it be nicer for someone to write something like the code bellow using automatic properties to describe exactly the same  model?

public class Customer : BaseObject
{
public Customer(Session session) : base(session) { }

public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

[Association("CustomerOrders")]
public XPCollection<Order> Orders
{
get;private set;
}
}

public class Order:BaseObject
{
public int Ammount { get; set; }

[Association("CustomerOrders")]
public Customer Customer { get; set; }
}


The solution


Yes it’s time to use AOP PostSharp and XpoAutomaticProperties open source frameworks to achieve our goal. Do not be afraid it’s actually very simple you only have to decorate your object with an attribute and implement an IPropertyChangedNotifier interface.I am sure that most of you have a BaseObject descendant so let’s add that interface to that object

[NonPersistent]
public abstract class CustomBaseObject:BaseObject,IPropertyChangedNotifier
{
protected CustomBaseObject(Session session) : base(session)
{
}

protected CustomBaseObject()
{
}

void IPropertyChangedNotifier.OnChanged(string propertyName, object oldValue, object newValue)
{
base.OnChanged(propertyName, oldValue, newValue);
}
}

Now lets change the base class of our objects from BaseObject to CustomBaseObject and decorate them with XpoAutomaticProperties attribute

[XpoAutomaticProperties]
public class Customer : CustomBaseObject
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

[Association("CustomerOrders")]
public XPCollection<Order> Orders
{
get;private set;
}
}
[XpoAutomaticProperties]
public class Order : CustomBaseObject
{
public int Ammount { get; set; }

[Association("CustomerOrders")]
public Customer Customer { get; set; }
}

That’s it!. Still not convinced that it works? I will write a simple test that confirms that

public void Test_That_Change_Event_Is_Raised()
{
var customer = new Customer();
bool fired= false;

customer.Changed += (sender, args) => fired = true;
customer.Age++;

Assert.AreEqual(true, fired);
}
[Test]
public void Test_That_Change_Event_Do_Not_Raizes_When_XpoIgnoreAutomaticPropertyAttribute_IsApplied()
{
var customer = new Customer(Session.DefaultSession);
bool fired = false;

customer.Changed += (sender, args) => fired = true;
customer.AgeToBeIngored++;

Assert.AreEqual(false, fired);
}


AgeToBeIngored property is decorated with XpoIgnoreAutomaticPropertyAttribute which allows you to control to which properties the aspect will be applied



Green light for this one!!! If still not convince then open up xaf and check if its undo feature still works that will convince you. I know because I did it to convince myself. PostSharp does its magic at compile time it inserts IL instructions directly to your assembly



I have prepare a sample project demonstrating that approach download it here EditorState



A good trick is to open your assembly with Reflector and see what PostSharp / XpoAutomaticProperties does behind the scenes



reflectorpng

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

The second blogging day, Which tools can i use for blogging?

 

The first blogging day was easy not much to say . I am a big newbie on this one. So lets start our blogging adventure.

I will see it like a problem that i am going to solve and even move it on step more (hahaha classic eh?)

Requirements for blogging

  • I would like to have an offline tool like word to write my posts so i can format the text easily and faster than any Web Base Html Editor
  • I would like to be open source or have a big community that supports it writing addons
  • I want to upload any file along with images and videos
  • Easy screenshot attachment
  • At least C# code formatting abilities

Lets start googling on those requirements then . First i fell upon Zountry but it didn’t convince me, i wanted something better than this one.

Second attempt and voila Live Writer. A large number of addons exists for this blog editor Live Gallery also there are a large number of projects at CodePlex.

It should have a great API i imagine, do not know yet but probably i will try it very soon Lets try to search for a addon that formats the Code with c# style. With a fast search in google I found out that most of the bloggers are using SyntaxHighlighter from Alex Gorbatchev so it should it be difficult to use it also. Next step is to install Live writer to my Windows Server 2003 64 bit new bough machine . I download try to install and got that annoying message that my operating system is not supported. That didn’t stop me . I fire up my Xp Virtual machine and try to install it there. Installation starts ok and after a while i see a message that .Net framework is installed. Hahahaha and then i got it. Live writer is a .Net application so the installer does nothing more than placing shortcuts and minor stuff I hope. So when installation finished i copied all files from my VMWare to local pc and run Live Writer Everything work!!!! Now we have our Live writer running lets fix the Syntax highlighting problem. A new search reveals Precode which is an addon for Live Writer that supports SyntaxHighLighter all you need to do is go to your blog template and add the following lines inside your Head tag
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shCore.js' type='text/javascript'/> 
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushBash.js' type='text/javascript'/>

<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushPlain.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/2.0.320/scripts/shBrushXml.js' type='text/javascript'/>
<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script type='text/javascript'>
SyntaxHighlighter.config.clipboardSwf = &#39; http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf&#39;;
SyntaxHighlighter.config.bloggerMode = true
SyntaxHighlighter.all();
</script>


Cool!!! 2 more to go then. What about screenshot I surely want a fast but professional way to take screenshot. One more search and here it is SnagIt I could not find any automation on how to upload files except images,videos to my blog though so I am hosting my files at  Google Sites and u/l them there manually for the moment.



Here is how my Live Writer Addons toolbar looks now



toolbar 



I think now I am ready to blog for some more interesting stuff.

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Xaf adventures

Before many years when i trying to find my way in R&D world using Delphi 6 if I remember well i met DevExpress.

Since then and after .Net appears i have been following those guys. Their organization if you do not already know is unbelievable their controls suite the same. But before 2 years they started a new project called Xaf.

Xaf is an application framework that if i can describe it in 7 words is "it makes you speak the business language".

I hope that you already know the basics on Xaf so i will try to blog on that wonderful framework and give you some code, ideas on that

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

Monday, June 1, 2009

Contact me

You can download my CV if you are interested in find more about my working experiences.

I am currently looking for new business opportunities, so if you feel that you are one, or you would like to hire me, or you just want to contact me on any matter please do not hesitate to do so



Your Name
Your Email Address
Subject
Message
Image Verification
captcha
Please enter the text from the image:
[ Refresh Image ] [ What's This? ]

Subscribe to XAF feed
Subscribe to community feed

DiggIt!