.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Post New Resource Bookmark and Share   

Saving user actions and replaying using Command Pattern

Posted By:Jean Paul       Posted Date: November 02, 2010    Points: 50    Category:    URL: http://www.dotnetspark.com  

Sometimes it is required for you to record the user actions, save it into a file and replay later. This example shows how to implement command pattern to achieve the same. This is achieved by converting each user actions into a Command.

You are working on a data manager application.

The application is having a list of text data.  This list is the heart of our app.

We can insert new data to the list or update existing ones.

You wanted to deploy the application to different users.
They will be inserting/updating data.  You need to save the insert/update
operations they have performed over the list.  Later these changes will
be saved to a file and send to you.

Using the file you can reproduce the user outputs.  It is possible to Undo/Redo operations
of the user because the actual list is kept unchanged.

Hope you got the challenge of the story.

In order to create the file containing user operations, the operations should be converted into objects
which could be persisted.

Let us define our Item class as following.
    public class Item
        public string Id

        public string Data

        public override string ToString()
            return this.Data.ToString();

Command Pattern

The Command Pattern says "Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undo able operations."

From the definition itself we can see queue or log requests is possible.  As we need to record each user operations queuing is required. 

The definition of Command format could be:
    public interface ICommand
        IList Items { get; set; }
        Item Item { get; set; }
        void Do();

Test Application

I have created a windows forms application with ListBox, Buttons for insert/update, saving/loading etc.
You can download the code and give a try.

Code Explained
Whenever the user clicks the Insert button, the text would be stored in a class instance of InsertCommand and logged into a commands list.

When user clicks Save Commands button the commands list will be saved into file.

When user clicks Load Commands button the file will be loaded and deserialized into commands list again.

The Reset button makes the user to restore back to the original list at any given point of time.


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend