Blogs

eXpress App Framework Team

  • Case Study: Building the Workflow-Based Licensing Application with XAF

         

    Check out a case study from Nathaniel Laff (you probably already know him from forums, as he always has nice avatarsWinking smile), where he described how he used the Workflow module (shipped as a part of our eXpressApp Framework (XAF) product) for automating the licensing process (tracking customers, orders, software licenses for both trial and licensed users) in his software line (he also posted some screenshots of his application), built using XAF and DevExpress components.

    Here is what Nate said about how the Workflow module helped him:

    “The Workflow module was an amazing addition to the XAF line, and with the small amount of time devoted to getting it up and running, in less than one week I was able to get that time back by not having to use my old techniques for e-mail follow ups, saving me time and massive amounts of energy, while hopefully generating more profits.”

    workflow_design

    Wish to share your story about using our products in your projects and have it appear on our web site?
    Get a case study template and write to us at clientservices@devexpress.com!

    Happy XAFingWinking smile

  • Connecting to any database at runtime

         

    In this post we will discuss how straight forward is to provide a solution for this science fiction subject! Our frameworks (XAF and XPO) along with a few smart classes are fully capable of doing all the hard job and spare our resources. At the end we will be able to apply all the XAF tools / modules in any legacy database. The module can connect the database world with powerful tools like the DX grids. In addition we can use use XAF’s main metadata storage (the model), the security system and all XAF’s modules. These tools are are so powerful that are able to produce logic by themselves! Having such great configuration flexibility it is possible to write behavior after distribution thus you enter new markets and ideas! In addition the module allows you to control the logic after generation using Xaf’s meta driven developing model.

    Retrieving any database metadata

    XPO is the best candidate for this. since it can transparently talk  to more than 15 different database systems!

    The metadata API used from XPO to describe its supported databases is very simple as shown,

    image

    In a nutshell for each supported database, XPO will return a set of DBTable classes. Each DBTable will be associated with one DBPrimaryKey class and a collection of DBColumn and DBForeighKey classes. Next is the code required to get the DBTable classes out of database and  with no surprise again is very simple!

    var storeSchemaExplorer = ((IDataStoreSchemaExplorer)XpoDefault.GetConnectionProvider("ConnectionString", AutoCreateOption.None));

    var storageTables = storeSchemaExplorer.GetStorageTables(storeSchemaExplorer.GetStorageTablesList());

    foreach (DBTable dbTable in storageTables) {

        foreach (DBColumn dbColumn in dbTable.Columns) {

            //now we are ready to do magic!

        }}

    Connecting at runtime – The magic part

    In order to query and create CRUD operations for a database system XPO requires a set of business classes. However, now there is a runtime factor involved. We need to create these business classes dynamically.

    XAF’s modularized architecture made this task too easy for us! We already created a dynamic class generation module called WorldCreator in the past. WorldCreator maps the structure of an assembly into persistent classes.

    image

    What we need is for each database to create a new PersistentAssemblyInfo, then for each DBTable a new PersistentClassInfo and finally for each DBColumn a new PersistentMemberInfo. In pseudo code this will look like,

    var persistentAssemblyInfo = ObjectSpace.CreateObject<PersistentAssemblyInfo>();

    foreach (DBTable dbTable in storageTables) {

        var persistentClassInfo = ObjectSpace.CreateObject<PersistentClassInfo>();

        persistentAssemblyInfo.Name = dbTable.Name;

        persistentAssemblyInfo.PersistentClassInfos.Add(persistentClassInfo);

        foreach (DBColumn dbColumn in dbTable.Columns) {

            var persistentMemberInfo = ObjectSpace.CreateObject<PersistentMemberInfo>();

            persistentMemberInfo.Name = dbColumn.Name;

            persistentClassInfo.OwnMembers.Add(persistentMemberInfo);

        }

    }

    WorldCreator UI allows further extension of the model as simple as writing .NET code or creating new objects. More ideas and contributions are always welcome.

    Up to this point everything was extremely easy for us and almost shocking in terms of productivity! I believe there is no reason to change that feeling so lets move to our final task.

    WorldCreator is simply a code generation module. It generates assemblies which include XAF modules and loads them at application startup. However that assembly has no difference at all from the assemblies we create at design time. The persistent classes of this dynamic module belong and point back to main XAF database. What we want here is to redirect the generated sql statements back to the original mapped database.

    Once more we have most of the job ready! eXpand already uses a proxy version of ObjectSpaceProvider to support scenarios similar to show Business Classes from several databases in a XAF application. Thus associating a WordCreator assembly (set of business classes) with a database is a rather easy job.

    Connecting to any database at runtime at first sounded very complicated. However our frameworks proved once more that they can raise our productivity and make our jobs so simple that even such complex task can fit in a small post like this one.

    The new module DBMapper, is already released as part of eXpand framework’s modules collection.

    We would appreciate your feedback on this post. Has it been useful to you? Feel free to contact us with any further questions.

  • Take a tour of DXv2: XAF Q&A

         

    A bit late with this post,…but

    Check out the "Take a tour of DXv2: XAF” webinar as well as the "XAF - Application Server & Improved Security System" tutorial videos to get started with the newest version of the eXpressApp Framework (XAF).

    And don’t forget to check out the What’s New pages for both XAF and XPO:

    Finally, do not miss the new and updated help articles for these products located in the What’s New in Help document.

    I also wanted to answer a few of the more interesting questions left unanswered from our last webinar. So, here we go:

    Q: What are the main advantages of your application server and the improved security system? Why would one want to use them?
    A: In our opinion, every serious application for a medium or large enterprise requires a stable and solid security system that will ensure that clients only access data and perform operations they have permissions to. In the most cases, secure data filtering is done in the middle tier, thus preventing the client application from direct database connections. The client application usually connects to the middle tier server via Remoting, WCF or other popular data transport technologies. The middle tier application itself can be run as a console, Windows service application or be hosted as part of a web application on IIS.

    As you know, implementing, testing and maintaining even the core of such a system yourself will require enormous resources. Implementing GUI for it will also cost you a lot of time and money. In addition, if you Google the term, you will quickly find that it will require learning both a large number of technologies and numerous patterns & best practices available in papers created by Microsoft and many third-parties…

    With XAF you get all of this out-of-the-box and as a result you have a ready GUI + Core that is based on existing DevExpress technologies (we use DevExpress visual components for the UI and XPO for the application server and security core). Finally, note that the XAF security system supports defining permissions on the object type, object instance and member levels, as well as custom permissions.

    Q: What are the main difference between the old and new XAF security systems?
    A: The new XAF security system prevents client applications from retrieving sensitive data. All permission requests are redirected to the security service located on the application server. Your secure data is much safer now as it will not leave the server. Refer to this help article explaining these differences in greater detail. In addition, the new security system is accompanied with a more effective UI for editing security permissions – you now have a permissions matrix that I believe will be welcomed by your clients.

    Q: I am interested in the new application server & security system and just wanted to verify that if a user does not have permissions to an object / field, the respective information will not be displayed in reports, analysis, etc.
    A: Of course, it works as you would expect and these features were specially designed for these scenario. Security does restrict data on the server side so that it never appears in reports, analysis and elsewhere on the client side. For more information, check out the work schema. Note that to obtain all these benefits, you will need to configure security in the middle tier. Simply using the new security system (without implementing it in the middle tier) will not provide data filtering on the server side, because this is done by the middle tier service.

    Q: Does your new security system allow creating and plugging custom security permissions, i.e. not only permissions for business objects and their members? How do I implement a custom permission?
    A: Sure, much like the previous version, our new security system allows for this. A good example of a custom permission is “Edit Model" permission. Refer to the following Support Center ticket for a detailed description and a small sample project that demonstrates its implementation: http://www.devexpress.com/issue=Q358567

    Q: Is it necessary to host the application server on a separate machine as part of a console, Windows service application or a web application on IIS?
    A: No, it is absolutely unnecessary. The application server is a pure NET code that can be run anywhere you need, even on the client application. For instance, in our SecurityDemo, the application server is hosted in the same client application, but in a different AppDomain (check the ApplicationServerStarter class for the details). By default, we provide a Visual Studio Project Template that hosts the application server in a Windows service. We plan to provide additional templates based on the customer feedback. If you cannot wait, it is not difficult to make these templates yourself based on the defaults we provide – it is simply a matter of creating a corresponding application type (refer to MSDN for more details) and copying the required application server code.

    Q: Is there a way to encrypt or compress data between the application server and the client?
    A: There is no special XAF encrypting code because everything is already supported by underlying data transport technologies. For instance, refer to the  http://msdn.microsoft.com/en-US/library/k62k71x0(v=VS.80).aspx and http://msdn.microsoft.com/en-us/library/ms735093.aspx help articles to learn more.

    Q: Is Application server completely stateless?
    A: Yes, the application server is stateless. However, the server caches a database session and access rights for a particular client. It's not a long-living cache and this is not a state for the client application.

    Q: I heard that you are also planning to move some standard XAF functionality (audit trail, validation, etc.) to the server side, what if I also want to execute my business rules on the server? How do I proceed?
    A: Yes, you are right, we have such plans for the future. In the meantime, if you want to delegate business logic from the client to the server, you can implement a solution similar to that demonstrated in the following Support Center ticket: http://www.devexpress.com/issue=Q356933

    Q: Is there an easy and fast way to replace the old security system with new member-level security?
    A: Yes, we'll provide a sample converter that can be used to convert old permissions to new permissions for our built-in security objects (User, Role, SecuritySimple, SecurityComplex, etc.). I suggest you check out this discussion in the Support Center for more information.

    Q: I noticed there were still some postbacks during my Web application operation. Is it a bug?
    A: No, some tasks can be performed only via postback (e.g. file download, theme changes, etc.). However, we plan enhance our Web UI and you can see our plans in this blog post.

    Q: I like the new AJAX Web UI, but previously I used some custom user and third-party controls that operate via postbacks. Is it possible to force them to use AJAX as well?
    A: If a third-party control operates via postbacks and does not support AJAX itself, it's unlikely to switch it into AJAX. However, it will continue to operate via postbacks as before. As for your custom user controls, it is possible to convert them to AJAX-like controls. Please contact our Support Team for further instructions.

    Q: What is the best way to convert my existing Web application to 11.2 to use the improved AJAX functionality?
    A: As always, we recommend that you follow the instructions given in the Upgrade Notes help article. From this article you can also find links to the list of breaking changes and implemented features. Finally, we suggest you check out the eXpressApp Framework v11.2 ASP.NET Application Migration Guidelines we've prepared. If you experience any difficulties with the upgrade, feel free to contact our Support Team.

    Q: Do you provide any converter for rules created using obsolete ConditionalEditorState and ConditionalFormatting modules?
    A: Sure, we do. Please refer to the following KB Article: http://www.devexpress.com/kb=K18547.

    Q: What are your plans for the old security system? I also noticed that not all XAF demos migrated to the new security system.
    A: Yes, that is true about the demos. You might also notice that the old security is still described in docs. We decided not to migrate all demos to the new security system in this release because there are a lot of people who are using the old security and might even use it in the future as it is effective, even though it works at the UI level. However, migrating all our demos to the new security system is planned as well as complete replacement of the old security system. People who are using Domain Components can also track this suggestion – a DC-based demo based on the new security system.

    As always, we will also try to keep new videos, blogs and other training materials coming. If you have specific suggestions or just want to share your feedback on how we are doing, please drop us a line or simply email me at dennis@devexpress.com.

    Happy XAFingSmile

  • eXpand on Hanselminutes

         

    First of all I would like to say a big thank you to Scott for having me on his show. I really enjoyed our conversation even though they said I worked for one of our competitors in the intro!

    Framework Series: The eXpand Framework with Apostolis Bekiaris

    For those of you who have not had a chance to listen to the show yet Scott and I had an illuminating discussion about the benefits of open source. I found the comments Scott made about Microsoft’s attitude towards these kind of projects particularly revealing. Of course we found plenty of time to chat about eXpand, including some of the history of the project and the important role that our contributors play. It is clear that Scott recognizes the value of a healthy open source community like ours. Also on the agenda  were the advantages of the special relationship between XAF and eXpand as well as the support that DevExpress gives to the world of open source.

    Thanks again to all of you out there in the community this is your framework and we all deserve a share of the glory!

  • Hey Mom we are on the Hanselminutes show!

         

    At 11.00 PST on Thursday 15th December I will be appearing live on Scott Hanselman’s podcast Hanselminutes. During the course of the show Scott and I will be discussing eXpand framework and its relationship with XAF. Please tune in and show some support for your favorite frameworks! We built this thing together guys and this is an exciting event for all of us.

  • You have changes? I have Workflow!

         

    Let me describe for a moment how we at DevExpress work. We build and sell software which means that we only sell and provide support for products that have been built and tested by us! However I am here as a framework evangelist and huge XAF fan. This makes it my duty to spread the word as much as I can and make XAF even bigger. To this end through collaboration within the XAF community, we have been building and supporting eXpand. This framework follows XAF to the letter and takes things even further. eXpand gets its inspiration from real life situations and bases itself on examples from DevExpress Support Center. eXpand is the first open source project based on the DevExpress eXpressApp Framework (XAF). More info is available at www.expandframework.com and our very existence relies on your efforts! Anyone is welcome to contribute and enjoy the rewards. It is not necessary to be a XAF guru, we can all manage to create a behavior taken from DevExpress code central. Let’s work together to enhance our beloved XAF!

    WF4 uses a service oriented architecture and as a result any problem can be decoupled into smaller, easily solvable and testable services. XAF uses MVC architecture which, in a sense, is very similar to that used by WF4. We can compare XAF’s controllers to WF4 services. Moreover XAF’s Application does the same job as the WF4 server. The upshot of all this is that users should be able to get the feel of WF4 in no time at all. The XAF workflow module introduces a new layer that makes the already decoupled services aware of our business classes.  After this the sky is the limit and over the next few posts I aim to demonstrate some of what can be achieved. For example the next post will focus on creating an event driven workflow initialization engine.

    To get back to today’s post, we will discuss an implementation that is very decoupled and as a result it has very limited dependencies on other modules. It is worth noting that all XAF’s features are decoupled, persistent objects take on the role of domain mappers.

    Take these requirements;

    • an end user needs to be able to input an object type (and or) a property name,
    • an object change needs to start the workflow either at client or at sever,
    • workflows need to be aware of the object that has changed, its PropertyName and its property OldValue.

    The custom workflow definition

    We cannot use the default XAF XpoWorkFlowDefinition class in any way.  This is because there are no fields to store the PropertyName and its OldValue. We should not even derive from the default XpoWorkFlowDefinition because we may face difficulties as this class is used by our workflow server. To cope with this issue it is necessary to create a custom ObjectChangedWorkflow definition as shown.

    image

    While we are doing this we also need to modify the default xaml of the workflow and add the two more arguments (propertyName, oldValue) as per our requirements.

    image

    Below you can see the UI of this custom workflow definition,

    image

    Up to here XAF has made things very straightforward for us. We have designed a normal persistent class to store our data and we have used attributes (PropertyEditorType, DataStourceProperty, TypeConverter etc) to configure the UI.

    Registration of custom workflow definition

    The next step is to register this custom workflow definition. To help with this task, eXpand, provides the WorkflowStartService<T> where T is the type of workflow. Furthermore for ObjectChangeWorkflow definitions the implementation is rather easy since there are no further requirements.

    public class ObjectChangedWorkflowStartService : WorkflowStartService<ObjectChangedWorkflow> {

        public ObjectChangedWorkflowStartService()

            : base(TimeSpan.FromMinutes(1)) {

        }

        public ObjectChangedWorkflowStartService(TimeSpan requestsDetectionPeriod) : base(requestsDetectionPeriod) { }

        protected override bool NeedToStartWorkflow(IObjectSpace objectSpace, ObjectChangedWorkflow workflow) {

            return true;

        }

     

        protected override void AfterWorkFlowStarted(IObjectSpace objectSpace, ObjectChangedWorkflow workflow, Guid startWorkflow) {

     

        }

    }

    Start workflow - Track Object Changes

    Now, when I have registered workflows on the server, it's time to return to my task: start a workflow when a property has been changed.
    In XAF, I can track changes with the help of the ObjectSpace.Committing and ObjectSpace.ObjectChanged events. However because we need to create only one request per object change, it is advisable to collect the changes in an array.

    protected override void OnActivated() {

        base.OnActivated();

        if (TypeHasWorkflows()) {

            ObjectSpace.ObjectChanged += PopulateObjectChangedEventArgs;

            ObjectSpace.Committing += StartWorkFlows;

        }

    }

     

    void PopulateObjectChangedEventArgs(object sender, ObjectChangedEventArgs objectChangedEventArgs) {

        if (!string.IsNullOrEmpty(objectChangedEventArgs.PropertyName)) {

            var changedEventArgs = _objectChangedEventArgses.FirstOrDefault(args => args.Object == objectChangedEventArgs.Object && args.PropertyName == objectChangedEventArgs.PropertyName);

            if (changedEventArgs != null) {

                _objectChangedEventArgses.Remove(changedEventArgs);

                _objectChangedEventArgses.Add(new ObjectChangedEventArgs(changedEventArgs.Object, changedEventArgs.PropertyName, changedEventArgs.OldValue, objectChangedEventArgs.NewValue));

            } else

                _objectChangedEventArgses.Add(objectChangedEventArgs);

        }

    }

     

    void StartWorkFlow(ObjectChangedEventArgs objectChangedEventArgs, ObjectChangedWorkflow objectChangedWorkflow) {

        var o = objectChangedEventArgs.Object;

        ITypeInfo typeInfo = XafTypesInfo.Instance.FindTypeInfo(o.GetType());

        object targetObjectKey = typeInfo.KeyMember.GetValue(o);

        if (objectChangedWorkflow.ExecutionDomain == ExecutionDomain.Server) {

            CreateServerRequest(objectChangedEventArgs, objectChangedWorkflow, targetObjectKey, typeInfo);

        } else {

            InvokeOnClient(objectChangedEventArgs, objectChangedWorkflow, targetObjectKey);

        }

    }

    As you will have noticed we have not used the default VS naming for ObjectSpace event handlers. This is because the names that have chosen give a more specific idea of how each method works.

    The ObjectChanged event occurs each time a property is changed and the changes are collected in the objectChangedEventArgses array. The Committing event occurs once changes are ready to be sent to the server and workflows start for each entry. We have introduced two options for starting and executing workflows;

    1. Execute synchronously and locally,
    2. Send a request to the server and execute at the server asynchronously

    Execute a workflow synchronously on the client

    The next stage is to create activities at the client then on ObjectSpace CommitChanges from appropriate WorkflowDefinition and execute them immediatelly

    public class StartWorkflowOnObjectChangeController : ViewController<ObjectView> {

     

        void InvokeOnClient(ObjectChangedEventArgs objectChangedEventArgs, ObjectChangedWorkflow objectChangedWorkflow, object targetObjectKey) {

            Activity activity = ActivityXamlServices.Load(new StringReader(objectChangedWorkflow.Xaml));

            var dictionary = ObjectChangedStartWorkflowService.Dictionary(targetObjectKey, objectChangedEventArgs.PropertyName, objectChangedEventArgs.OldValue);

            WorkflowInvoker.Invoke(activity, dictionary);

        }


    This is a simple code which can be found in nearly any WF4 example at http://www.microsoft.com/download/en/details.aspx?id=21459.

    Send a request to start workflow on the server

    The second of our two methods involves starting the workflow at the server. Now we need to notify the server of the values of those arguments as well. In the manually starting workflows post we learnt that XAF does this by using XpoStartWorkflowRequest. This class has a different design however, and may create issues since it is used by XAF default services. Therefore instead of deriving from XpoStartWorkflowRequest we need to design a similar custom class.

    public class ObjectChangedXpoStartWorkflowRequest : WFBaseObject, IObjectChangedWorkflowRequest {

     

        [TypeConverter(typeof(StringToTypeConverter))]

        public Type TargetObjectType {

            get { return _targetObjectType; }

            set { SetPropertyValue("TargetObjectType", ref _targetObjectType, value); }

        }

        #region IDCStartWorkflowRequest Members

        public string TargetWorkflowUniqueId {

            get { return GetPropertyValue<string>("TargetWorkflowUniqueId"); }

            set { SetPropertyValue("TargetWorkflowUniqueId", value); }

        }

     

        [ValueConverter(typeof(KeyConverter))]

        public object TargetObjectKey {

            get { return GetPropertyValue<object>("TargetObjectKey"); }

            set { SetPropertyValue<object>("TargetObjectKey", value); }

        }

        #endregion

        #region IObjectChangedWorkflowRequest Members

        public string PropertyName {

            get { return _propertyName; }

            set { SetPropertyValue("PropertyName", ref _propertyName, value); }

        }

     

        [ValueConverter(typeof(SerializableObjectConverter))]

        [Size(SizeAttribute.Unlimited)]

        public object OldValue {

            get { return _oldValue; }

            set { SetPropertyValue("OldValue", ref _oldValue, value); }

        }

    This is a very simple class, its only role is to store values in the database. Now instead of invoking workflows locally we only need to create ObjectChangedXpoStartWorkflowRequest objects.

    public class StartWorkflowOnObjectChangeController : ViewController<ObjectView> {

        void CreateServerRequest(ObjectChangedEventArgs objectChangedEventArgs, ObjectChangedWorkflow objectChangedWorkflow, object targetObjectKey, ITypeInfo typeInfo) {

            var request = ObjectSpace.CreateObject<ObjectChangedXpoStartWorkflowRequest>();

            request.TargetWorkflowUniqueId = objectChangedWorkflow.GetUniqueId();

            request.TargetObjectType = typeInfo.Type;

            request.TargetObjectKey = targetObjectKey;

            request.PropertyName = objectChangedEventArgs.PropertyName;

            request.OldValue = GetOldValue(objectChangedEventArgs);

        }

    In the next step we are going to create a service to consume these values from the server and start a workflow,

    public class StartWorkflowOnObjectChangeService : BaseTimerService {

        public override void OnTimer() {

            using (var objectSpace = ObjectSpaceProvider.CreateObjectSpace()) {

                //get all requests from the database

                foreach (var request in objectSpace.GetObjects<ObjectChangedXpoStartWorkflowRequest>()) {

                    //find workflow

                    var definition = GetService<IWorkflowDefinitionProvider>().FindDefinition(request.TargetWorkflowUniqueId);

                    if (definition != null && definition.CanOpenHost) {

                        //Start the workflow passing in PropertyName && OldValue

                        if (GetService<ObjectChangedStartWorkflowService>().StartWorkflow(definition.Name,

                            request.TargetWorkflowUniqueId, request.TargetObjectKey, request.PropertyName, request.OldValue)) {

                            objectSpace.Delete(request);

                            objectSpace.CommitChanges();

                        }

                    }

     

                }

            }

        }

    At this point our server has all the information it needs to start workflows with arguments taken from persistent ObjectChangeXpoStartWorkFlowRequest objects.

    I must admit that I have fully enjoyed preparing this post. The decoupled development experienced offered by the WF service oriented model is something that really appeals to me. At the same time XAF’s workflow module implementation made modeling the requirements a simple and enjoyable process. As usual it was possible to work directly on the problem and leave the hard work to non XAF developers.

    We are happy to read your feedback about this!. Remember that your questions are the best candidates for future posts

  • Access eXpand from the Start menu (coming in v2011 vol 2)

         

    In the upcoming release of DXperience v2011 vol 2, we have made it easier for new and existing users to discover the great capabilities of our eXpressApp Framework (XAF) via eXpand  - the first open source framework built based on the XAF infrastructure and providing extra modules to its developers:

    screenshot

    For those who are not yet familiar with eXpand, let me quote a more detailed description from their web site:

    “…The eXpand Framework team have extended the capabilities of the eXpressApp Framework to include 57 cutting-edge assemblies containing tools and modules that target numerous business scenarios. The main idea behind eXpand is to offer as many features as possible to developers/business users through a declarative approach (configuring files rather than writing code). Please go through each of the following brief descriptions and find out how eXpand can help you accomplish your complex development tasks with easy declarative programming…”

    I hope that you were pleased by this news too. Please let us know in comments to this blog.

    Happy XAFingWinking smile

  • Improvements to AJAX and Performance in XAF ASP.NET UI (coming in v2011 vol 2)

         

    Recently I sat down with a few members of our eXpressApp Framework Team to discuss some of the features we'll introduce in the upcoming release of DXperience v2011 vol 2. Here are Serge K, Leo K DiCaprio  and Dmitry S in their own words...

    HolyXAF3

    Q: Guys, briefly describe what you have achieved in this release.

    A: XAF ASP.NET applications now use AJAX-based rendering for nearly everything. This means that only small modified elements of the web page markup are sent from the web server to the client’s web browser via callbacks. Thus, the web page is now updated smoothly. If a part of the page is static, there is no need to render it by the web server on each HTTP request and send its markup to the client.

    Q: How will these improvements affect performance and traffic?

    A: Actually “performance” is a very broad term and there are a lot of metrics to measure it. Let’s address some web request-response cycle steps affected by our improvements. As you know, every web request takes time to connect to the web server, to send a request data to the server, to process this request, to render a result, to send this result to a browser, to render the received HTML in the browser, to process startup JavaScript and after that an end-user can interact with the page again. Previously, we reduced the “process-request” time in the described cycle. We have now improved the other aspects. Web applications now produce about 25% less HTTP requests than before. In other words, since the web server can now render only small portions of the page and not the whole thing, it can allocate ¼ of its work time to better serve other users requests. Based on measurements, the web server now produces 3 times less HTML markup, which can also be transported 3 times faster through the wire (these numbers may vary depending on the end application UI). It is also important to note that now the first request is processed much faster, and an end-user can start interacting with the page before the startup view is fully loaded. Also, web browser now executes common startup Java Script code only once when you open the application’s startup page.

    Q: I presume it significantly improves the overall usability? In other words, what does it mean for end-users?

    A: Of course, end-users will love these enhancements because the application is now more responsive and performs smoothly. For instance, imagine that you have a detail form with payment info and want to calculate its amount  based on some rate and man hour values. When you change these values, the amount should be automatically updated. This now works much more smoothly, without any reloads of the page. Our measurements showed that in v2011 vol 2 the same scenario can be performed 1.5 times faster than before.

    Another nice addition, which is worth mentioning here, is that while working on this feature we overcame previous limitations preventing the web browser’s Back and Forward buttons from functioning correctly under certain circumstances.

    Q: What do you plan to change or improve in future versions of the XAF ASP.NET?

    A: First and foremost improvement will continue in the area of performance. As you know, we have been committed to improving overall application performance through our latest releases (one, two, three). That has allowed us to drastically reduce web page size and the number of requests sent to the web server  (and hence overall traffic). We are confident that we have not yet pushed it to its limit and we believe we can continue our optimizations in future versions.

    There are also a couple of other interesting new features from our backlog worth mentioning:

    • Implement simpler and more user-friendly URLs for XAF Views;
    • Replace standard web browser popup windows with the ASPxPopupControl.

    These are the most popular requests related to ASP.NET UI improvement from our customers.

    Demonstration

    The team prepared a short video demonstrating how the MainDemo.Web application shipped with XAF operates in v2011 vol 2 (the video is large, so you may want to right-click and choose the “Show All” option):

    --> Get Adobe Flash player -->

    Do you like what you have read or seen? Please let us known. You input is greatly appreciated!

    Happy XAFingWinking smile

  • Creating a State Machine module for eXpand Framework–Part 2

         

    Let me describe for a moment how we at DevExpress work. We build and sell software which means that we only sell and provide support for products that have been built and tested by us! However I am here as a framework evangelist and huge XAF fan. This makes it my duty to spread the word as much as I can and make XAF even bigger. To this end through collaboration within the XAF community, we have been building and supporting eXpand. This framework follows XAF to the letter and takes things even further. eXpand gets its inspiration from real life situations and bases itself on examples from DevExpress Support Center. eXpand is the first open source project based on the DevExpress eXpressApp Framework (XAF). More info is available at www.expandframework.com and our very existence relies on your efforts! Anyone is welcome to contribute and enjoy the rewards. It is not necessary to be a XAF guru, we can all manage to create a behavior taken from DevExpress code central. Let’s work together to enhance our beloved XAF!

    Prerequisites
    Part 1

    In this post we are going to enhance the State Machine module UI. Remember that along with all the usual XAF goodies we can now use Xpand code base which gives us a lot more options. Our StateMachineTransitionPermission has 2 lookups, StateMachineName and StateMachine. Our goal is to populate both of these cascading lookups without creating a platform specific module.

    StateMachineNames

    Creating lookups is a common scenario for which Xpand provides a set of property editors and controllers. By contrast with other business frameworks XAF allows maximum flexibility. Therefore in most cases we are able to code in such a generic way that everything could live in separate frameworks such as eXpand. Now, in order to populate the StateMachine name I am going to derive a new controller from a specialized abstract controller which is Xpand.ExpressApp.SystemModule.PopulateController<T>. This controller uses the PredefinedValues attribute of the XAF model. When filling the attribute with a set of values separated by semicolons XAF will create a lookup with these values targeting each supported platform.

    image

    However, if at runtime we set the value of the PredefinedValues attribute this will be written at model’s lastlayer and it will make it dirty. We want to avoid this because we want to leave the lastlayer intact.. To cater for this need the populate controller uses a hack. First it stores the lastlayer in a variable then removes it from the model’s layers collection. As a result it is possible to modify the new lastlayer as shown in the Populate method and then return the clean old one to its place. Now the model has all the necessary information with a clean userdiffs layer and while XAF is creating a new view can get the PredefinedValues string from it and create the lookups.

    public abstract class PopulateController<T> : ViewController<ObjectView> {

       

        …

     

        protected virtual void Populate(Func<IModelMember, string> collect) {

            var name = PropertyName;

            if (name != null) {

                var model = ((ModelApplicationBase)Application.Model);

                var lastLayer = model.LastLayer;

                model.RemoveLayer(lastLayer);

                PopulateCore(collect, name);

                model.AddLayer(lastLayer);

           }

       }

     

        private void PopulateCore(Func<IModelMember, string> collect, string propertyName) {

            IModelMember modelMember = View.Model.ModelClass.AllMembers.FirstOrDefault(member => member.Name == propertyName);

            if (modelMember != null) {

                modelMember.PredefinedValues = collect.Invoke(modelMember);

            }

        }

        …

        …

       }

     

    Although this seems like a complicated explanation users need not be intimidated! The implementation of our controller that will populate all StateMachineNames is as simple as this,

    public class StateMachinePopulateController : PopulateController<StateMachineTransitionPermission> {

        protected override string GetPredefinedValues(IModelMember wrapper) {

            IList<XpoStateMachine> xpoStateMachines = ObjectSpace.GetObjects<XpoStateMachine>(null);

            return xpoStateMachines.Select(machine => machine.Name).AggregateWith(";");

        }

     

        protected override Expression<Func<StateMachineTransitionPermission, object>> GetPropertyName() {

            return permission => permission.StateMachineName;

        }

    }

     

    The first thing we did was to provide the propertyName in the GetPropertyName method. Then using the GetPredifinedalues method we return the semincolon delimited string with the machine names. This very simple controller is capable of populating the statemachine lookup for win and web platforms!.
     
    StateCaptions
    This is a cascading lookup and as a result when the current StateMachineName changes it needs to provide a list of all its StateCaptions. To this end we are going to use a specialized property editor, Xpand’s StringLookupEditor. This supports the DataSourceProperty XAF attribute which will be used to provide the StateCaption collection. Moreover when using Xpand it is possible to mark editors with an interface and host it in a transparent module. We can then use the Xpand PropertyEditor attribute with the type of the interface as parameter to tell XAF which propertyeditor will be created at runtime. Finally we need to apply all these along with an ImmediatePostData to the StateMachineName property. The permission will look like this,
     

    [ImmediatePostData]

    public string StateMachineName { get; set; }

     

    //IStringLookupPropertyEditor lives in Xpand.ExpressApp assembly

    //Xpand.ExpressApp.Web.PropertyEditors.StringLookupPropertyEditor, Xpand.ExpressApp.Win.PropertyEditors.StringLookupPropertyEditor inherit from IStringLookupPropertyEditor

    [PropertyEditor(typeof(IStringLookupPropertyEditor))]

    [DataSourceProperty("StateCaptions")]

    public string StateCaption { get; set; }

     

    IList<string> _stateCaptions = new List<string>();

    [Browsable(false)]

    public IList<string> StateCaptions {get {return _stateCaptions;}}

     

    If you look carefully at this code however you may notice that __stateCaptions count is always zero. Let me remind you here that the StateMachineTransitionPermission is a non persistent sessionless object. This means that the object is not handled by an ObjectSpace therefore a call like ObjectSpace.FindObjectSpaceByObject(this) will always return null. In addition the permission does not implement INotifyPropertyChanged so we need to synchronize the class just before the StateCaptions are requested. Below you can see a modified version of the StateMachinePopulateController,

     

    public class StateMachinePopulateController : PopulateController<StateMachineTransitionPermission> {

        protected override void OnViewControlsCreated() {

            base.OnViewControlsCreated();

            var stringLookupPropertyEditor = GetPropertyEditor(permission => permission.StateCaption) as IStringLookupPropertyEditor;

            if (stringLookupPropertyEditor != null)

                stringLookupPropertyEditor.ItemsCalculating += StringLookupPropertyEditorOnItemsCalculating;

        }

        void StringLookupPropertyEditorOnItemsCalculating(object sender, HandledEventArgs handledEventArgs) {

            var propertyEditor = GetPropertyEditor(permission => permission.StateMachineName);

            if (propertyEditor != null && View.IsControlCreated) {

                var stateMachineTransitionPermission = ((StateMachineTransitionPermission)View.CurrentObject);

                var readOnlyCollection = GetStateCaptions(propertyEditor);

                stateMachineTransitionPermission.SyncStateCaptions(readOnlyCollection, propertyEditor.ControlValue as string);

            }

        }

     

        ReadOnlyCollection<string> GetStateCaptions(PropertyEditor propertyEditor) {

            var stateMachineName = propertyEditor.ControlValue as string;

            return ObjectSpace.GetObjects<XpoState>(state => state.StateMachine.Name == stateMachineName).Select(

                    state => state.Caption).ToList().AsReadOnly();

        }

     

    Finally we add the new SyncStateCaptions method and the full version of the permission will be,

     

    [NonPersistent]

    public class StateMachineTransitionPermission : PermissionBase {

        …

        …

     

        [ImmediatePostData]

        public string StateMachineName { get; set; }

     

        [PropertyEditor(typeof(IStringLookupPropertyEditor))]

        [DataSourceProperty("StateCaptions")]

        public string StateCaption { get; set; }

     

        IList<string> _stateCaptions = new List<string>();

        [Browsable(false)]

        public IList<string> StateCaptions {get {return _stateCaptions;}}

     

        public void SyncStateCaptions(IList<string> stateCaptions, string machineName) {

            StateMachineName = machineName;

           _stateCaptions = stateCaptions;

        }

    }

    To support platform independent cascading lookups we wrote only about 10 lines of code! This is proof of how much XAF architecture cuts down on development costs. The module can be downloaded from the Xpand download page   and we are happy to hear your feedback. Remember that your questions are the best candidates for future posts!

  • eXpand Framework calculated members creation—Pros and Cons

         

    Let me describe for a moment how we at DevExpress work. We build and sell software which means that we only sell and provide support for products that have been built and tested by us! However I am here as a framework evangelist and huge XAF fan. This makes it my duty to spread the word as much as I can and make XAF even bigger. To this end through collaboration within the XAF community, we have been building and supporting eXpand. This framework follows XAF to the letter and takes things even further. eXpand gets its inspiration from real life situations and bases itself on examples from DevExpress Support Center. eXpand is the first open source project based on the DevExpress eXpressApp Framework (XAF). More info is available at www.expandframework.com and our very existence relies on your efforts! Anyone is welcome to contribute and enjoy the rewards. It is not necessary to be a XAF guru, we can all manage to create a behavior taken from DevExpress code central. Let’s work together to enhance our beloved XAF!

    As promised in the previous post I will now attempt to provide a concise yet comprehensive look at the 5 possibilities that Xpand gives us when we want to create a calculated member. I will also provide discussion of the relative advantages and disadvantages of each approach. We can see all of them in action in Xpand FeatureCenter application. Remember it is only thanks to the fact that XAF/XPO have such a strong and flexible architecture that this is possible! We must also acknowledge that these approaches have evolved as a direct result of contributions from the XAF team and community.

    image

    1. The XPO way –>Using Code

    Take a look at the CreateCalculabeMember extension method in the code below,

    public class CreateRuntimeCalculatedFieldController : ViewController {

        public override void CustomizeTypesInfo(DevExpress.ExpressApp.DC.ITypesInfo typesInfo) {

            base.CustomizeTypesInfo(typesInfo);

            XPClassInfo classInfo = XafTypesInfo.XpoTypeInfoSource.XPDictionary.GetClassInfo(typeof(Customer));

            if (classInfo.FindMember("SumOfOrderTotals")==null) {

                var attributes = new Attribute[] {new PersistentAliasAttribute("Orders.Sum(Total)")};

                XPCustomMemberInfo calculabeMember = classInfo.CreateCalculabeMember("SumOfOrderTotals", typeof(float), attributes);

                typesInfo.RefreshInfo(typeof(Customer));

            }

        }

    }

     

    XPO has a dictionary of domain metadata. The metadata of each persistent object is stored in XPClassInfo classes and the metadata of their properties is stored in XPMemberInfo classes. One of the main advantages of this approach is that it  adds a new member to the XPO dictionary and therefore follows XAF to the letter. This is because in order to form the model XAF first queries the XPO dictionary and finally in order to configure the views it queries the model. Since we have worked in the data layer our calculated values will be sent to any data bound enabled control for rendering. The other benefit is that if we code there are no restrictions on what we can do, for example we can create members calling a WCF service. The sky’s the limit!

    On the other hand each time we write new code we need to spend time testing and distributing it. Furthermore in certain scenarios problems can occur due to the fact that we add a new member to the object. For each new member we add to an object we are forced to deal with long properties lists in our model which can be somewhat unwieldy – imagine an  object with 200 properties.

    Note; XAF is smart enough to manage all of this without even breaking a sweat. This means that its performance does not suffer in any way. It is simply that this approach can leave the user with a bit of a headache!

    2. Using the model

    We have extended our model in order to describe all types of calculated and runtime properties.

     

    image_thumb[14]

     

    Having done this makes it pretty easy to utilize the powerful XPO and add members in its dictionary as with the previous approach. This means this method shares some of the benefits we mentioned above. However as we are not writing code we can’t enjoy the same level of flexibility unless we utilize ModelUpdaters. Also as the columns can only be created using model editor they are only useful in situations when we have permission to modify the model. Finally we could end up with a huge number of properties here too for the same reason we identified previously.

     

    All this is not to say that this approach doesn’t have its own unique advantages. For example the model difference can be stored in a database or xml file making it easy to distribute. To this end we can use the build in API or a specialized module like IO. Moreover it is possible to develop on site (client). Of course working at the model level allows us to use a model manager module like ModelDifference which is a great aid. It can be used to distribute the unbound columns to users, roles and even to other applications. In addition since ModelDifference supports both platforms it is possible to create calculated members without restarting the application or IIS.

    3.WorldCreator extended members

    This module maps the structure of the XPMemberInfo class to a persistent object. This approach is again similar to model approach (and once again has similar benefits) however there is a crucial difference. Instead of using the model to gather data to form the calculated members we use the input taken from the UI.

    image_thumb[17]image_thumb[20]

    Using the UI is simplicity itself! It requires no technical knowledge whatsoever as the user is only required to choose from a set of basic options. We can still code if we wish, this time by creating persistent objects and then leaving eXpand to take care of the rest. That being said the real beauty of this approach is that the product can be developed on site without the user having to write a single line of code or using a sophisticated tool like Model Editor. Moreover we can enjoy ease of distribution due to the fact that our objects are stored in the database. As the metadata is now in the form of persistent objects locating it and working with it is as easy as ever.

    By now it should be clear that as we are still relying on XPO we are faced with the same old problem regarding multiple views.

    4. Using a WordCreator Dynamic Assembly

    Our fourth approach uses the same module to create dynamic persistent assemblies using code generation templates. XAF is the best framework to describe domains which is evidenced by the way that  WorldCreator maps the Assembly structure to persistent objects and auto generates a flexible UI.

    image_thumb[23]

    Using the templates will create a dynamic assembly with exactly the same code and structure as if we had taken the time to design it ourselves inside VS. Distribution is still easy since is everything is in the database. The fact that we script at runtime means that our options are almost unlimited when taking this approach.

    5. The Unbound Column

    Extending the model with an Unbound column node as shown makes it possible to create Unbound grid columns and set their unbound expressions.

    image

     

    image

    This is the only approach that allows us to work directly on views without utilizing XPO. This means that we gain the maximum level of flexibility since it is possible to have different columns for the same object views. Therefore we can work on this column independently. At the same time the end user can change the UnboundExpression at runtime using expression editor (windows only). When it comes to distribution we find the same advantages as we do whenever we deal with the model.

    As with the second approach we lose some flexibility because we are not writing code but again we can get round this using ModelUpdaters. In addition our columns still cannot be used when we do not have permission to modify the model. Another disadvantage concerns the fact that XAF is designed to make all calculations in the data layer and send the values to controls by applying an MVC pattern. A few years after XAF was released, Microsoft built Silverlight featuring very similar architecture. Taking into account the various factors this has been recognized as the optimal approach. Although using Unbound columns allows us to work in a different way we need to write extra code to support each control (Tree, Pivot etc) because the calculations are performed in the UI.


    We are happy to read your feedback about this!. Remember that your questions are the best candidates for future posts.

  • eXpandFrameWork Supporting Unbound Columns

         

    Let me describe for a moment how we at DevExpress work. We build and sell software which means that we only sell and provide support for products that have been built and tested by us! However I am here as a framework evangelist and huge XAF fan. This makes it my duty to spread the word as much as I can and make XAF even bigger. To this end through collaboration within the XAF community, we have been building and supporting eXpand. This framework follows XAF to the letter and takes things even further. eXpand gets its inspiration from real life situations and bases itself on examples from DevExpress Support Center. eXpand is the first open source project based on the DevExpress eXpressApp Framework (XAF). More info is available at www.expandframework.com and our very existence relies on your efforts! Anyone is welcome to contribute and enjoy the rewards. It is not necessary to be a XAF guru, we can all manage to create a behavior taken from DevExpress code central. Let’s work together to enhance our beloved XAF!

    Recently in Xpand forums Dionisis Soldatos raised a question about how unbound columns can be implemented with XAF. Unbound columns along with their UnboundExpression can be used for creating calculated fields even at runtime. Since we are talking about unbound grid columns it should be obvious that we will operate at the UI level by modifying the grid control columns. However lets do a deep dive inside XAF model to extend it as needed!

    The Model

    By now we are all used to XAF providing us with excellent out of the box solutions which negate the need for us to write hundredths of lines of code. This of course means money saved during developing and ultimately your product hits the market faster. Why spend time reinventing the wheel when the XAF team have already done the hard work for you?

    XAF creates the model by reading the metadata of our classes, this model has 3 types of view. One of these is the ListView which can be displayed with data source enabled controls like Grid controls. ListView has columns which correspond to existing object properties metadata and when XAF creates a Grid at runtime it queries model’s ListView columns. It then creates and configures Grid columns from their attributes. These stages are well tested and it is preferable to use them in our solution and override the unnecessary stages. For example we could create a normal model column node using XAF default Add/Column menu. After the Grid column is created it we simply need a few lines of code to make it unbound and set its Unbound Expression.

     

    image

     

    In order to store this expression we still need to extend model’s ListView with an attribute. The model can be extended either by registering an interface at ModuleBase.ExtendModelInterfaces or by deriving it from an already registered interface. I am going to take the latter options by deriving from IModelColumn interface which I will explain as we go.

    public interface IModelColumnUnbound : IModelColumn {

     

        [Category("eXpand")]

        bool ShowUnboundExpressionMenu { get; set; }

     

        [Category("eXpand")]

        [Required]

        string UnboundExpression { get; set; }

    }

    XAF model editor is a highly sophisticated tool which has the capability to recognize that we extended the model. It then takes care of the vital step of adding an entry to the Add menu for creating Unbound columns.

    image

    Now it is possible to create a new type of column with 2 extra attributes as shown,

    image

    Moving on we need to set the mandatory PropertyName attribute shown above to an always existing object property name. Remember XAF requires this in order to behave as designed. To this end we are going to set as PropertyName the object’s key property name using this simple DomainLogic class,

    [DomainLogic(typeof(IModelColumnUnbound))]

    public class IModelColumnUnboundLogic {

        public static string Get_PropertyName(IModelColumnUnbound columnUnbound) {

            return ((IModelListView)columnUnbound.Parent.Parent).ModelClass.KeyProperty;

        }

    As a result (PropertyName, PropertyEditorType and Caption) attributes will be populated the next time we create a ColumnUnbound Node. However these will be fixed values and it is preferable to hide them from the end user. At the same time we need to mark Caption attribute as required and remove its default value. To do all of this we just need to extend our IModelColumnUnbound interface like this,

    image

    Note; Although PropertyName and Caption belong to IModelColumn using the new operator it is possible to override them!

    We have now finished with the model modifications and for our ColumnUnbound nodes XAF by design will create a new column pointing back to object’s key property metadata.

    The UI

    A key benefit of XAF’s commitment to design patterns, specifically to the Single responsibility principle, is that it provides us with the model’s synchronizer classes. These can be used to synchronize our model with the control and vice versa. It is only necessary to derive from the abstract ModelSyncroniser<T,V> and implement ApplyModeCore method to synchronize the control and from SynchronizeModel to do the same with the model.

    public class c: ModelSynchronizer<GridListEditor, IModelListView> {

        public UnboundColumnSynchronizer(GridListEditor control, IModelListView model)

            : base(control, model) {

        }

     

        protected override void ApplyModelCore() {

            var xafGridColumns = GetXafGridColumns();

            foreach (var column in xafGridColumns) {

                var modelColumnUnbound = (IModelColumnUnbound)column.Model;

                column.FieldName = modelColumnUnbound.Id;

                column.UnboundType = UnboundColumnType.Object;

                column.OptionsColumn.AllowEdit = false;

                column.ShowUnboundExpressionMenu = modelColumnUnbound.ShowUnboundExpressionMenu;

                column.UnboundExpression = modelColumnUnbound.UnboundExpression;

            }

        }

     

        IEnumerable<XafGridColumn> GetXafGridColumns() {

            IEnumerable<XafGridColumn> xafGridColumns =

                Model.Columns.OfType<IModelColumnUnbound>().Select(

                    unbound => Control.GridView.Columns[unbound.PropertyName] as XafGridColumn).Where(column => column != null);

            return xafGridColumns;

        }

     

        public override void SynchronizeModel() {

            var xafGridColumns = GetXafGridColumns();

            foreach (var xafGridColumn in xafGridColumns) {

                ((IModelColumnUnbound) xafGridColumn.Model).UnboundExpression = xafGridColumn.UnboundExpression;

            }

        }

    }

     

     

    The above code uses the GetXafGridColumns method to return the grid columns that correspond to IModelColumnUnbound nodes. The web implementation is very similar and can be found here.

    All that is left is to register our UnboundColumnSynchronizer like this,

    public class UnboundColumnController : ViewController<ListView> {

        protected override void OnActivated() {

            base.OnActivated();

            var gridListEditor = View.Editor as GridListEditor;

            if (gridListEditor != null)

                gridListEditor.CreateCustomModelSynchronizer += GridListEditorOnCreateCustomModelSynchronizer;

        }

     

        void GridListEditorOnCreateCustomModelSynchronizer(object sender, CreateCustomModelSynchronizerEventArgs createCustomModelSynchronizerEventArgs) {

            createCustomModelSynchronizerEventArgs.ModelSynchronizer = new UnboundColumnSynchronizer((GridListEditor)sender, View.Model);

        }

    }

     

    Note; Setting ShowUnboundExpressionMenu to true is only supported by Windows platform. There, an end user can modify the UnBoundExpression by invoking Grid’s expression editor

    image image

    Together with the unbound column Xpand allows for up to 5 different approaches to creating calculated fields. In the next post we will discuss the pros and cons of each approach so stay tuned!

    We are happy to read your feedback about this!. Remember that your questions are the best candidates for future posts

  • Checking whether the currently logged user belongs to a certain role in a filter becomes easier in 11.1.7

         

    Prerequisites

    I am confident that every user who utilized XAF’s Security module with the Complex Security strategy should have met this requirement at least once using XAF, for example, when you had to filter out a ListView to display records only for people from the Administrators role and hide them from the rest. Or, you wanted to make your favorite Appearance or Validation rule work only for people from the Users role? Sound familiar?

    A good way to address such requirements is to implement a custom function criteria operator. Tolis recently demonstrated how it can be done in his recent blog post about applying security to the State Machine module. The first time I saw the blog, I thought that it would be nice to have such a function in XAF out-of-the-box. So, shortly thereafter, after seeing a discussion on the forum, I logged a corresponding feature request.

    New built-in criteria function

    This feature request was implemented in version 11.1.7, and that means that you can already make use of the new IsCurrentUserInRole function in your criteria. The function’s use is very simple. All that you need to do is to pass the name of the role as a parameter:

    IsCurrentUserInRole(‘Administrators’)

    I expect that this built-in criteria function will be no less popular than the CurrentUserId()  function and will also save you a lot of time, because the described requirements are quite common in business applications.

    Future plans

    While we are talking about custom criteria functions, a note about our future plans. Although XAF already provides a similar feature called Read-Only Parameters, we are gradually stepping away from it and moving towards custom criteria functions everywhere. This is because they provide more capabilities (e.g. they are supported by all DevExpress products and not only in XAF; functions can accept arguments whereas Read Only Parameters are constants, etc.). It is intended not only to optimize our support costs, but also to allow a faster evolution of our products.

    Do you like this small improvement? Please let us know your opinion! Happy XAFing!Winking smile

  • Scheduling workflows in eXpandFrameWork

         

    Let me describe for a moment how we at DevExpress work. We build and sell software which means that we only sell and provide support for products that have been built and tested by us! However I am here as a framework evangelist and huge XAF fan. This makes it my duty to spread the word as much as I can and make XAF even bigger. To this end through collaboration within the XAF community, we have been building and supporting eXpand. This framework follows XAF to the letter and takes things even further. eXpand gets its inspiration from real life situations and bases itself on examples from DevExpress Support Center. eXpand is the first open source project based on the DevExpress eXpressApp Framework (XAF). More info is available at www.expandframework.com and our very existence relies on your efforts! Anyone is welcome to contribute and enjoy the rewards. It is not necessary to be a XAF guru, we can all manage to create a behavior taken from DevExpress code central. Let’s work together to enhance our beloved XAF!

    In this post we are going to extend the functionality of the workflow module. to create a UI that will help us to schedule workflows. Some of you may recall that we looked at using a Delay inside a While activity in Working with CRUD activities – Short Transactions. Recently, DX-Squad member Martin Praxmarer raised an interesting question relating to this topic:

    I have the requirement to do a workflow which starts each day on 6 clock - searches for orderdocuments where a specific date is less then X days. I know I will do an do while loop, but workflow definition has 2 options, start when new object, start when criteria, so when do i start this Workflow?

    In order to achieve this we will use the WorkFlow demo that ships with our framework. The first thing is to design our custom ScheduledWorkflow persistent object by implementing IWorkflowDefinition. We didn’t derive it from the existing WorkFlowDefinition object because it has properties like TargetObjectType and start up conditions.

    public enum StartMode {

        OneTime,

        Daily,

        Weekly

    }

     

    [DefaultClassOptions]

    [Appearance("WeekDays", "StartMode <> 'Weekly'",

        TargetItems = "RecurEveryWeeks;Moday;Tuesday;Wednesday;Thursday;Friday;Saturday;Sunday",

        Visibility = ViewItemVisibility.Hide)]

    public class ScheduledWorkflow : BaseObject, IWorkflowDefinition {

        public ScheduledWorkflow(Session session)

            : base(session) {

        }

     

        public bool IsActive {

            get { return GetPropertyValue<bool>("IsActive"); }

            set { SetPropertyValue("IsActive", value); }

        }

     

        public bool RuntASAPIfScheduledStartIsMissed {

            get { return GetPropertyValue<bool>("RuntASAPIfScheduledStartIsMissed"); }

            set { SetPropertyValue("RuntASAPIfScheduledStartIsMissed", value); }

        }

     

        [Association]

        public XPCollection<ScheduledWorkflowLaunchHistory> LaunchHistoryItems {

            get { return GetCollection<ScheduledWorkflowLaunchHistory>("LaunchHistoryItems"); }

        }

     

        [ImmediatePostData]

        public StartMode StartMode {

            get { return GetPropertyValue<StartMode>("StartMode"); }

            set { SetPropertyValue("StartMode", value); }

        }

     

        public TimeSpan StartTime {

            get { return GetPropertyValue<TimeSpan>("StartTime"); }

            set { SetPropertyValue("StartTime", value); }

        }

     

        [Appearance("RecurEveryDays", "StartMode <> 'Daily'", Visibility = ViewItemVisibility.Hide)]

        public int RecurEveryDays {

            get { return GetPropertyValue<int>("RecurEveryDays"); }

            set { SetPropertyValue("RecurEveryDays", value); }

        }

     

        public int RecurEveryWeeks {

            get { return GetPropertyValue<int>("RecurEveryWeeks"); }

            set { SetPropertyValue("RecurEveryWeeks", value); }

        }

     

        public bool Monday {

            get { return GetPropertyValue<bool>("Monday"); }

            set { SetPropertyValue("Monday", value); }

        }

     

        public bool Tuesday {

            get { return GetPropertyValue<bool>("Tuesday"); }

            set { SetPropertyValue("Tuesday", value); }

        }

     

        public bool Wednesday {

            get { return GetPropertyValue<bool>("Wednesday"); }

            set { SetPropertyValue("Wednesday", value); }

        }

     

        public bool Thursday {

            get { return GetPropertyValue<bool>("Thursday"); }

            set { SetPropertyValue("Thursday", value); }

        }

     

        public bool Friday {

            get { return GetPropertyValue<bool>("Friday"); }

            set { SetPropertyValue("Friday", value); }

        }

     

        public bool Saturday {

            get { return GetPropertyValue<bool>("Saturday"); }

            set { SetPropertyValue("Saturday", value); }

        }

     

        public bool Sunday {

            get { return GetPropertyValue<bool>("Sunday"); }

            set { SetPropertyValue("Sunday", value); }

        }

        #region IWorkflowDefinition Members

        public string GetActivityTypeName() {

            return GetUniqueId();

        }

     

        public IList<IStartWorkflowCondition> GetConditions() {

            return new IStartWorkflowCondition[0];

        }

     

        public string GetUniqueId() {

            if (Session.IsNewObject(this)) {

                throw new InvalidOperationException();

            }

            return "ScheduledWorkflow" + Oid.ToString().ToUpper().Replace("-", "_");

        }

     

        [Browsable(false)]

        public bool CanCompile {

            get { return false; }

        }

     

        [Browsable(false)]

        public bool CanOpenHost {

            get { return IsActive && !string.IsNullOrEmpty(Name); }

        }

     

        public string Name {

            get { return GetPropertyValue<string>("Name"); }

            set { SetPropertyValue("Name", value); }

        }

     

        [Size(SizeAttribute.Unlimited)]

        public string Xaml {

            get { return GetPropertyValue<string>("Xaml"); }

            set { SetPropertyValue("Xaml", value); }

        }

        #endregion

        public override void AfterConstruction() {

            base.AfterConstruction();

            Xaml = DCWorkflowDefinitionLogic.InitialXaml;

        }

    }

     

    In the above class we have added some scheduled specific properties such as StartMode, StartTime, RecurEveryDays etc. The class has been decorated with the Appearance attribute to control the visibility of the Day properties. This means when StartMode <> 'Weekly these properties will be hidden.

    Moreover there is a collection LaunchHistoryItems of ScheduledWorkflowLaunchHistory objects, which will be used later to check if the workflow has been launched.

    public class ScheduledWorkflowLaunchHistory : BaseObject {

        public ScheduledWorkflowLaunchHistory(Session session) : base(session) {}

        public DateTime LaunchedOn {

            get { return GetPropertyValue<DateTime>("LaunchedOn"); }

            set { SetPropertyValue<DateTime>("LaunchedOn", value); }

        }

        [Association]

        public ScheduledWorkflow Workflow {

            get { return GetPropertyValue<ScheduledWorkflow>("Workflow"); }

            set { SetPropertyValue<ScheduledWorkflow>("Workflow", value); }

        }

    }

     

    After designing these classes, we now have all the required input in order to schedule our workflows.

    The next step is to load our custom workflows by extending the workflow provider service as shown,

    public class ScheduledWorkflowDefinitionProvider : WorkflowDefinitionProvider {

        public ScheduledWorkflowDefinitionProvider(Type workflowDefinitionType) : base(workflowDefinitionType) { }

        public ScheduledWorkflowDefinitionProvider(Type workflowDefinitionType, IObjectSpaceProvider objectSpaceProvider) : base(workflowDefinitionType, objectSpaceProvider) { }

        public override IList<IWorkflowDefinition> GetDefinitions() {

            IList<IWorkflowDefinition> result = base.GetDefinitions();

            IObjectSpace objectSpace = ObjectSpaceProvider.CreateObjectSpace(); //don't dispose immediately

            foreach(ScheduledWorkflow workflow in objectSpace.GetObjects<ScheduledWorkflow>()) {

                result.Add(workflow);

            }

            return result;

        }

    }

     

    After this we are ready to implement our final service that will schedule our workflows,

    public class ScheduledWorkflowStartService : BaseTimerService {

        private bool NeedToStartWorkflow(IObjectSpace objectSpace, ScheduledWorkflow workflow) {

            if (workflow.StartMode == StartMode.OneTime) {

                if (workflow.LaunchHistoryItems.Count == 0) {

                    return true;

                }

            } else if (workflow.StartMode == StartMode.Daily) {

                var historyItem = objectSpace.FindObject<ScheduledWorkflowLaunchHistory>(CriteriaOperator.Parse("GetDate(LaunchedOn) = ?", DateTime.Today));

                if (historyItem == null && DateTime.Now.TimeOfDay > workflow.StartTime) {

                    return true;

                }

            } else if (workflow.StartMode == StartMode.Weekly) {

                throw new NotImplementedException();

            }

            return false;

        }

        public ScheduledWorkflowStartService()

            : base(TimeSpan.FromMinutes(1)) {

        }

        public ScheduledWorkflowStartService(TimeSpan requestsDetectionPeriod) : base(requestsDetectionPeriod) { }

        public override void OnTimer() {

            using (IObjectSpace objectSpace = ObjectSpaceProvider.CreateObjectSpace()) {

                foreach (ScheduledWorkflow workflow in objectSpace.GetObjects<ScheduledWorkflow>(new BinaryOperator("IsActive", true))) {

                    WorkflowHost host;

                    if (HostManager.Hosts.TryGetValue(workflow.GetUniqueId(), out host)) {

                        if (NeedToStartWorkflow(objectSpace, workflow)) {

                            host.StartWorkflow(new Dictionary<string, object>());

                            var historyItem = objectSpace.CreateObject<ScheduledWorkflowLaunchHistory>();

                            historyItem.Workflow = workflow;

                            historyItem.LaunchedOn = DateTime.Now;

                            objectSpace.CommitChanges();

                        }

                    }

                }

            }

        }

    }

     

    Note; the service is not fully implemented, however its very easy to continue from this point. This code will live in the new Xpand.ExpressApp.Workflow module. Now, for the rest of the implementation I would like to ask the help of our community. Anyone that wants to finish it contribute it is most welcome!

    Finally we modify the WorkflowServerStarter class and add this service,

    private void Start_(string connectionString, string applicationName) {

        ServerApplication serverApplication = new ServerApplication();

        serverApplication.ApplicationName = applicationName;

        serverApplication.Modules.Add(new WorkflowDemoModule());

        serverApplication.ConnectionString = connectionString;

        serverApplication.Security = new SecurityComplex<User, Role>(

            new WorkflowServerAuthentication(new BinaryOperator("UserName", "WorkflowService")));

        serverApplication.Setup();

        serverApplication.Logon();

     

        IObjectSpaceProvider objectSpaceProvider = serverApplication.ObjectSpaceProvider;

     

        server = new WorkflowServer("http://localhost:46232", objectSpaceProvider, objectSpaceProvider);

     

        server.WorkflowDefinitionProvider = new ScheduledWorkflowDefinitionProvider(typeof(XpoWorkflowDefinition));

     

        //Add the service           

        server.ServiceProvider.AddService(new ScheduledWorkflowStartService());

    We are now ready to go!

    4-9-2011 12-50-05 μμ

    Note; You can watch this approach live in this webinar

    Updated: Big thanks to Martin Praxmarer for contributing the missing parts of this implementation. It can be found in eXpand v11.2.11.9 

    Related Links
    Blog posts
    Online documentation
    Videos

  • XAF- XPO Ask the Team Webinar–August

         

    This is a reminder post for today’s webinar. We are going to cover 3 main areas. Firstly we are going to demo how to extend our Workflow module in order to provide support for scheduled workflows. Then we are going to see how nested properties are handled by our enhanced FilterEditor. Finally we are going to explore a very early preview of a Middle Tier XAF application. In this preview only the security is implemented as a service, however the point of the demo is to show the general direction when working with an application server.

    The team and myself are really looking forward to speak to you this evening, so pop along and register now!

  • XAF Workflow persistence storage

         

    The .NET Framework 4 ships with the SQL Workflow Instance Store which allows workflows to persist state information about workflow instances in a SQL Server 2005 or SQL Server 2008 database. However its implementation is based on stored procedures which can be a bit scary if you are not familiar with them. In addition our customers may follow different standards (Oracle, Firebird, VistaDB, MySQL, PostgreSQL etc.) and it’s unrealistic to hire more people to support SQL Server infrastructure.

    Usually when dealing with these issues the first thing we do is to carry out a Google search for storage solutions. Surprisingly there is no such solution out there! Moreover there is very little useful code or samples available. Luckily XAF provides us with an easier route!

    XAF is the perfect workflow modeling environment. It provides a ready made solution for creating and deploying a server that will execute workflows as described here.  In order to start modeling workflows we can use VS design time along with our re-hosted runtime Workflow designer and custom WF4 activities. XAF also gives us increased control over our workflows for example through the ability to manually start workflows. Finally since XAF uses XPO to access data we can easily support 16 different database systems simply by providing a connection string!

    XPO Data Store Adapter XPO Data Store Adapter's Assembly Name Database Provider Assembly
    AccessConnectionProvider DevExpress.Xpo.vXXX System.Data.dll
    AdvantageConnectionProvider DevExpress.Xpo.vXXX.Providers Advantage.Data.Provider.dll 9.10.2.0
    AsaConnectionProvider DevExpress.Xpo.vXXX.Providers iAnywhere.Data.SQLAnywhere.dll 11.0.0.12642
    AseConnectionProvider DevExpress.Xpo.vXXX.Providers Sybase.Data.AseClient.dll 1.15.50.0
    DB2ConnectionProvider DevExpress.Xpo.vXXX.Providers IBM.Data.DB2.dll 9.5.2.2
    FirebirdConnectionProvider DevExpress.Xpo.vXXX.Providers FirebirdSql.Data.Firebird.dll 1.7.1.0
    FirebirdSql.Data.FirebirdClient.dll 2.5.1.0
    MSSqlConnectionProvider DevExpress.Xpo.vXXX System.Data.dll
    MSSqlCEConnectionProvider DevExpress.Xpo.vXXX.Providers System.Data.SqlServerCe.dll 3.5.0
    System.Data.SqlServerCe.dll 4.0.8482.1
    MySqlConnectionProvider DevExpress.Xpo.vXXX.Providers MySql.Data.dll 5.2.5.0
    OracleConnectionProvider DevExpress.Xpo.vXXX.Providers System.Data.OracleClient.dll 2.0.0.0
    Oracle.DataAccess.dll 9.2.0.700
    ODPConnectionProvider DevExpress.Xpo.vXXX.Providers Oracle.DataAccess.dll 10.1.0.200
    PervasiveSqlConnectionProvider DevExpress.Xpo.vXXX.Providers Pervasive.Data.SqlClient.dll 2.10.0.15
    PostgreSqlConnectionProvider DevExpress.Xpo.vXXX.Providers Npgsql.dll 2.0.11.0
    SQLiteConnectionProvider DevExpress.Xpo.vXXX.Providers System.Data.SQLite.dll 1.0.61.0
    VistaDBConnectionProvider DevExpress.Xpo.vXXX.Providers VistaDB.4.dll 4.0.0.0

    More info @ Database Systems Supported by XPO

    This is only one example of what XAF can do for us. XAF provides a comprehensive set of solutions that allow you to outsource all of the mundane programming tasks leaving you to focus purely on your business needs. For more info consult our docs, blogs, code central and support center.

    DevExpress Workflow Instance Store

    In version 11.1.7 our team now provides workflow instance support outside XAF borders! With a few lines of code, it is now possible to store our workflows in any of the 14 database systems described.

    Durability is a key benefit of the Workflow Foundation and it is based on the ability to store a running workflow instance on the fly at almost any time.
    To this end Microsoft workflow team implemented the SqlWokflowInstanceStore class. Using this class and a few lines is possible to store workflow instances in SQL Server as shown,

    // Define SqlWorkflowInstanceStoreBehavior:

    // Set interval to renew instance lock to 5 seconds.

    // Set interval to check for runnable instances to 2 seconds.

    // Instance Store does not keep instances after it is completed.

    // Select exponential back-off algorithm when retrying to load a locked instance.

    // Instance state information is compressed using the GZip compressing algorithm.

    SqlWorkflowInstanceStoreBehavior instanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior(connectionString);

    instanceStoreBehavior.HostLockRenewalPeriod = new TimeSpan(0, 0, 5);

    instanceStoreBehavior.RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 2);

    instanceStoreBehavior.InstanceCompletionAction = InstanceCompletionAction.DeleteAll;

    instanceStoreBehavior.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry;

    instanceStoreBehavior.InstanceEncodingOption = InstanceEncodingOption.GZip;

    host.Description.Behaviors.Add(instanceStoreBehavior);

    The above code was copied from the "BuiltInConfiguration" demo, "InstanceStore1" project. This demo is described at "Built-in Configuration"
    (
    http://msdn.microsoft.com/en-us/library/ee622978.aspx). You can download full sources of this demo and many others at "WCF and WF Samples for .NET Framework 4"
    (
    http://www.microsoft.com/download/en/details.aspx?id=21459).

    Following the same architecture our team implemented the DX WorkFlow Instance Store. eXpress Persistent Objects (XPO) is used for common objects storage and is fully capable of working transparently with 14 different database systems. For example to provide support for an Oracle database we could write,

    //We create or connect to a database by setting the connectionstring

    //This code will create 2 tables (XpoWorkflowInstance, XpoInstanceKeyc) in the database

    using (var session = new Session()) {

    session.ConnectionString = "Data Source=DevExpressInstanceStore;User Id=myUsername;Password=myPassword";

    session.UpdateSchema(typeof(XpoWorkflowInstance), typeof(XpoInstanceKey));

    session.CreateObjectTypeRecords(typeof(XpoWorkflowInstance), typeof(XpoInstanceKey));

    }

    // Define WorkflowInstanceStoreBehavior:

    var dxInstanceStoreBehavior = new WorkflowInstanceStoreBehavior(

    typeof(XpoWorkflowInstance), typeof(XpoInstanceKey), DevExpressConnectionString);

    host.Description.Behaviors.Add(dxInstanceStoreBehavior);

    dxInstanceStoreBehavior.RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 2);

    dxInstanceStoreBehavior.InstanceCompletionAction = InstanceCompletionAction.DeleteAll;

    You can download a modified version of the “BuiltInConfiguration” solution here. The console application starts a long running workflow that implements a counting service. Once the service’s start method is invoked, the service counts from 0 to 59. The counter is incremented every 2 seconds. After each count the workflow persists so you can close the application at any time and when you start it next time it will continue. A new one will be started from '0' value in addition to the loaded instances. The second project “InstanceStore2” in the solution provides the same functionality, however it is configured using the app.config file as shown,

    <system.serviceModel>

    <extensions>

    <behaviorExtensions>

    <add name="DevExpressWorkflowInstanceStore" type="DevExpress.Workflow.Store.WorkflowInstanceStoreElement, DevExpress.Workflow.Activities.v11.1"/>

    </behaviorExtensions>

    </extensions>

    <services>

    <service name="CountingWorkflow" behaviorConfiguration="">

    </service>

    </services>

    <behaviors>

    <serviceBehaviors>

    <behavior name="">

    <!--<sqlWorkflowInstanceStore

    connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=InstanceStore;Integrated Security=True;Asynchronous Processing=True"

    hostLockRenewalPeriod="00:00:05" runnableInstancesDetectionPeriod="00:00:02" instanceCompletionAction="DeleteAll"

    instanceLockedExceptionAction="AggressiveRetry" instanceEncodingOption="GZip"

    />-->

    <DevExpressWorkflowInstanceStore

    connectionString="Data Source=DevExpressInstanceStore;User Id=myUsername;Password=myPassword"

    runnableInstancesDetectionPeriod="00:00:02" instanceCompletionAction="DeleteAll"/>

    </behavior>

    </serviceBehaviors>

    </behaviors>

    </system.serviceModel>

    Note; All we need to do to use these code snippets in our code is to reference 'DevExpress.ExpressApp.v11.1.dll' and 'DevExpress.Workflow.Activities.v11.1.dl assemblies. Even though these assemblies are part of our eXpressApp framework and need a special license they can also be used to support any other type of .NET application!

    We are waiting to read your feedback about this. Remember that your questions are the best candidates for future posts.

    Related Links
    Blog posts
    Online documentation
    Videos

Next page »
More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.