首页 > 开发 > 综合 > 正文

An Introduction to Business Objects in C#

2024-07-21 02:22:16
字体:
来源:转载
供稿:网友
  • download source files - 22 kb
note: after downloading be sure to consult readme.txt first.

introduction

this sample is an introduction to rockford lhotka's component-based scalable logical architecture (csla) as described in his book, visual basic 6 business objects (wrox press, 1998). the csla is an implementation of n-tier design, where an application is logically partitioned into four layers - presentation, ui-centric business objects, data-centric business objects, and data services. the purpose of the architecture is to achieve two overarching objectives.
  1. scalability.
  2. flexibility in the physical placement of each layer.
the latter means that we can decide whether to place all the layers on a single machine or to distribute them between client and server machines with little or no impact on the business logic code. it also means that we can provide a variety of presentation layers, ranging from a traditional windows interface to a web interface, with little or no impact on the business logic code. a typical physical architecture, utilizing a rich windows-style user interface, is to place the ui- centric objects on a client workstation where they are close to the user interface. the ui- centric objects communicate with the data-centric objects, which are placed on an application server, and the latter communicate with the data services, which are on a database server. the code presented here in c# is not a full implementation of the architecture. rather, it serves to illustrate the basic ideas. it presents a single ui-centric business object that captures basic information about a person - social security number, name and date of birth. it shows how a microsoft .net windows forms user interface can interact with the business object while allowing the latter to validate all the business rules as the user enters data. the user interface is completely insulated from detailed business rule validation. it just needs to act on a property of the business object - whether it is currently in a valid or invalid state. uml class diagram

the person class

the person class has three supplied properties:
  • social security number
  • name
  • birth date
and one computed property:
  • age
it has three business rules.
  • social security number contains exactly 11 alphanumeric characters (though the sample asks the user for digits).
  • name must be non-empty.
  • birth date must be in a valid format.
a person object is not considered to be in a valid state until these rules are satisfied. in order to provide the richest and most responsive user experience the idea is to validate these rules while the user is entering their data, rather than after it has all been entered. other user interfaces, such as an html 3.2 interface, can make do with a "batch"-style interface but we want to be able to use a variety of user interfaces and a windows-style gui provides the richest. the basic idea is that the controls for saving the user's data should only become available when the user has supplied all the data necessary to make a person valid. it is the user interface developer's job to write the code to do this. but they don't need to write detailed validation code they need only query the person's "valid" property. however, in practice, the ui developer has to know more about a person than this. but what they have to know is not to do with business rules but with the operational state of a person at any time. let's consider the operations that can be performed on a person:
add a new person. save it to a database. load an existing person from the database. delete a person.
a rich user interface will have features that enable a user to:
edit their data, save their changes and close the application. edit their data, save their changes, do further editing, save and close. edit their data, cancel their changes, and close.
and so on. in a data entry form the above is typically implemented using ok, cancel and apply buttons. this might not seem particularly problematic. however, a feature of this architecture is that the person object's state is being updated as the user types. if the user cancels their edits it is important to restore the object to the last valid state it was in prior to the edits. this means we have to keep a copy of the current state after each apply operation. in this particular example, this doesn't matter but in a more complex application, say, with collections of persons, it would. and we are trying to illustrate the general principles. the ui developer also needs to know a few other things about a person, such as whether a person is new, modified (dirty), or is currently being edited. for example, it should not be possible to load a new person from the database while one is being edited.

managing edits

to facilitate editing, three methods are provided: beginedit this enables editing. applyedit saves or deletes object if appropriate and terminates editing. clients should immediately call beginedit if they wish to continue editing. canceledit cancels all changes since the last applyedit operation or since the object was marked for deletion. terminates editing. in database terminology these three methods function like "begintrans", "commit" and "rollback" respectively, but applied to an object rather than a database.

managing business rules

in rockford lhotka's original visual basic implementation he created a brokenrules class that was made available to every business object in the application. in this sample, i have moved this functionality into an abstract base class, businessobject. i could also have placed an abstract interface to the three editing methods here while deferring the implementation to person, but i chose not to for this sample. the validity or invalidity of a person object is determined by maintaining a collection of broken business rules. the object is invalid while the collection is non-empty. when the count goes to zero the object becomes valid. the method that maintains the collection is: void rulebroken(string rule, bool isbroken) where: rule is a description of the business rule. this can be as simple as just the name of the property, e.g., "birth date" isbroken indicates whether the rule is broken or not. when a rule becomes broken it's added to the collection. if it's repeatedly broken the algorithm just skips adding it. when it becomes unbroken it is removed from the collection. when a person object is first constructed all its fields will be empty, so all its rules will be broken. remember, the rules are:
  • social security number contains exactly 11 alphanumeric characters.
  • name must be non-empty.
  • birth date must be in a valid format.
in the person constructor we write: rulebroken("social security number", true); rulebroken("name", true); rulebroken("birth date", true); of course, this is not normally how we should construct objects. normally objects should always be constructed in a valid state. however, the object being discussed here is a special kind. and when anything important is being done to it, such as persisting it or restoring it, the method ensures that the object is valid before it's persisted or after it's restored.

making a person valid

the idea is that a person should move from an invalid to a valid state as the user types in their data. initially each item that is the subject of a business rule will be incorrect. then one by one, as the user completes a data entry field, each should become valid until person becomes valid. this is achieved by appropriately constructed person set_xxx properties and form textchanged events. so, for social security number we have: in person.set_socialsecuritynumber property. (simplified for illustration)
set{   socialsecuritynumber = value;   rulebroken("social security number", socialsecuritynumber.length != 11);}
in form.txtsocialsecuritynumber_textchanged event. person.socialsecuritynumber = txtsocialsecuritynumber.text; the textchanged event occurs on each keystroke and for each keystroke, the person set_socialsecuritynumber property is called which calls rulebroken. note the expression: socialsecuritynumber.length != 11. this describes as true the condition that makes the rule broken. on the first keystroke social security number is not 11 characters long so it is added to the broken rules collection. on subsequent keystrokes it remains broken and so rulebroken will skip adding it to the collection. but when the 11th character is typed rulebroken receives a false value for its argument, indicating that the rule is no longer broken, so it is removed from the collection. this procedure is repeated for the name and birth date properties until the person object becomes valid.

informing a client that a person is valid or invalid

the person class exposes an isvalid property but also exposes valid and invalid custom events. these two events are handled by the client, in this case a windows forms application, to enable or disable saving of a person object. this means enabling or disabling the ok and apply buttons. to fire the events the person class (actually the base class) declares an event handler delegate and two events. public delegate void eventhandler(object sender, eventargs e); public event eventhandler oninvalid; public event eventhandler onvalid; to fire the onvalid event
      if (onvalid != null)      {        onvalid (this, eventargs.empty);      }    
rulebroken executes this code when the count of broken business rules falls to zero. the client handles the event as follows:
      // subscribe to person event      person.onvalid += new person.eventhandler(person_onvalid);      private void person_onvalid(object sender, system.eventargs e)      {        btnok.enabled = true;       btnapply.enabled = true;      }    
this event handler code is simplified compared to the actual implementation. but it illustrates the general idea. the oninvalid event is implemented similarly.

the age property

the age property is interesting. it is exposed as read-only so the client cannot set it. instead, it is computed from the birth date. however, it can be exposed to the user interface as a dynamic property that is updated each time the user enters a different birth date. (note: the sample application expects a date in uk format - day/month/year (dd/mm/yyyy).) suppose the user enters 11/1/1969 for date of birth. this gives an age of 33. the idea is to have 33 displayed to them in a read-only field the instant they type the 9 for 1969. if they make a mistake and decide to change, say, the year to 1959 the age field should immediately update itself to show 43. this behaviour can be achieved by again defining an event in the person class:
public event eventhandler onnewage;
in the person object, once the birth date is valid this event is raised and it is raised again on each subsequent occasion that it becomes valid, if the new age differs from the previous valid age. the client handles the event as follows:
      private void person_onnewage(object sender, system.eventargs e)      {        // update the displayed age        lblage.text = person.age.tostring();      }    

persistence

persistence is implemented using a "manager" object, personmanager. this has load, save and delete methods and communicates with the person object. the data access is via ado.net and a microsoft access database. the interface between the two is very simplistic. in a production environment we would need to use .net remoting and serialization, as the personmanager class would typically reside on a server. also, later in his book, lhotka streamlines his concepts and refers to person and personpersist objects to refer to the ui-centric and data-centric halves of the business object.

examples

as indicated, the sample employs a windows forms user interface. it is not intended to win any prizes for user interface design. its purpose is to illustrate the principal concepts discussed above.

editing a new person

the screenshot below shows an incompletely edited person. the birth year is in two-digit format but it needs to be four digits, so the ok and apply buttons are disabled. http://www.codeproject.com/csharp/person/editinvalid.jpg once the mistake is corrected the person object becomes valid and the ok and apply buttons are enabled. note also that the age field is now filled in. http://www.codeproject.com/csharp/person/edit.jpg

loading a new person

a person is loaded using their social security number. the screenshot below shows an incomplete social security number. it needs to be 11 digits long, so the load button is disabled. the name and birth date fields are also disabled, as we're not in edit mode. http://www.codeproject.com/csharp/person/loadinvalid.jpg once the 11th digit is added the load button is enabled. http://www.codeproject.com/csharp/person/loadenabled.jpg once the person is loaded the social security number field itself becomes disabled. http://www.codeproject.com/csharp/person/loaded.jpg but if we now uncheck the check box to enable editing, all fields are enabled and we can also delete the person at this point because it is no longer new. http://www.codeproject.com/csharp/person/loadenabledelete.jpg

an asp.net client

i have not included the code but, for illustration, the screenshots below show an asp.net web forms implementation. this demonstrates a "batch"-style user interface. validation does not take place until all the fields have been entered and the user clicks one of the save buttons. instead of validation being done in the textchanged events, the asp.net required field and custom validators are used. these are invoked when a submit button, i.e., one of the save buttons, is clicked. the first screenshot shows an invalid date with an error message. this is corrected in the second screenshot. the ui was a bit trickier to implement due to the statelessness of a web application. for example, after a submit command the form is reloaded and this invalidates the current state; the loading checkbox must have autopostback=true and so on. however, the essential point is that no changes are required to the person object. http://www.codeproject.com/csharp/person/aspeditinvalid.jpg http://www.codeproject.com/csharp/person/aspedit.jpg中国最大的web开发资源网站及技术社区,
上一篇:C#中调用API

下一篇:ref和out关键字初解

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表