Showing posts with label ObjectSpace. Show all posts
Showing posts with label ObjectSpace. Show all posts

Wednesday, April 11, 2018

Access XAF Application Data in a non-XAF Application

Access XAF Application Data in a non-XAF Application

In certain scenarios, you may need to create an axillary application for database maintenance and use Object Space to query your primary XAF application data. This topic describes how you can create and use Object Space in a regular non-XAF application.
Important
We do not recommend using the approach described here in XAF applications. Instead, always use the XafApplication.CreateObjectSpace method or access an existing Object Space.
In a non-XAF application, you have no XafApplication object to create an Object Space. But, an XafApplication does not create Object Spaces itself. Internally, it uses the Object Space Provider designed to create Object Spaces for the currently used ORM and those registered in its overridden XafApplication.CreateDefaultObjectSpaceProvider method. In a non-XAF application, you can instantiate the Object Space Provider manually. In XPO-based applications, use the DevExpress.ExpressApp.Xpo.XPObjectSpaceProvider constructor for this purpose. In Entity Framework applications, use the DevExpress.ExpressApp.EF.EFObjectSpaceProvider. Then, you can call the provider's CreateObjectSpace method to create an Object Space.

Expanded Entity Framework Example

You can use the following code to access data of the EFDemo application (typically installed to %PUBLIC%\Documents\DevExpress Demos 17.2\Components\eXpressApp Framework\EFDemoCodeFirst) and write the list of Departments to the standard output stream.
C#
VB
using DevExpress.ExpressApp.EF;
using DevExpress.ExpressApp;
using EFDemo.Module.Data;
// ... 
class Program {
    static void Main(string[] args) {
        EFObjectSpaceProvider osProvider = new EFObjectSpaceProvider(typeof(EFDemoDbContext),
            "integrated security=True;multipleactiveresultsets=True;data source=(localdb)\\v11.0;initial catalog=EFDemo_17.2");
        IObjectSpace objectSpace = osProvider.CreateObjectSpace();
        foreach (Department department in objectSpace.GetObjects()) {
           Console.WriteLine(department.Title + "\t" + department.Office);
        }
    }
}

Expanded XPO Example

In XPO-based applications, you should additionally initialize the Types Info Subsystem. The following example demonstrates how to access data of the MainDemo application (typically installed to %PUBLIC%\Documents\DevExpress Demos 17.2\Components\eXpressApp Framework\MainDemo) and write the list of Departments to the standard output stream:
C#
VB
using DevExpress.ExpressApp.Xpo;
using DevExpress.ExpressApp;
using MainDemo.Module.BusinessObjects;
// ... 
class Program {
    static void Main(string[] args) {
        XpoTypesInfoHelper.GetXpoTypeInfoSource();
        XafTypesInfo.Instance.RegisterEntity(typeof(Department));
        XPObjectSpaceProvider osProvider = new XPObjectSpaceProvider(
        @"integrated security=SSPI;pooling=false;data source=(localdb)\v11.0;initial catalog=MainDemo_17.2", null);
        IObjectSpace objectSpace = osProvider.CreateObjectSpace();
        foreach (Department department in objectSpace.GetObjects()) {
            Console.WriteLine(department.Title + "\t" + department.Office);
        }
    }
}
If you need to populate the database with initial data, use the DatabaseUpdater.Update method as follows:
C#
VB
using DevExpress.ExpressApp.Updating;
// ... 
DatabaseUpdater databaseUpdater = new DatabaseUpdater(
    osProvider, new ModuleBase[0], "", osProvider.ModuleInfoType);
databaseUpdater.Update();

Expanded See Also

XAF implement Business Logic using ObjectSpace

Ways to Implement Business Logic

There are two common places for your business logic code - Controllers and business classes themselves. In Controllers, you can declare new and customize existing Actions and handle other Controllers' events. In business classes, you can put logic into property getters and setters, implement methods that are triggered automatically when the object is created, loaded, saved and deleted (see IXafEntityObject) and declare action methods. In these cases, Object Space is required when data the current business object exposes is insufficient for your business logic, and you need to query more data. You may also use Object Space in your database initialization code, in complex View Items, etc. This topic describes the API you can use to get Object Space in various contexts.

Expanded Get an Existing Object Space

Usually, you can use an existing Object Space instance accessible via the XAF API. The following table describes how you can get an Object Space from various contexts of your code:
ContextWays to Access Object SpaceExamples
Business Object
An Object Space reference is automatically assigned to the IObjectSpaceLink.ObjectSpace property when a business object supporting an IObjectSpaceLink is instantiated. You can implement this interface and access other business objects directly in the current object code using the Object Space passed to the ObjectSpace property.
If you additionally implement an IXafEntityObject, then you can place your logic into the IXafEntityObject.OnCreatedIXafEntityObject.OnLoaded and IXafEntityObject.OnSaving methods. You can use the XAF Business Object | EF Business Object from Template Gallery to add a class that supports both IXafEntityObject and IObjectSpaceLink.
We recommend using Controllers instead of accessing UI-related entities (ViewsControllersActions) and executing UI-specific logic within the business class code, because it violates the separation of concerns principle and is against the MVC architecture.
Controller
In XAF applications, an Object Space is automatically assigned for each View. In a View Controller, you can get the current View using the ViewController.View property. Then, access the Object Space with the View.ObjectSpace. You can also use the protected ViewController.ObjectSpace property that refers to the same Object Space as View.ObjectSpace.
A Window Controller does not expose a View directly. You can access the current Frame using the Controller.Frame property and get the View with Frame.View.
A View handles Object Space events to update the UI each time an object changes. We recommend creating a new Object Space that is not bound to a current View instead of using theView.ObjectSpace property to process large amounts of data. You should also use a new Object Space when you create a new View with the XafApplication.CreateListView or XafApplication.CreateDetailView methods.
Module Updater
In a ModuleUpdater descendant, you can use the protected ModuleUpdater.ObjectSpace property to access the Object Space instance that can be used for database update operations. Do not use a new Object Space to update the database.
List Editor
A reference to the CollectionSourceBase object is automatically passed to the IComplexListEditor.Setup method if your custom List Editor supports the IComplexListEditor interface. You can implement this interface and access the Object Space via the CollectionSourceBase.ObjectSpace property.
View Item or Property Editor
A reference to an Object Space is automatically passed to the IComplexViewItem.Setup method if your custom View Item or Property Editor supports the IComplexViewItem interface. You can implement this interface and store the Object Space reference to a local variable for future use.
Object Space is also available using arguments passed to various events of the XafApplication class.

Expanded Create a New Object Space

It is often necessary to instantiate a new Object Space (for example, when you create a View using the XafApplication.CreateListView or XafApplication.CreateDetailView methods). Use the XafApplication.CreateObjectSpace method instead of an Object Space constructor to create an Object Space. For instance, the Controller.Application property is available in a Controller context, and you can create an Object Space as follows:
C#
VB
IObjectSpace objectSpace = this.Application.CreateObjectSpace();
Refer to the XafApplication class description to see how to obtain an XafApplication instance in various contexts. You cannot create new Object Spaces in the business object context because an XafApplication instance is not available there.
Examples:
Important
You should manually dispose of an Object Space when you are finished using it if you do not assign it to a View. An Object Space associated with a View is removed automatically together with this View.
Once you have obtained or created an Object Space, you can use it to query or modify data (see Create, Read, Update and Delete Data).

Expanded See Also

ObjectSpace CRUD

Create, Read, Update and Delete Data

Once you have obtained or created an Object Space instance (as described in the Ways to Implement Business Logic topic), you can use it to create, read, update or delete data. This topic lists common data-aware operations with the corresponding Object Space methods and events.
Data Manipulation
Related IObjectSpace Members
Create a new object
Methods:
Get a single object
Methods:
Get a collection
Methods:
Count objects
Methods:
Save
Methods:
Properties:
Events:
Delete
Methods:
Properties:
Events:
Track modifications
Methods:
Properties:
Events:
Refresh and rollback
Methods:
Events:
For details, refer to the descriptions of these members.

Expanded See Also

Saturday, March 17, 2018

ObjectSpace

BaseObjectSpace Members

A base class for the classes that implement the IObjectSpace interface.

Expanded Public Constructors

Show: Inherited
 NameDescription
Public methodBaseObjectSpaceCreates a new instance of the BaseObjectSpace class.
Top

Expanded Public Properties

Show: Inherited
 NameDescription
Public propertyCanFilterByNonPersistentMembersFor internal use.
Public propertyConnectionGets the connection to the underlying data source.
Public propertyDatabaseGets the name of the database.
Public propertyIsCommittingIndicates whether the Object Space is currently committing the changes made to its object(s).
Public propertyIsConnectedIndicates whether the BaseObjectSpace is connected to the database.
Public propertyIsDeletingIndicates whether the current Object Space is about to delete an object(s).
Public propertyIsDisposedGets a value indicating whether an Object Space has been disposed of.
Public propertyIsModifiedSpecifies whether objects belonging to the current Object Space are modified.
Public propertyIsReloadingGets a boolean value indicating whether or not the Object Space is reloading.
Public propertyLockingCheckEnabledSpecifies whether or not the additional locking check is performed.
Public propertyModifiedObjectsReturns a collection of objects that have been created, modified or deleted in the current object context.
Public propertyNonPersistentChangesEnabledSpecifies whether the BaseObjectSpace is marked as modified (see IsModified) when a non-persistent property is changed.
Public propertyOwnerSpecifies the View owning the current Object Space.
Public propertyTypesInfoGets information on the business classes added to the Application Model (see IModelBOModel).
Top

Expanded Public Methods

Show: Inherited
 NameDescription
Public methodApplyCriteriaFilters a particular collection on the server side.
Public methodApplyFilterFilters a particular collection on the client side.
Public methodCanApplyCriteriaIndicates whether collections of a particular type can be filtered on the server side.
Public methodCanApplyFilterIndicates whether a particular collection can be filtered on the client side.
Public methodCanInstantiateIndicates whether instances of a particular type can be created.
Public methodCommitChangesSaves all the changes made to the persistent objects belonging to the current Object Space to the database.
Public methodContainsIndicates whether a specified object belongs to the current Object Space.
Public methodStatic memberConvertExpressionsStringToExpressionsListReturns the list of DataViewExpression objects converted from the passed semicolon-separated expressions list.
Public methodStatic memberConvertSortingToStringReturns the string representation of a given sort list.
Public methodStatic memberConvertStringToSortingConverts the sorting string into the sorting list.
Public methodCreateCollectionOverloaded. Creates and initializes a collection of objects of the specified type.
Public methodCreateDataViewOverloaded. Returns a list of data records retrieved from a database without loading complete business classes (a data view). Values in each data record can be obtained from specific business class properties directly, or be evaluated by the database server using complex expressions.
Public methodCreateInstantFeedbackCollection
Public methodCreateNestedObjectSpaceCreates a nested Object Space.
Public methodCreateObjectCreates an object of the specified type.
Public methodCreateObjectCreates an object of the type designated by the specified generic type parameter.
Public methodCreateParseCriteriaScopeUsed when parsing a CriteriaOperator represented by a string and containing persistent objects.
Public methodCreateServerCollectionCreates and initializes a new instance of the EFServerCollection or DevExpress.Xpo.XPServerCollectionSource class with criteria-specific options.
Public methodDeleteOverloaded. Marks the specified persistent object and its aggregated objects as deleted from persistent storage.
Public methodDisposeReleases all resources used by an BaseObjectSpace object.
Public methodEnableObjectDeletionOnRemoveEnables/disables the deletion of persistent objects from the data source when they are removed from the specified collection.
Public methodStatic memberEqualsDetermines whether the specified System.Object instances are considered equal. (Inherited from System.Object)
Public methodEqualsDetermines whether the specified System.Object is equal to the current System.Object. (Inherited from System.Object)
Public methodEvaluateEvaluates the specified criteria for business objects of the given type.
Public methodFindObjectOverloaded. Searches for the first object of the specified type, matching the specified criteria.
Public methodFindObjectOverloaded. Searches for the first object of the type designated by the specified generic type parameter, matching the specified criteria.
Public methodGetAssociatedCollectionCriteriaReturns the criteria applied to a specific object's associated collection property.
Public methodGetCollectionObjectType
Public methodGetCollectionSortingReturns the sort settings for a particular collection.
Public methodGetCriteriaReturns the criteria used to filter a particular collection on the server side.
Public methodGetDisplayablePropertiesGets the properties considered visible by the specified collection.
Public methodGetEvaluatorContextDescriptorCreates an instance of the EvaluatorContextDescriptor that is used to supply metadata on the specified type to the ExpressionEvaluator objects.
Public methodGetExpressionEvaluatorOverloaded. Creates an ExpressionEvaluator object that is used to evaluate whether objects of the specified type satisfy a particular criteria.
Public methodGetFilterReturns the criteria used to filter a particular collection on the client side.
Public methodGetHashCodeServes as a hash function for a particular type. System.Object.GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from System.Object)
Public methodGetIntermediateObjectReferencesFor internal use.
Public methodGetKeyPropertyNameGets the name of the specified type's key property.
Public methodGetKeyPropertyTypeGets the key property type of the specified business type.
Public methodGetKeyValueOverloaded. Returns the key property's value of the specified object.
Public methodStatic memberGetKeyValueOverloaded. Returns the key property's value of the specified persistent object.
Public methodGetKeyValueAsStringOverloaded. Returns the key property's value of the specified object, converted to a string representation.
Public methodStatic memberGetKeyValueAsStringOverloaded.
Public methodGetObjectRetrieves an object that corresponds to a specific object from another Object Space or to a specific record from a data view created by the IObjectSpace.CreateDataView method.
Public methodGetObjectRetrieves an object from another Object Space to the current Object Space. The returned object is cast by the type designated by the specified generic type parameter.
Public methodGetObjectByHandleReturns the object with the specified handle.
Public methodGetObjectByKeyReturns the persistent object that has the specified value for its key property.
Public methodGetObjectByKeyReturns a persistent object of the type designated by the specified generic type parameter, with the specified value for its key property.
Public methodGetObjectHandleReturns an object's handle.
Public methodGetObjectKeyConverts the key property value string representation into its actual type.
Public methodGetObjectsOverloaded. Returns an IList collection of objects of the specified type, retrieved to the current Object Space and filtered according to the specified criteria.
Public methodGetObjectsOverloaded. Returns an IList collection of objects of the specified type, retrieved to the current Object Space and filtered according to the specified criteria.
Public methodGetObjectsCountReturns the number of objects specified.
Public methodGetObjectsCriteriaConstructs a criteria that can be used to select the specified list of business objects.
Public methodGetObjectsQueryGets a queryable data structure that provides functionality to evaluate queries against a specific business object type.
Public methodGetObjectsToDeleteReturns a collection of persistent objects that will be deleted when the current transaction is committed, including objects that will be deleted in the parent transaction(s), optionally.
Public methodGetObjectsToSaveReturns a collection of persistent objects that will be saved when the current transaction is committed, including objects that will be saved in the parent transaction(s), optionally.
Public methodGetObjectTypeReturns the type of the specified business object.
Public methodGetTopReturnedObjectsCountReturns the maximum number of objects to be retrieved by the specified collection from a data store.
Public methodGetTypeGets the System.Type of the current instance. (Inherited from System.Object)
Public methodIsCollectionLoadedIndicates whether a particular collection is loaded with objects from the database.
Public methodIsDeletedObjectIndicates whether the specified persistent object is deleted from the database.
Public methodIsDeletionDeferredTypeReturns a value that indicates if the deferred deletion is enabled for persistent objects of a given type.
Public methodIsDisposedObjectDetermines whether an object has been disposed of.
Public methodIsIntermediateObjectFor internal use.
Public methodIsKnownTypeReturns the boolean value indicating whether or not the specified type is known by the BaseObjectSpace.
Public methodIsNewObjectIndicates whether a specified object has been created but has not been saved to the database.
Public methodIsObjectDeletionOnRemoveEnabledIndicates whether the deletion of persistent objects from the data source when they are removed from the specified collection is enabled.
Public methodIsObjectFitForCriteriaOverloaded. Specifies whether a particular object satisfies the specified criteria.
Public methodIsObjectToDeleteIndicates whether the specified object has been deleted but not committed in the current object context or the transaction currently in progress.
Public methodIsObjectToSaveIndicates whether the specified object has been added, deleted or modified, but not committed in the current object context or the transaction currently in progress.
Public methodStatic memberObjectKeyValuesEqual
Public methodParseCriteriaTries to convert the specified string representation of an expression to its DevExpress.Data.Filtering.CriteriaOperator equivalent.
Public methodStatic memberReferenceEqualsDetermines whether the specified System.Object instances are the same instance. (Inherited from System.Object)
Public methodRefreshUpdates the persistent objects belonging to the current Object Space.
Public methodReloadCollectionClears the specified collection.
Public methodReloadObjectUpdates the specified object in the current Object Space with data from the data source.
Public methodRemoveFromModifiedObjectsRemoves the specified object from the object context or the list of objects to be committed.
Public methodRollbackCancels the changes made to the persistent objects belonging to the current Object Space.
Public methodSetCollectionSortingApplies the specified sorting to a given collection.
Public methodSetDisplayablePropertiesChanges the properties considered visible by a particular collection.
Public methodSetModifiedOverloaded. Sets the state of the specified object to be Modified.
Public methodSetPrefetchPropertyNames
Public methodSetTopReturnedObjectsCountSets the maximum number of objects that can be retrieved from the specified collection in a data store.
Public methodToStringReturns a System.String that represents the current System.Object. (Inherited from System.Object)
Top

Expanded Public Fields

Show: Inherited
 NameDescription
Public fieldStatic memberCompositeKeyPropertyType
Top

Expanded Public Events

Show: Inherited
 NameDescription
Public eventCommittedRaised after saving changes made to persistent objects belonging to the current Object Space to the database.
Public eventCommittingOccurs before saving the persistent objects belonging to the current Object Space to the database.
Public eventConfirmationRequiredOccurs when performing refresh or rollback operations with the current Object Space's persistent objects.
Public eventConnectedOccurs after a connection to a database has been established.
Public eventCustomCommitChangesReplaces the default process for committing changes made to persistent objects with a custom one.
Public eventCustomDeleteObjectsOccurs to replace the default process of deleting persistent objects with a custom one.
Public eventCustomRefreshOccurs to replace the default process of refreshing persistent objects with a custom one.
Public eventCustomRollBackOccurs to replace the default process of persistent objects rollback with a custom one.
Public eventDisposedOccurs before an Object Space is disposed of.
Public eventModifiedChangedOccurs when the current Object Space's IsModified state is changed.
Public eventObjectChangedRaised when a persistent object is created, changed or deleted.
Public eventObjectDeletedOccurs after the specified objects have been deleted.
Public eventObjectDeletingOccurs when the specified objects are about to be deleted.
Public eventObjectEndEditOccurs after ending an edit operation taking place on the specified object.
Public eventObjectReloadedOccurs after an object has been reloaded from the database.
Public eventObjectSavedOccurs after saving changes made to a specified persistent object to the database.
Public eventObjectSavingRaised before saving changes made to a specified persistent object to the database.
Public eventRefreshingOccurs before refreshing the current Object Space's persistent objects.
Public eventReloadedOccurs when the Rollback or Refresh method is called.
Public eventRollingBackOccurs before rolling back the changes made to the current Object Space's persistent objects.
Top

Expanded See Also