DataObjects.Net Extensions are small projects that extend standard functionality of DataObjects.Net core. They are maintained by Xtensive engineers and volunteers from DataObjects.Net community. Each extension has a corresponding NuGet package so they can be installed separately or in any combination. Using NuGet is a recommended way of installing the extensions.
The extensions are published on CodePlex with source code open.
The extension provides a set of IQueryable extension methods that are translated to server-side UPDATE or DELETE commands.
Add Bulk Operations package to your project.
Query.All<Bar>()
.Where(a => a.Id == 1)
.Set(a => a.Count, 2)
.Update();
Query.All<Bar>()
.Where(a => a.Id==1)
.Set(a => a.Count, a => a.Description.Length)
.Update();
// Emulating entity loading
var bar = Query.Single<Bar>(1);
Query.All<Foo>()
.Where(a => a.Id == 2)
.Set(a => a.Bar, bar)
.Update();
Query.All<Foo>()
.Where(a => a.Id == 1)
.Set(a => a.Bar, a => Query.Single<Bar>(1))
.Update();
Query.All<Foo>()
.Where(a => a.Id == 1)
.Set(a => a.Bar, a => Query.All<Bar>().Single(b => b.Name == "test"))
.Update();
bool condition = CheckCondition();
var query = Query.All()<Bar>
.Where(a => a.Id == 1)
.Set(a => a.Count, 2);
if(condition)
query = query.Set(a => a.Name, a => a.Name + "test");
query.Update();
Query.All<Bar>()
.Where(a => a.Id == 1)
.Update(a => new Bar(null) { Count = 2, Name = a.Name + "test", dozens of other properties... });
Query.All<Foo>()
.Where(a => a.Id == 1)
.Delete();
The extension transparently solves a task of application or service localization. This implies that localizable resources are a part of domain model so they are stored in database.
<Xtensive.Orm>
<domains>
<domain ... >
<types>
<add assembly="your assembly"/>
<add assembly="Xtensive.Orm.Localization"/>
</types>
</domain>
</domains>
</Xtensive.Orm>
[HierarchyRoot]
public class Page : Entity, ILocalizable<PageLocalization>
{
[Field, Key]
public int Id { get; private set; }
// Localizable field. Note that it is non-persistent
public string Title
{
get { return Localizations.Current.Title; }
set { Localizations.Current.Title = value; }
}
[Field] // This is a storage of all localizations for Page class
public LocalizationSet<PageLocalization> Localizations { get; private set; }
public Page(Session session) : base(session) {}
}
[HierarchyRoot]
public class PageLocalization : Localization<Page>
{
[Field(Length = 100)]
public string Title { get; set; }
public PageLocalization(Session session, CultureInfo culture, Page target)
: base(session, culture, target) {}
}
page.Title = "Welcome";
string title = page.Title;
var en = new CultureInfo("en-US");
var sp = new CultureInfo("es-ES");
var page = new Page(session);
page.Localizations[en].Title = "Welcome";
page.Localizations[sp].Title = "Bienvenido";
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
string title = page.Title; // title is "Welcome"
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
string title = page.Title; // title is "Bienvenido"
using (new LocalizationScope(new CultureInfo("en-US"))) {
string title = page.Title; // title is "Welcome"
}
using (new LocalizationScope(new CultureInfo("es-ES"))) {
string title = page.Title; // title is "Bienvenido"
}
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
var query = from p in session.Query.All<Page>()
where p.Title=="Welcome"
select p;
Assert.AreEqual(1, query.Count());
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
var query = from p in session.Query.All<Page>()
where p.Title=="Bienvenido"
select p;
Assert.AreEqual(1, query.Count());
The extension provides API for reprocessible operations. The reprocessible operation should represent a separate block of logic, usually a delegate of a method and be transactional.
Domain.Execute(session =>
{
// Task logic
});
To indicate that a particular strategy should be used, use the following syntax:
Domain.WithStrategy(new HandleReprocessExceptionStrategy())
.Execute(session =>
{
// Task logic
});
3. To omit setting up the strategy each time consider configuring it in application configuration file, e.g.:
<configSections>
...
<section name="Xtensive.Orm.Reprocessing"
type="Xtensive.Orm.Reprocessing.Configuration.ConfigurationSection, Xtensive.Orm.Reprocessing" />
</configSections>
<Xtensive.Orm.Reprocessing
defaultTransactionOpenMode="New"
defaultExecuteStrategy="Xtensive.Orm.Reprocessing.HandleReprocessableExceptionStrategy, Xtensive.Orm.Reprocessing">
</Xtensive.Orm.Reprocessing>
Having that done, in scenarios with no strategy specified, the extension will automatically use the strategy from the configuration.
The extension provides security layer (authentication services, principals, roles, secured queries) There are 2 main parts that can also be used separately: authentication services and role-based access to domain entities
<Xtensive.Orm>
<domains>
<domain ... >
<types>
<add assembly="your assembly"/>
<add assembly="Xtensive.Orm.Security"/>
</types>
</domain>
</domains>
</Xtensive.Orm>
<section name="Xtensive.Orm.Security" type="Xtensive.Orm.Security.Configuration.ConfigurationSection,
Xtensive.Orm.Security" />
and set up the desired hashing service:
<Xtensive.Orm.Security>
<hashingService name="plain"/>
<!-- other options are: md5, sha1, sha256, sha384, sha512 -->
</Xtensive.Orm.Security>
[HierarchyRoot]
public class User : GenericPrincipal
{
[Field, Key]
public int Id { get; private set; }
[Field]
public string LastName { get; set; }
[Field]
public string FirstName { get; set; }
...
public User(Session session) : base(session) {}
}
// Creating a user
using (var session = Domain.OpenSession()) {
using (var transaction = session.OpenTransaction()) {
var user = new User(session);
user.Name = "admin";
user.SetPassword("password");
transaction.Complete();
}
}
// Authenticating a user
using (var session = Domain.OpenSession()) {
using (var transaction = session.OpenTransaction()) {
var user = session.Authenticate("admin", "password");
transaction.Complete();
}
}
EmployeeRole
|
|- StockManagerRole
|
|- SalesRepresentativeRole
|
|- SalesManagerRole
|
|- SalesPresidentRole
// This is base role for all employees
[HierarchyRoot(InheritanceSchema = InheritanceSchema.SingleTable)]
public abstract class EmployeeRole : Role
{
[Field, Key]
public int Id { get; set; }
protected override void RegisterPermissions()
{
// All employees can read products
RegisterPermission(new Permission<Product>());
// All employees can read other employees
RegisterPermission(new Permission<Employee>());
}
protected EmployeeRole(Session session)
: base(session) {}
}
public class StockManagerRole : EmployeeRole
{
protected override void RegisterPermissions()
{
// Stock manager inherits Employee permissions
base.RegisterPermissions();
// Stock manager can read and write products
RegisterPermission(new Permission<Product>(canWrite:true));
}
public StockManagerRole(Session session)
: base(session) {}
}
// Create instances of roles on first domain initialization
using (var session = Domain.OpenSession()) {
using (var transaction = session.OpenTransaction()) {
new SalesRepresentativeRole(session);
new SalesManagerRole(session);
new SalesPresidentRole(session);
new StockManagerRole(session);
transaction.Complete();
}
}
using (var session = Domain.OpenSession()) {
using (var transaction = session.OpenTransaction()) {
var stockManagerRole = session.Query.All<StockManagerRole>().Single();
var user = new User(session);
user.Name = "peter";
user.SetPassword("password");
user.Roles.Add(stockManagerRole);
transaction.Complete();
}
}
user.IsInRole("StockManagerRole");
// or
user.Roles.Contains(stockManagerRole);
using (var imContext = session.Impersonate(user)) {
// inside the region the session is impersonated with the specified
// principal and set of their roles and permissions
// Checking whether the user has a permission for reading Customer entities
imContext.Permissions.Contains<Permission<Customer>>(p => p.CanRead);
// Checking whether the user has a permission for writing to Customer entities
imContext.Permissions.Contains<Permission<Customer>>(p => p.CanWrite);
// another way
var p = imContext.Permissions.Get<Permission<Customer>>();
if (p != null && p.CanRead)
// allow doing some stuff
}
To end the impersonation call ImpersonationContext.Undo() or Dispose() method.
Impersonation contexts can be nested, e.g.:
using (var userContext = session.Impersonate(user)) {
// do some user-related stuff
using (var adminContext = session.Impersonate(admin)) {
// do some admin stuff
}
// we are still in user impersonation context
}
// no context here
7. Secure (restrictive) queries
A role may set up a condition that will be automatically added to any query and filters the query results, e.g.:
public class AutomobileManagerRole : EmployeeRole
{
private static IQueryable<Customer> GetCustomers(ImpersonationContext context, QueryEndpoint query)
{
return query.All<Customer>()
.Where(customer => customer.IsAutomobileIndustry);
}
protected override void RegisterPermissions()
{
base.RegisterPermissions();
// This permission tells that a principal can read/write customers
// but only those that are returned by the specified condition
RegisterPermission(new CustomerPermission(true, GetCustomers));
}
public AutomobileManagerRole(Session session)
: base(session) {}
}
Now all employees that have AutomobileManagerRole will read customers that have IsAutomobileIndustry property set to true, e.g.:
using (var session = Domain.OpenSession()) {
using (var transaction = session.OpenTransaction()) {
var automobileManagerRole = session.Query.All<AutomobileManagerRole>().Single();
var user = new User(session);
user.Name = "peter";
user.SetPassword("password");
user.Roles.Add(automobileManagerRole);
using (var context = session.Impersonate(user)) {
var customers = Query.All<Customer>();
// Inside the impersonation context the above-mentioned query condition
// will be added automatically so user will get only automobile customers
}
transaction.Complete();
}
}
The extension provides tracking/auditing funtionality on Session/Domain level.
How to use
<Xtensive.Orm>
<domains>
<domain ... >
<types>
<add assembly="your assembly"/>
<add assembly="Xtensive.Orm.Tracking"/>
</types>
</domain>
</domains>
</Xtensive.Orm>
4. Subscribe to TrackingCompleted event. After each tracked transaction is committed you receive the TrackingCompletedEventArgs object.
5. TrackingCompletedEventArgs.Changes contains a collection of ITrackingItem objects, each of them represents a set of changes that occurred to an Entity within the transaction committed.
var monitor = Domain.Services.Get<IDomainTrackingMonitor>();
monitor.TrackingCompleted += TrackingCompletedListener;
using (var session = Domain.OpenSession()) {
using (var t = session.OpenTransaction()) {
var e = new MyEntity(session);
e.Text = "some text";
t.Complete();
}
}
private void TrackingCompletedListener(object sender, TrackingCompletedEventArgs e)
{
foreach (var change in e.Changes) {
Console.WriteLine(change.Key);
Console.WriteLine(change.State);
foreach (var value in change.ChangedValues) {
Console.WriteLine(value.Field.Name);
Console.WriteLine(value.OriginalValue);
Console.WriteLine(value.NewValue);
}
}
}
The extension adds integration for DataObjects.Net and ASP.NET. It contains SessionManager class which is an implementation of IHttpModule and automatically provides Session and transaction for each web request.
SessionManager has the following features:
Note that presence of SessionManager does not prevent you from creating Sessions manually. It operates relying on Session.Resolver event, which is raised only when there is no current Session.
Finally, no automatic Session + transaction will be provided, if you don’t use Session.Current/Session.Demand() methods in your code (directly or indirectly). So e.g. requests to static web pages won’t lead to any DB interaction.
web.config:
<configuration>
<system.web>
<httpModules>
<add name="SessionManager" type="Xtensive.Orm.Web.SessionManager, Xtensive.Orm.Web"/>
</httpModules>
</system.web>
</configuration>
using Xtensive.Orm.Web;
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
SessionManager.DomainBuilder = DomainBuilder.Build;
}
}
public partial class EditCustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Session is provided automatically, transaction also starts
var session = Session.Demand();
var id = Request["customerId"];
if (!string.IsNullOrEmpty(id)) {
var customerId = int.Parse(id);
var customer = session.Query.Single<Customer>(customerId);
}
...
}
protected void Save(object sender, EventArgs e)
{
try {
var session = Session.Demand();
if (customer==null)
customer = new Customer(session);
customer.Name = textName.Text;
...
Back();
}
catch(InvalidOperationException exception) {
// This will roll back the transaction on end of http request
SessionManager.Current.HasErrors = true;
}
}