Skip to main content
All docs
V23.2

Connect to the Middle Tier Server from Non-XAF Applications (.NET 6+)

  • 2 minutes to read

This topic demonstrates how to access the data protected with the Middle Tier Application Server from a non-XAF application.

Initialize Metadata for Persistent Classes

The code sample below demonstrates how to initialize metadata on Employee, Project, and Task persistent classes.

XPDictionary dictionary = new ReflectionDictionary();
Type[] types = { typeof(Employee), typeof(Project), typeof(Task) }
dictionary.CollectClassInfos(types);

You can collect metadata for all persistent classes automatically when your data model is in a separate assembly. The code sample below demonstrates how to collect metadata for all persistent classes in the assembly that contains the Employee class:

dictionary.CollectClassInfos(Assembly.GetAssembly(typeof(Employee)));

Establish a Connection

The code sample below demonstrates how to create a connection to a Middle Tier Server.

var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://localhost:5001/");
var webApiSecuredClient = new WebApiSecuredDataServerClient(httpClient, XafTypesInfo.Instance);

Check if a Permission is Granted

Before checking whether a permission is granted, authenticate at the Middle Tier Service:

webApiSecuredClient.Authenticate(new AuthenticationStandardLogonParameters("User", ""));

When the secured client is initialized, and the user is logged on, you can create a permission request and check whether a user has a specific permission:

var readRequest = new SerializablePermissionRequest(typeof(Employee), null, null, SecurityOperations.Read);
bool isReadGranted = ((IMiddleTierServerSecurity)webApiSecuredClient).IsGranted(readRequest);

var writeRequest = new SerializablePermissionRequest(typeof(Employee), null, null, SecurityOperations.Write);
bool isWriteGranted = ((IMiddleTierServerSecurity)webApiSecuredClient).IsGranted(writeRequest);

Access Data

To access data via the secured Object Access Layer, create a UnitOfWork via the constructor that takes an object layer (see UnitOfWork). You can then create an XPCollection in this Unit of Work, or use UnitOfWork methods. Note that an exception is thrown when you access data that is restricted to the current user.

MiddleTierSerializableObjectLayerClient securedObjectLayerClient = new MiddleTierSerializableObjectLayerClient(webApiSecuredClient);
SerializableObjectLayerClient objectLayerClient = new SerializableObjectLayerClient(securedObjectLayerClient, dictionary);
UnitOfWork uow = new UnitOfWork(objectLayerClient);
foreach (Task task in new XPCollection<Task>(uow)) {
    Console.WriteLine(task.Subject);
}
try {
    var task = uow.FirstOrDefault<Task>(t => t.Subject == "Check Reports");
    task.Subject = "Review Reports";
    uow.CommitChanges();
}
catch(Exception e) {
    Console.WriteLine("Error: " + e.Message);
}
See Also