diff --git a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Actions.cs b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Actions.cs index 63e2fa4d..0f798c16 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Actions.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Actions.cs @@ -2,26 +2,18 @@ { using System; using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; using System.Reflection; using System.Web.Http; using System.Web.OData; using System.Web.OData.Extensions; - using System.Web.OData.Query; using System.Web.OData.Routing; - using Expressions; + using ICSSoft.STORMNET; - using Microsoft.OData.Core; - using Microsoft.OData.Edm.Library; - using Microsoft.OData.Edm.Values; - using NewPlatform.Flexberry.ORM.ODataService.Formatter; + using NewPlatform.Flexberry.ORM.ODataService.Functions; using NewPlatform.Flexberry.ORM.ODataService.Handlers; - using NewPlatform.Flexberry.ORM.ODataService.Model; using NewPlatform.Flexberry.ORM.ODataService.Routing; + using Action = NewPlatform.Flexberry.ORM.ODataService.Functions.Action; /// @@ -107,7 +99,7 @@ private IHttpActionResult ExecuteAction(ODataActionParameters parameters) if (result is DataObject) { - var entityType = _model.GetEdmEntityType(result.GetType()); + var entityType = Model.GetEdmEntityType(result.GetType()); return SetResult(GetEdmObject(entityType, result, 1, null)); } diff --git a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Events.cs b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Events.cs deleted file mode 100644 index 73f19801..00000000 --- a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.Events.cs +++ /dev/null @@ -1,113 +0,0 @@ -namespace NewPlatform.Flexberry.ORM.ODataService.Controllers -{ - using ICSSoft.STORMNET; - using ICSSoft.STORMNET.Business; - - using NewPlatform.Flexberry.ORM.ODataService.Events; - using System; - using System.Net; - - /// - /// OData controller class. - /// Part with event handlers. - /// - public partial class DataObjectController - { - /// - /// The container with registered events. - /// - private readonly IEventHandlerContainer _events; - - /// - /// Вызов делегата перед запросом. - /// - /// . - /// - internal bool ExecuteCallbackBeforeGet(ref LoadingCustomizationStruct lcs) - { - return _events.CallbackBeforeGet == null || _events.CallbackBeforeGet(ref lcs); - } - - /// - /// Вызов делегата перед создания объекта. - /// - /// Объект после создания. - /// - internal bool ExecuteCallbackBeforeCreate(DataObject obj) - { - return _events.CallbackBeforeCreate == null || _events.CallbackBeforeCreate(obj); - } - - /// - /// Вызов делегата перед изменением объекта. - /// - /// Объект после создания. - /// - internal bool ExecuteCallbackBeforeUpdate(DataObject obj) - { - return _events.CallbackBeforeUpdate == null || _events.CallbackBeforeUpdate(obj); - } - - /// - /// Вызов делегата перед удалением объекта. - /// - /// Объект после создания. - /// - internal bool ExecuteCallbackBeforeDelete(DataObject obj) - { - return _events.CallbackBeforeDelete == null || _events.CallbackBeforeDelete(obj); - } - - /// - /// Вызов делегата после вычитывания объектов. - /// - /// Объект после создания. - internal void ExecuteCallbackAfterGet(ref DataObject[] objs) - { - _events.CallbackAfterGet?.Invoke(ref objs); - } - - /// - /// Вызов делегата после создания объекта. - /// - /// Объект после создания. - internal void ExecuteCallbackAfterCreate(DataObject obj) - { - _events.CallbackAfterCreate?.Invoke(obj); - } - - /// - /// Вызов делегата после обновления объекта. - /// - /// Объект после обновления. - internal void ExecuteCallbackAfterUpdate(DataObject obj) - { - _events.CallbackAfterUpdate?.Invoke(obj); - } - - /// - /// Вызов делегата после удаления объекта. - /// - /// Объект перед удалением. - internal void ExecuteCallbackAfterDelete(DataObject obj) - { - _events.CallbackAfterDelete?.Invoke(obj); - } - - /// - /// Вызов делегата после возникновения исключения. - /// - /// Исключение, которое возникло внутри ODataService. - /// Возвращаемый код HTTP. По-умолчанияю 500. - /// Исключение, которое будет отправлено клиенту. - internal Exception ExecuteCallbackAfterInternalServerError(Exception ex, ref HttpStatusCode code) - { - if (_events.CallbackAfterInternalServerError == null) - { - return ex; - } - - return _events.CallbackAfterInternalServerError(ex, ref code); - } - } -} \ No newline at end of file diff --git a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.ModifyData.cs b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.ModifyData.cs index 3910d71a..fe0ad36d 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.ModifyData.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.ModifyData.cs @@ -63,9 +63,9 @@ public HttpResponseMessage Post([FromBody] EdmEntityObject edmEntity) } DataObject obj = UpdateObject(edmEntity, null); - ExecuteCallbackAfterCreate(obj); + Events.AfterCreate(this, obj); - edmEntity = GetEdmObject(_model.GetEdmEntityType(type), obj, 1, null, null); + edmEntity = GetEdmObject(Model.GetEdmEntityType(Type), obj, 1, null, null); var responseForPreferMinimal = TestPreferMinimal(); if (responseForPreferMinimal != null) { @@ -134,7 +134,7 @@ public HttpResponseMessage Patch([FromODataUri] Guid key, [FromBody] EdmEntityOb } DataObject obj = UpdateObject(edmEntity, key); - ExecuteCallbackAfterUpdate(obj); + Events.AfterUpdate(this, obj); var responseForPreferMinimal = TestPreferMinimal(); if (responseForPreferMinimal != null) @@ -147,7 +147,7 @@ public HttpResponseMessage Patch([FromODataUri] Guid key, [FromBody] EdmEntityOb return Request.CreateResponse(System.Net.HttpStatusCode.NoContent); } - edmEntity = GetEdmObject(_model.GetEdmEntityType(type), obj, 1, null, null); + edmEntity = GetEdmObject(Model.GetEdmEntityType(Type), obj, 1, null, null); var result = Request.CreateResponse(System.Net.HttpStatusCode.OK, edmEntity); result.Headers.Add("Preference-Applied", "return=representation"); return result; @@ -195,7 +195,7 @@ private HttpResponseMessage DeleteEntity(object key) Init(); - var obj = _dataObjectCache.CreateDataObject(type, key); + var obj = DataObjectCache.CreateDataObject(Type, key); // Раз объект данных удаляется, то и все ассоциированные с ним файлы должны быть удалены. // Запоминаем метаданные всех ассоциированных файлов, кроме файлов соответствующих файловым свойствам типа File @@ -213,7 +213,7 @@ private HttpResponseMessage DeleteEntity(object key) // В данный момент ReferentialConstraints не создаются в модели. obj.SetStatus(ObjectStatus.Deleted); - if (ExecuteCallbackBeforeDelete(obj)) + if (Events.BeforeDelete(this, obj)) { if (Request.Properties.ContainsKey(DataObjectODataBatchHandler.DataObjectsToUpdatePropertyKey)) { @@ -222,13 +222,13 @@ private HttpResponseMessage DeleteEntity(object key) } else { - _dataService.UpdateObject(obj); + DataService.UpdateObject(obj); } } // При успешном удалении вычищаем из файловой системы, файлы подлежащие удалению. FileController.RemoveFileUploadDirectories(_removingFileDescriptions); - ExecuteCallbackAfterDelete(obj); + Events.AfterDelete(this, obj); return Request.CreateResponse(System.Net.HttpStatusCode.NoContent); } @@ -249,7 +249,7 @@ private HttpResponseMessage InternalServerErrorMessage(Exception ex) { HttpStatusCode code = HttpStatusCode.InternalServerError; Exception originalEx = ex; - ex = ExecuteCallbackAfterInternalServerError(ex, ref code); + ex = Events.AfterInternalServerError(this, ex, ref code); if (ex == null) { @@ -433,7 +433,7 @@ private DataObject UpdateObject(EdmEntityObject edmEntity, object key) { if (_newDataObjects[objs[i]]) { - if (!ExecuteCallbackBeforeCreate(objs[i])) + if (!Events.BeforeCreate(this, objs[i])) { objs.RemoveAt(i); i++; @@ -441,7 +441,7 @@ private DataObject UpdateObject(EdmEntityObject edmEntity, object key) } else { - if (!ExecuteCallbackBeforeUpdate(objs[i])) + if (!Events.BeforeUpdate(this, objs[i])) { objs.RemoveAt(i); i++; @@ -466,7 +466,7 @@ private DataObject UpdateObject(EdmEntityObject edmEntity, object key) } else { - _dataService.UpdateObjects(ref objsArrSmall); + DataService.UpdateObjects(ref objsArrSmall); } // При успешном обновлении вычищаем из файловой системы, файлы подлежащие удалению. @@ -495,7 +495,7 @@ private DataObject ReturnDataObject(Type objType, object keyValue) if (keyValue != null) { - DataObject dataObjectFromCache = _dataObjectCache.GetLivingDataObject(objType, keyValue); + DataObject dataObjectFromCache = DataObjectCache.GetLivingDataObject(objType, keyValue); if (dataObjectFromCache != null) { @@ -507,13 +507,13 @@ private DataObject ReturnDataObject(Type objType, object keyValue) return dataObjectFromCache; } - var view = _model.GetDataObjectDefaultView(objType); + var view = Model.GetDataObjectDefaultView(objType); // Проверим существование объекта в базе. var ldef = SQLWhereLanguageDef.LanguageDef; LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(objType, view); lcs.LimitFunction = ldef.GetFunction(ldef.funcEQ, new VariableDef(ldef.GuidType, SQLWhereLanguageDef.StormMainObjectKey), keyValue); - DataObject[] dobjs = _dataService.LoadObjects(lcs, _dataObjectCache); + DataObject[] dobjs = DataService.LoadObjects(lcs, DataObjectCache); if (dobjs.Length == 1) { DataObject dataObject = dobjs[0]; @@ -527,12 +527,12 @@ private DataObject ReturnDataObject(Type objType, object keyValue) if (keyValue != null) { - obj = _dataObjectCache.CreateDataObject(objType, keyValue); + obj = DataObjectCache.CreateDataObject(objType, keyValue); } else { obj = (DataObject)Activator.CreateInstance(objType); - _dataObjectCache.AddDataObject(obj); + DataObjectCache.AddDataObject(obj); } _newDataObjects.Add(obj, true); @@ -555,13 +555,13 @@ private DataObject GetDataObjectByEdmEntity(EdmEntityObject edmEntity, object ke } IEdmEntityType entityType = (IEdmEntityType)edmEntity.ActualEdmType; - Type objType = _model.GetDataObjectType(_model.GetEdmEntitySet(entityType).Name); + Type objType = Model.GetDataObjectType(Model.GetEdmEntitySet(entityType).Name); // Значение свойства. object value; // Получим значение ключа. - var keyProperty = entityType.Properties().FirstOrDefault(prop => prop.Name == _model.KeyPropertyName); + var keyProperty = entityType.Properties().FirstOrDefault(prop => prop.Name == Model.KeyPropertyName); if (key != null) { value = key; @@ -594,7 +594,7 @@ private DataObject GetDataObjectByEdmEntity(EdmEntityObject edmEntity, object ke // Все свойства объекта данных означим из пришедшей сущности, если они были там установлены(изменены). foreach (var prop in entityType.Properties()) { - string dataObjectPropName = _model.GetDataObjectProperty(entityType.FullTypeName(), prop.Name).Name; + string dataObjectPropName = Model.GetDataObjectProperty(entityType.FullTypeName(), prop.Name).Name; if (edmEntity.GetChangedPropertyNames().Contains(prop.Name)) { // Обработка мастеров и детейлов. diff --git a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.UserFunctions.cs b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.UserFunctions.cs index d1db8b10..2aa6a571 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.UserFunctions.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.UserFunctions.cs @@ -131,7 +131,7 @@ internal IHttpActionResult ExecuteUserFunction(QueryParameters queryParameters) Request.ODataProperties().SelectExpandClause = QueryOptions.SelectExpand.SelectExpandClause; } - this.type = type; + this.Type = type; CreateDynamicView(); IncludeCount = false; if (queryOpt.Count != null && queryOpt.Count.Value) @@ -149,7 +149,7 @@ internal IHttpActionResult ExecuteUserFunction(QueryParameters queryParameters) NameValueCollection queryParams = Request.RequestUri.ParseQueryString(); - if ((_model.ExportService != null || _model.ODataExportService != null) && (Request.Properties.ContainsKey(PostPatchHandler.AcceptApplicationMsExcel) || Convert.ToBoolean(queryParams.Get("exportExcel")))) + if ((Model.ExportService != null || Model.ODataExportService != null) && (Request.Properties.ContainsKey(PostPatchHandler.AcceptApplicationMsExcel) || Convert.ToBoolean(queryParams.Get("exportExcel")))) { _objs = (result as IEnumerable).Cast().ToArray(); return ResponseMessage(CreateExcel(queryParams)); @@ -170,9 +170,9 @@ internal IHttpActionResult ExecuteUserFunction(QueryParameters queryParameters) Request.ODataProperties().SelectExpandClause = QueryOptions.SelectExpand.SelectExpandClause; } - this.type = result.GetType(); + this.Type = result.GetType(); CreateDynamicView(); - var entityType = _model.GetEdmEntityType(this.type); + var entityType = Model.GetEdmEntityType(this.Type); return SetResult(GetEdmObject(entityType, result, 1, null, _dynamicView)); } diff --git a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.cs b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.cs index 98314b38..baa2984b 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Controllers/DataObjectController.cs @@ -11,7 +11,6 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; - using System.Web; using System.Web.Http; using System.Web.Http.Dispatcher; using System.Web.Http.Results; @@ -19,14 +18,15 @@ using System.Web.OData.Extensions; using System.Web.OData.Query; using System.Web.OData.Routing; - using Handlers; using ICSSoft.STORMNET; using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; using ICSSoft.STORMNET.FunctionalLanguage; using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; using ICSSoft.STORMNET.KeyGen; + using ICSSoft.STORMNET.Security; using ICSSoft.STORMNET.UserDataTypes; + using Microsoft.OData.Core; using Microsoft.OData.Core.UriParser.Semantic; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Library; @@ -34,14 +34,11 @@ using NewPlatform.Flexberry.ORM.ODataService.Expressions; using NewPlatform.Flexberry.ORM.ODataService.Formatter; using NewPlatform.Flexberry.ORM.ODataService.Functions; + using NewPlatform.Flexberry.ORM.ODataService.Handlers; using NewPlatform.Flexberry.ORM.ODataService.Model; using NewPlatform.Flexberry.ORM.ODataService.Offline; using ODataPath = System.Web.OData.Routing.ODataPath; using OrderByQueryOption = NewPlatform.Flexberry.ORM.ODataService.Expressions.OrderByQueryOption; - using Microsoft.Practices.Unity; - using Microsoft.Practices.Unity.Configuration; - using ICSSoft.STORMNET.Security; - using Microsoft.OData.Core; /// /// Определяет класс контроллера OData, который поддерживает запись и чтение данных с использованием OData формата. @@ -52,20 +49,25 @@ public partial class DataObjectController : BaseODataController private DataObject[] _objs; private LoadingCustomizationStruct _lcs; + /// + /// The container with registered events. + /// + public IEventHandlerContainer Events { get; } + /// /// Data service for all manipulations with data. /// - private readonly IDataService _dataService; + public IDataService DataService { get; } /// /// Data object cache for sync loading. /// - private readonly DataObjectCache _dataObjectCache; + public DataObjectCache DataObjectCache { get; } /// /// The current EDM model. /// - private readonly DataObjectEdmModel _model; + public DataObjectEdmModel Model { get; } /// /// Используемые в запросе параметры. Заполняется в методе Init(). @@ -75,7 +77,7 @@ public partial class DataObjectController : BaseODataController /// /// Тип DataObject, который соответствует сущности в наборе из запроса. Заполняется в методе Init(). /// - public Type type { get; set; } + public Type Type { get; set; } /// /// Включать или нет в метаданные количество сущностей. @@ -110,20 +112,20 @@ public DataObjectController( IEventHandlerContainer events, IFunctionContainer functions) { - _dataService = dataService ?? throw new ArgumentNullException(nameof(dataService), "Contract assertion not met: dataService != null"); + DataService = dataService ?? throw new ArgumentNullException(nameof(dataService), "Contract assertion not met: dataService != null"); if (dataObjectCache != null) { - _dataObjectCache = dataObjectCache; + DataObjectCache = dataObjectCache; } else { - _dataObjectCache = new DataObjectCache(); - _dataObjectCache.StartCaching(false); + DataObjectCache = new DataObjectCache(); + DataObjectCache.StartCaching(false); } - _model = model; - _events = events; + Model = model; + Events = events; _functions = functions; OfflineManager = new DummyOfflineManager(); @@ -185,10 +187,10 @@ public HttpResponseMessage GetString() ODataPath odataPath = Request.ODataProperties().Path; string key = odataPath.Segments[1].ToString().Trim().Replace("'", string.Empty); Init(); - var obj = LoadObject(type, key); + var obj = LoadObject(Type, key); var result = Request.CreateResponse( System.Net.HttpStatusCode.OK, - GetEdmObject(_model.GetEdmEntityType(type), obj, 1, null, _dynamicView)); + GetEdmObject(Model.GetEdmEntityType(Type), obj, 1, null, _dynamicView)); return result; } @@ -213,10 +215,10 @@ public HttpResponseMessage GetGuid() Guid key = new Guid(odataPath.Segments[1].ToString()); Init(); - var obj = LoadObject(type, key); + var obj = LoadObject(Type, key); var result = Request.CreateResponse( System.Net.HttpStatusCode.OK, - GetEdmObject(_model.GetEdmEntityType(type), obj, 1, null, _dynamicView)); + GetEdmObject(Model.GetEdmEntityType(Type), obj, 1, null, _dynamicView)); return result; } @@ -266,13 +268,13 @@ private bool HasOdataError(Exception exception) public int GetObjectsCount(Type type, ODataQueryOptions queryOptions) { var expr = GetExpressionFilterOnly(type, queryOptions); - View view = _model.GetDataObjectDefaultView(type); + View view = Model.GetDataObjectDefaultView(type); var lcs = LinqToLcs.GetLcs(expr, view); lcs.View = view; lcs.LoadingTypes = new[] { type }; lcs.ReturnType = LcsReturnType.Objects; - return _dataService.GetObjectsCount(lcs); + return DataService.GetObjectsCount(lcs); } internal HttpResponseMessage CreateExcel(NameValueCollection queryParams) @@ -330,17 +332,17 @@ internal HttpResponseMessage CreateExcel(NameValueCollection queryParams) par.DetailsInSeparateColumns = Convert.ToBoolean(queryParams.Get("detSeparateCols")); par.DetailsInSeparateRows = Convert.ToBoolean(queryParams.Get("detSeparateRows")); MemoryStream result; - if (_model.ODataExportService != null) + if (Model.ODataExportService != null) { - result = _model.ODataExportService.CreateExportStream(_dataService, par, _objs, queryParams); + result = Model.ODataExportService.CreateExportStream(DataService, par, _objs, queryParams); } else { - result = _model.ExportService.CreateExportStream(_dataService, par, _objs); + result = Model.ExportService.CreateExportStream(DataService, par, _objs); } HttpResponseMessage msg = Request.CreateResponse(HttpStatusCode.OK); - RawOutputFormatter.PrepareHttpResponseMessage(ref msg, "application/ms-excel", _model, result.ToArray()); + RawOutputFormatter.PrepareHttpResponseMessage(ref msg, "application/ms-excel", Model, result.ToArray()); msg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); msg.Content.Headers.ContentDisposition.FileName = "list.xlsx"; return msg; @@ -359,12 +361,12 @@ internal EdmEntityObjectCollection GetEdmCollection(IEnumerable objs, Type type, { if (level == 0) return null; - var entityType = _model.GetEdmEntityType(type); + var entityType = Model.GetEdmEntityType(type); List edmObjList = new List(); foreach (var obj in objs) { - var realType = _model.GetEdmEntityType(obj.GetType()); + var realType = Model.GetEdmEntityType(obj.GetType()); var edmObj = GetEdmObject(realType, obj, level, expandedNavigationSelectItem, dynamicView); if (edmObj != null) edmObjList.Add(edmObj); @@ -447,7 +449,7 @@ internal EdmEntityObject GetEdmObject(IEdmEntityType entityType, object obj, int foreach (var prop in entityType.Properties()) { - string dataObjectPropName = _model.GetDataObjectProperty(entityType.FullTypeName(), prop.Name).Name; + string dataObjectPropName = Model.GetDataObjectProperty(entityType.FullTypeName(), prop.Name).Name; if (prop is EdmNavigationProperty) { if (expandedProperties.ContainsKey(prop.Name)) @@ -464,18 +466,18 @@ internal EdmEntityObject GetEdmObject(IEdmEntityType entityType, object obj, int View view; if (master == null) { - view = _model.GetDataObjectDefaultView(obj.GetType()); + view = Model.GetDataObjectDefaultView(obj.GetType()); obj = LoadObject(view, (DataObject)obj); } master = obj.GetType().GetProperty(dataObjectPropName).GetValue(obj, null); if (master != null) { - view = _model.GetDataObjectDefaultView(master.GetType()); + view = Model.GetDataObjectDefaultView(master.GetType()); if (view != null) { master = LoadObject(view, (DataObject)master); - edmObj = GetEdmObject(_model.GetEdmEntityType(master.GetType()), master, level, expandedItem); + edmObj = GetEdmObject(Model.GetEdmEntityType(master.GetType()), master, level, expandedItem); } } } @@ -485,10 +487,10 @@ internal EdmEntityObject GetEdmObject(IEdmEntityType entityType, object obj, int { if (!DynamicView.ContainsPoperty(dynamicView.View, propPath)) { - _dataService.LoadObject(dynamicView.View, (DataObject)master, false, true, _dataObjectCache); + DataService.LoadObject(dynamicView.View, (DataObject)master, false, true, DataObjectCache); } - edmObj = GetEdmObject(_model.GetEdmEntityType(master.GetType()), master, level, expandedItem, dynamicView); + edmObj = GetEdmObject(Model.GetEdmEntityType(master.GetType()), master, level, expandedItem, dynamicView); } } @@ -498,7 +500,7 @@ internal EdmEntityObject GetEdmObject(IEdmEntityType entityType, object obj, int if (navProp.TargetMultiplicity() == EdmMultiplicity.Many) { DetailArray detail = null; - View view = _model.GetDataObjectDefaultView(obj.GetType()); + View view = Model.GetDataObjectDefaultView(obj.GetType()); if (dynamicView == null || !DynamicView.ContainsPoperty(dynamicView.View, propPath)) { obj = LoadObject(view, (DataObject)obj); @@ -520,7 +522,7 @@ internal EdmEntityObject GetEdmObject(IEdmEntityType entityType, object obj, int } else { - if (prop.Name == _model.KeyPropertyName) + if (prop.Name == Model.KeyPropertyName) { object key = obj.GetType().GetProperty(dataObjectPropName).GetValue(obj, null); if (key is KeyGuid) @@ -625,7 +627,7 @@ public Expression ToExpression(ODataQueryOptions queryOpt) if (queryOpt.OrderBy != null) { // queryable = queryOpt.OrderBy.ApplyTo(queryable, new ODataQuerySettings()); - queryable = new OrderByQueryOption(queryOpt.OrderBy, type).ApplyTo(queryable, new ODataQuerySettings()); + queryable = new OrderByQueryOption(queryOpt.OrderBy, Type).ApplyTo(queryable, new ODataQuerySettings()); } if (queryOpt.Skip != null) @@ -744,7 +746,7 @@ private IQueryable FilterApplyTo(FilterQueryOption filter, IQueryable query) throw Error.ArgumentNull("assembliesResolver"); } - if (type == null) + if (Type == null) { throw Error.NotSupported(SRResources.ApplyToOnUntypedQueryOption, "ApplyTo"); } @@ -763,18 +765,18 @@ private IQueryable FilterApplyTo(FilterQueryOption filter, IQueryable query) updatedSettings.HandleNullPropagation = HandleNullPropagationOptionHelper.GetDefaultHandleNullPropagationOption(query); } - FilterBinder binder = FilterBinder.Transform(filterClause, type, filter.Context.Model, assembliesResolver, updatedSettings); + FilterBinder binder = FilterBinder.Transform(filterClause, Type, filter.Context.Model, assembliesResolver, updatedSettings); _filterDetailProperties = binder.FilterDetailProperties; if (binder.IsOfTypesList.Count > 0) { - _lcsLoadingTypes = _model.GetTypes(binder.IsOfTypesList); + _lcsLoadingTypes = Model.GetTypes(binder.IsOfTypesList); } else { _lcsLoadingTypes.Clear(); } - query = ExpressionHelpers.Where(query, binder.LinqExpression, type); + query = ExpressionHelpers.Where(query, binder.LinqExpression, Type); return query; } @@ -785,8 +787,8 @@ private IQueryable FilterApplyTo(FilterQueryOption filter, IQueryable query) /// Контекст запроса OData. private ODataQueryContext CreateODataQueryContext(Type type) { - ODataPath path = new ODataPath(new EntitySetPathSegment(_model.GetEdmEntitySet(_model.GetEdmEntityType(type)))); - return new ODataQueryContext(_model, type, path); + ODataPath path = new ODataPath(new EntitySetPathSegment(Model.GetEdmEntitySet(Model.GetEdmEntityType(type)))); + return new ODataQueryContext(Model, type, path); } /// @@ -795,12 +797,12 @@ private ODataQueryContext CreateODataQueryContext(Type type) /// Сущность или коллекция сущностей. private IEdmObject EvaluateOdataPath() { - type = _model.GetDataObjectType(Request.ODataProperties().Path.Segments.OfType().First().ToString()); + Type = Model.GetDataObjectType(Request.ODataProperties().Path.Segments.OfType().First().ToString()); DetailArray detail = null; ODataPath odataPath = Request.ODataProperties().Path; Guid key = new Guid(odataPath.Segments[1].ToString()); IEdmEntityType entityType = null; - var obj = LoadObject(type, key); + var obj = LoadObject(Type, key); if (obj == null) { throw new InvalidOperationException("Not Found OData Path Segment " + 1); @@ -809,8 +811,8 @@ private IEdmObject EvaluateOdataPath() bool returnCollection = false; for (int i = 2; i < odataPath.Segments.Count; i++) { - type = obj.GetType(); - entityType = _model.GetEdmEntityType(type); + Type = obj.GetType(); + entityType = Model.GetEdmEntityType(Type); string propName = odataPath.Segments[i].ToString(); EdmNavigationProperty navProp = (EdmNavigationProperty)entityType.FindProperty(propName); @@ -819,7 +821,7 @@ private IEdmObject EvaluateOdataPath() DataObject master = (DataObject)obj.GetType().GetProperty(propName).GetValue(obj, null); if (master == null) { - View view = _model.GetDataObjectDefaultView(obj.GetType()); + View view = Model.GetDataObjectDefaultView(obj.GetType()); obj = LoadObject(view, obj); } @@ -828,9 +830,9 @@ private IEdmObject EvaluateOdataPath() throw new InvalidOperationException("Not Found OData Path Segment " + i); } - if (master != null && _model.GetDataObjectDefaultView(master.GetType()) != null) + if (master != null && Model.GetDataObjectDefaultView(master.GetType()) != null) { - master = LoadObject(_model.GetDataObjectDefaultView(master.GetType()), master); + master = LoadObject(Model.GetDataObjectDefaultView(master.GetType()), master); } obj = master; @@ -838,7 +840,7 @@ private IEdmObject EvaluateOdataPath() if (navProp.TargetMultiplicity() == EdmMultiplicity.Many) { - View view = _model.GetDataObjectDefaultView(obj.GetType()); + View view = Model.GetDataObjectDefaultView(obj.GetType()); obj = LoadObject(view, obj); detail = (DetailArray)obj.GetType().GetProperty(propName).GetValue(obj, null); i++; @@ -857,17 +859,17 @@ private IEdmObject EvaluateOdataPath() } } - entityType = _model.GetEdmEntityType(obj.GetType()); + entityType = Model.GetEdmEntityType(obj.GetType()); if (returnCollection) { - type = detail.ItemType; + Type = detail.ItemType; } else { - type = obj.GetType(); + Type = obj.GetType(); } - QueryOptions = new ODataQueryOptions(new ODataQueryContext(_model, type, Request.ODataProperties().Path), Request); + QueryOptions = new ODataQueryOptions(new ODataQueryContext(Model, Type, Request.ODataProperties().Path), Request); if (QueryOptions.SelectExpand != null && QueryOptions.SelectExpand.SelectExpandClause != null) { Request.ODataProperties().SelectExpandClause = QueryOptions.SelectExpand.SelectExpandClause; @@ -875,8 +877,8 @@ private IEdmObject EvaluateOdataPath() if (returnCollection) { - IQueryable queryable = ApplyExpression(type, QueryOptions, detail.GetAllObjects()); - return GetEdmCollection(queryable, type, 1, null); + IQueryable queryable = ApplyExpression(Type, QueryOptions, detail.GetAllObjects()); + return GetEdmCollection(queryable, Type, 1, null); } return GetEdmObject(entityType, obj, 1, null); @@ -950,34 +952,34 @@ private HttpResponseMessage ExecuteExpression() NameValueCollection queryParams = Request.RequestUri.ParseQueryString(); - if ((_model.ExportService != null || _model.ODataExportService != null) && (Request.Properties.ContainsKey(PostPatchHandler.AcceptApplicationMsExcel) || Convert.ToBoolean(queryParams.Get("exportExcel")))) + if ((Model.ExportService != null || Model.ODataExportService != null) && (Request.Properties.ContainsKey(PostPatchHandler.AcceptApplicationMsExcel) || Convert.ToBoolean(queryParams.Get("exportExcel")))) { return CreateExcel(queryParams); } HttpResponseMessage msg = null; EdmEntityObjectCollection edmCol = null; - edmCol = GetEdmCollection(_objs, type, 1, null, _dynamicView); + edmCol = GetEdmCollection(_objs, Type, 1, null, _dynamicView); msg = Request.CreateResponse(HttpStatusCode.OK, edmCol); return msg; } public LoadingCustomizationStruct CreateLcs() { - Expression expr = GetExpression(type, QueryOptions); + Expression expr = GetExpression(Type, QueryOptions); if (_filterDetailProperties != null && _filterDetailProperties.Count > 0) { CreateDynamicView(); _filterDetailProperties = null; } - View view = _model.GetDataObjectDefaultView(type); + View view = Model.GetDataObjectDefaultView(Type); if (_dynamicView != null) view = _dynamicView.View; IEnumerable resolvingViews; - view = DynamicView.GetViewWithPropertiesUsedInExpression(expr, type, view, _dataService, out resolvingViews); + view = DynamicView.GetViewWithPropertiesUsedInExpression(expr, Type, view, DataService, out resolvingViews); if (_lcsLoadingTypes.Count == 0) - _lcsLoadingTypes = _model.GetDerivedTypes(type).ToList(); + _lcsLoadingTypes = Model.GetDerivedTypes(Type).ToList(); for (int i = 0; i < _lcsLoadingTypes.Count; i++) { @@ -1010,8 +1012,8 @@ public LoadingCustomizationStruct CreateLcs() /// private void Init() { - type = _model.GetDataObjectType(Request.ODataProperties().Path.Segments.OfType().First().ToString()); - QueryOptions = new ODataQueryOptions(new ODataQueryContext(_model, type, Request.ODataProperties().Path), Request); + Type = Model.GetDataObjectType(Request.ODataProperties().Path.Segments.OfType().First().ToString()); + QueryOptions = new ODataQueryOptions(new ODataQueryContext(Model, Type, Request.ODataProperties().Path), Request); if (QueryOptions.SelectExpand != null && QueryOptions.SelectExpand.SelectExpandClause != null) { Request.ODataProperties().SelectExpandClause = QueryOptions.SelectExpand.SelectExpandClause; @@ -1028,7 +1030,7 @@ private void Init() /// Объект DataObject для данного ключа. private DataObject LoadObject(Type type, string key) { - View view = _model.GetDataObjectDefaultView(type); + View view = Model.GetDataObjectDefaultView(type); return LoadObject(type, view, key); } @@ -1041,7 +1043,7 @@ private DataObject LoadObject(Type type, string key) /// Объект DataObject для данного ключа. private DataObject LoadObject(Type type, Guid key) { - View view = _model.GetDataObjectDefaultView(type); + View view = Model.GetDataObjectDefaultView(type); return LoadObject(type, view, key); } @@ -1074,16 +1076,16 @@ private DataObject LoadObject(Type objType, View view, object keyValue) /// /// LoadingCustomizationStruct. /// В этом параметре веренётся количество объектов, если параметр callGetObjectsCount установлен в true, иначе -1. - /// Задаёт будет ли вызваться метод ExecuteCallbackBeforeGet. + /// Задаёт будет ли вызваться метод Events.BeforeGet. /// Задаёт будет ли вызваться метод GetObjectsCount вместо LoadObjects у сервиса данных. /// Если параметр callGetObjectsCount установлен в false, то возвращаются объекты, иначе пустой массив объектов. private DataObject[] LoadObjects(LoadingCustomizationStruct lcs, out int count, bool callExecuteCallbackBeforeGet = true, bool callGetObjectsCount = false, bool callExecuteCallbackAfterGet = true) { foreach (var propType in Information.GetAllTypesFromView(lcs.View)) { - if (!_dataService.SecurityManager.AccessObjectCheck(propType, tTypeAccess.Full, false)) + if (!DataService.SecurityManager.AccessObjectCheck(propType, tTypeAccess.Full, false)) { - _dataService.SecurityManager.AccessObjectCheck(propType, tTypeAccess.Read, true); + DataService.SecurityManager.AccessObjectCheck(propType, tTypeAccess.Read, true); } } @@ -1091,16 +1093,16 @@ private DataObject[] LoadObjects(LoadingCustomizationStruct lcs, out int count, bool doLoad = true; count = -1; if (callExecuteCallbackBeforeGet) - doLoad = ExecuteCallbackBeforeGet(ref lcs); + doLoad = Events.BeforeGet(this, ref lcs); if (doLoad) { if (!callGetObjectsCount) { - dobjs = _dataService.LoadObjects(lcs, _dataObjectCache); + dobjs = DataService.LoadObjects(lcs, DataObjectCache); } else { - count = _dataService.GetObjectsCount(lcs); + count = DataService.GetObjectsCount(lcs); } } @@ -1108,7 +1110,7 @@ private DataObject[] LoadObjects(LoadingCustomizationStruct lcs, out int count, throw new OperationCanceledException(); // TODO if (callExecuteCallbackAfterGet) - ExecuteCallbackAfterGet(ref dobjs); + Events.AfterGet(this, ref dobjs); return dobjs; } @@ -1127,20 +1129,20 @@ private void CreateDynamicView() { if (QueryOptions.SelectExpand == null || QueryOptions.SelectExpand.SelectExpandClause == null) { - var properties = DynamicView.GetProperties(type); + var properties = DynamicView.GetProperties(Type); if (_filterDetailProperties != null && _filterDetailProperties.Count > 0) { properties.AddRange(_filterDetailProperties); } - _dynamicView = DynamicView.Create(type, properties /*, _model.DynamicViewCache */); // TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + _dynamicView = DynamicView.Create(Type, properties /*, _model.DynamicViewCache */); // TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return; } List props = new List(); if (QueryOptions.SelectExpand.SelectExpandClause.AllSelected) { - var props2 = DynamicView.GetProperties(type); + var props2 = DynamicView.GetProperties(Type); props.AddRange(props2); } @@ -1162,7 +1164,7 @@ private void CreateDynamicView() typeName = (edmType as EdmEntityType).FullName(); } - var types = _model.GetTypes(new List() { typeName }); + var types = Model.GetTypes(new List() { typeName }); var props2 = DynamicView.GetProperties(types[0]); for (int i = 0; i < props2.Count; i++) { @@ -1182,7 +1184,7 @@ private void CreateDynamicView() props.AddRange(_filterDetailProperties); } - _dynamicView = DynamicView.Create(type, props /*, _model.DynamicViewCache */); // TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + _dynamicView = DynamicView.Create(Type, props /*, _model.DynamicViewCache */); // TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } private void GetPropertiesForDynamicView(ExpandedNavigationSelectItem parent, IEnumerable selectedItems) @@ -1238,13 +1240,13 @@ private string GetPropertyName(SelectItem item) } } - string itemName = _model.GetDataObjectProperty(itemProperty.DeclaringType.FullTypeName(), itemProperty.Name).Name; + string itemName = Model.GetDataObjectProperty(itemProperty.DeclaringType.FullTypeName(), itemProperty.Name).Name; string parentName = null; var parentExpandedItem = _parentExpandedNavigationSelectItem[item]; while (parentExpandedItem != null) { IEdmProperty property = (parentExpandedItem.PathToNavigationProperty.FirstSegment as NavigationPropertySegment).NavigationProperty; - string name = _model.GetDataObjectProperty(property.DeclaringType.FullTypeName(), property.Name).Name; + string name = Model.GetDataObjectProperty(property.DeclaringType.FullTypeName(), property.Name).Name; if (parentName == null) { parentName = name; diff --git a/NewPlatform.Flexberry.ORM.ODataService/Events/EventHandlerContainer.cs b/NewPlatform.Flexberry.ORM.ODataService/Events/EventHandlerContainer.cs index c37f871d..c4a5ba2c 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Events/EventHandlerContainer.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Events/EventHandlerContainer.cs @@ -1,54 +1,69 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Events { + using System; + using System.Net; + + using ICSSoft.STORMNET; + using ICSSoft.STORMNET.Business; + + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + /// /// Default implementation of . /// - /// internal class EventHandlerContainer : IEventHandlerContainer { - /// - /// Делегат для вызова логики перед выполнением запроса. - /// - public DelegateBeforeGet CallbackBeforeGet { get; set; } - - /// - /// Делегат для вызова логики перед изменением объекта. - /// - public DelegateBeforeUpdate CallbackBeforeUpdate { get; set; } - - /// - /// Делегат для вызова логики перед созданием объекта. - /// - public DelegateBeforeCreate CallbackBeforeCreate { get; set; } - - /// - /// Делегат для вызова логики перед удалением объекта. - /// - public DelegateBeforeDelete CallbackBeforeDelete { get; set; } - - /// - /// Делегат для вызова логики после вычитывания объектов. - /// - public DelegateAfterGet CallbackAfterGet { get; set; } - - /// - /// Делегат для вызова логики после сохранения объекта. - /// - public DelegateAfterCreate CallbackAfterCreate { get; set; } - - /// - /// Делегат для вызова логики после обновления объекта. - /// - public DelegateAfterUpdate CallbackAfterUpdate { get; set; } - - /// - /// Делегат для вызова логики после удаления объекта. - /// - public DelegateAfterDelete CallbackAfterDelete { get; set; } - - /// - /// Делегат, вызываемый после возникновения исключения. - /// - public DelegateAfterInternalServerError CallbackAfterInternalServerError { get; set; } + /// + public ManagementToken Token { get; set; } + + /// + public bool BeforeGet(DataObjectController controller, ref LoadingCustomizationStruct lcs) + { + return true; + } + + /// + public bool BeforeCreate(DataObjectController controller, DataObject obj) + { + return true; + } + + /// + public bool BeforeUpdate(DataObjectController controller, DataObject obj) + { + return true; + } + + /// + public bool BeforeDelete(DataObjectController controller, DataObject obj) + { + return true; + } + + /// + public void AfterGet(DataObjectController controller, ref DataObject[] objs) + { + } + + /// + public void AfterCreate(DataObjectController controller, DataObject obj) + { + } + + /// + public void AfterUpdate(DataObjectController controller, DataObject obj) + { + } + + /// + public void AfterDelete(DataObjectController controller, DataObject obj) + { + } + + /// + public Exception AfterInternalServerError(DataObjectController controller, Exception ex, ref HttpStatusCode code) + { + return ex; + } } } \ No newline at end of file diff --git a/NewPlatform.Flexberry.ORM.ODataService/Events/IEventHandlerContainer.cs b/NewPlatform.Flexberry.ORM.ODataService/Events/IEventHandlerContainer.cs index 081e9a1b..877a9c6f 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Events/IEventHandlerContainer.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Events/IEventHandlerContainer.cs @@ -1,53 +1,90 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Events { + using System; + using System.Net; + + using ICSSoft.STORMNET; + using ICSSoft.STORMNET.Business; + + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + /// /// Interface of container with OData Service event handlers. /// public interface IEventHandlerContainer { /// - /// Делегат для вызова логики перед выполнением запроса. + /// The OData Service token. + /// + ManagementToken Token { get; set; } + + /// + /// Обработчик, вызываемый перед выполнением запроса. /// - DelegateBeforeGet CallbackBeforeGet { get; set; } + /// Контроллер OData. + /// Структура загрузки. + /// для продолжения операции. + bool BeforeGet(DataObjectController controller, ref LoadingCustomizationStruct lcs); /// - /// Делегат для вызова логики перед изменением объекта. + /// Обработчик, вызываемый перед созданием объекта. /// - DelegateBeforeUpdate CallbackBeforeUpdate { get; set; } + /// Контроллер OData. + /// Объект. + /// для продолжения операции. + bool BeforeCreate(DataObjectController controller, DataObject obj); /// - /// Делегат для вызова логики перед созданием объекта. + /// Обработчик, вызываемый перед изменением объекта. /// - DelegateBeforeCreate CallbackBeforeCreate { get; set; } + /// Контроллер OData. + /// Объект. + /// для продолжения операции. + bool BeforeUpdate(DataObjectController controller, DataObject obj); /// - /// Делегат для вызова логики перед удалением объекта. + /// Обработчик, вызываемый перед удалением объекта. /// - DelegateBeforeDelete CallbackBeforeDelete { get; set; } + /// Контроллер OData. + /// Объект. + /// для продолжения операции. + bool BeforeDelete(DataObjectController controller, DataObject obj); /// - /// Делегат для вызова логики после вычитывания объектов. + /// Обработчик, вызываемый после вычитывания объектов. /// - DelegateAfterGet CallbackAfterGet { get; set; } + /// Контроллер OData. + /// Вычитанные объекты. + void AfterGet(DataObjectController controller, ref DataObject[] objs); /// - /// Делегат для вызова логики после сохранения объекта. + /// Обработчик, вызываемый после создания объекта. /// - DelegateAfterCreate CallbackAfterCreate { get; set; } + /// Контроллер OData. + /// Объект после создания. + void AfterCreate(DataObjectController controller, DataObject obj); /// - /// Делегат для вызова логики после обновления объекта. + /// Обработчик, вызываемый после обновления объекта. /// - DelegateAfterUpdate CallbackAfterUpdate { get; set; } + /// Контроллер OData. + /// Объект после обновления. + void AfterUpdate(DataObjectController controller, DataObject obj); /// - /// Делегат для вызова логики после удаления объекта. + /// Обработчик, вызываемый после удаления объекта. /// - DelegateAfterDelete CallbackAfterDelete { get; set; } + /// Контроллер OData. + /// Объект перед удалением. + void AfterDelete(DataObjectController controller, DataObject obj); /// - /// Делегат, вызываемый после возникновения исключения. + /// Обработчик, вызываемый после возникновения исключения. /// - DelegateAfterInternalServerError CallbackAfterInternalServerError { get; set; } + /// Контроллер OData. + /// Исключение, которое возникло внутри ODataService. + /// Возвращаемый код HTTP. По-умолчанияю 500. + /// Исключение, которое будет отправлено клиенту. + Exception AfterInternalServerError(DataObjectController controller, Exception ex, ref HttpStatusCode code); } } diff --git a/NewPlatform.Flexberry.ORM.ODataService/Extensions/HttpConfigurationExtensions.cs b/NewPlatform.Flexberry.ORM.ODataService/Extensions/HttpConfigurationExtensions.cs index cbcb5d7c..374432cf 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Extensions/HttpConfigurationExtensions.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Extensions/HttpConfigurationExtensions.cs @@ -13,8 +13,10 @@ using ICSSoft.STORMNET.Business; using NewPlatform.Flexberry.ORM.ODataService.Batch; using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; using NewPlatform.Flexberry.ORM.ODataService.Files.Providers; using NewPlatform.Flexberry.ORM.ODataService.Formatter; + using NewPlatform.Flexberry.ORM.ODataService.Functions; using NewPlatform.Flexberry.ORM.ODataService.Handlers; using NewPlatform.Flexberry.ORM.ODataService.Model; using NewPlatform.Flexberry.ORM.ODataService.Routing; @@ -103,7 +105,9 @@ public static ManagementToken MapODataServiceDataObjectRoute( config.Properties[typeof(CustomODataSerializerProvider)] = customODataSerializerProvider; // Token. - var token = new ManagementToken(route, model); + IEventHandlerContainer eventHandlerContainer = (IEventHandlerContainer)config.DependencyResolver.GetService(typeof(IEventHandlerContainer)) ?? new EventHandlerContainer(); + IFunctionContainer functionContainer = (IFunctionContainer)config.DependencyResolver.GetService(typeof(IFunctionContainer)) ?? new FunctionContainer(); + var token = new ManagementToken(route, model, eventHandlerContainer, functionContainer); config.SetODataServiceToken(token); // Handlers. diff --git a/NewPlatform.Flexberry.ORM.ODataService/Functions/FunctionContainer.cs b/NewPlatform.Flexberry.ORM.ODataService/Functions/FunctionContainer.cs index 5f5d27bc..21d336c6 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Functions/FunctionContainer.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Functions/FunctionContainer.cs @@ -11,53 +11,51 @@ /// internal class FunctionContainer : IFunctionContainer { - /// - /// The OData Service token. - /// - private readonly ManagementToken _token; - /// /// The registered OData Service functions. /// private readonly Dictionary _functions = new Dictionary(); - /// - /// Initializes a new instance of the class. - /// - /// The OData Service token. - public FunctionContainer(ManagementToken token) - { - _token = token ?? throw new ArgumentNullException(nameof(token), "Contract assertion not met: token != null"); - } + /// + public ManagementToken Token { get; set; } - /// - /// Registers the specified OData Service function. - /// - /// The OData Service function. + /// public void Register(Function function) { _functions.Add(function.Name, function); - _token.Model.AddUserFunction(function); + Token.Model.AddUserFunction(function); } - /// - /// Registers the specified delegate as OData Service function. - /// - /// The function. + /// public void Register(Delegate function) { Register(function, false); } - /// - /// Registers the specified delegate as OData Service action. - /// - /// The function. + /// public void RegisterAction(Delegate function) { Register(function, true); } + /// + public bool IsRegistered(string functionName) + { + return _functions.ContainsKey(functionName); + } + + /// + public Function GetFunction(string functionName) + { + return _functions[functionName]; + } + + /// + public IEnumerable GetFunctions() + { + return _functions.Values; + } + private void Register(Delegate function, bool createAction) { var functionName = function.Method.Name; @@ -91,34 +89,5 @@ private void Register(Delegate function, bool createAction) Register(new Function(functionName, handler, returnType, arguments)); } } - - /// - /// Determines whether the specified OData Service function is already registered. - /// - /// The name of the function. - /// Returns true if function is registered; otherwise false. - public bool IsRegistered(string functionName) - { - return _functions.ContainsKey(functionName); - } - - /// - /// Gets the registered OData Service function. - /// - /// Name of the function. - /// Registered OData Service function with specified name. - public Function GetFunction(string functionName) - { - return _functions[functionName]; - } - - /// - /// Gets all registered functions. - /// - /// Enumeration of all registered functions. - public IEnumerable GetFunctions() - { - return _functions.Values; - } } } \ No newline at end of file diff --git a/NewPlatform.Flexberry.ORM.ODataService/Functions/IFunctionContainer.cs b/NewPlatform.Flexberry.ORM.ODataService/Functions/IFunctionContainer.cs index 1b0ef5fe..44459f9b 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Functions/IFunctionContainer.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Functions/IFunctionContainer.cs @@ -8,6 +8,11 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Functions /// public interface IFunctionContainer { + /// + /// The OData Service token. + /// + ManagementToken Token { get; set; } + /// /// Registers the specified OData Service function. /// diff --git a/NewPlatform.Flexberry.ORM.ODataService/Functions/QueryParameters.cs b/NewPlatform.Flexberry.ORM.ODataService/Functions/QueryParameters.cs index 7804c010..090a4f88 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Functions/QueryParameters.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/Functions/QueryParameters.cs @@ -64,7 +64,7 @@ public LoadingCustomizationStruct CreateLcs(Type type, string odataQuery = null) } _controller.QueryOptions = _controller.CreateODataQueryOptions(type, request); - _controller.type = type; + _controller.Type = type; return _controller.CreateLcs(); } diff --git a/NewPlatform.Flexberry.ORM.ODataService/ManagementToken.cs b/NewPlatform.Flexberry.ORM.ODataService/ManagementToken.cs index 2c8129be..bd7dbdcf 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/ManagementToken.cs +++ b/NewPlatform.Flexberry.ORM.ODataService/ManagementToken.cs @@ -39,15 +39,19 @@ public DataObjectEdmModel Model public ODataRoute Route { get; } - public IEventHandlerContainer Events { get; } = new EventHandlerContainer(); + public IEventHandlerContainer Events { get; } public IFunctionContainer Functions { get; } - public ManagementToken(ODataRoute route, DataObjectEdmModel model) + public ManagementToken(ODataRoute route, DataObjectEdmModel model, IEventHandlerContainer events, IFunctionContainer functions) { Route = route ?? throw new ArgumentNullException(nameof(route), "Contract assertion not met: route != null"); _model = model ?? throw new ArgumentNullException(nameof(model), "Contract assertion not met: model != null"); - Functions = new FunctionContainer(this); + Events = events ?? throw new ArgumentNullException(nameof(events), "Contract assertion not met: events != null"); + Functions = functions ?? throw new ArgumentNullException(nameof(functions), "Contract assertion not met: functions != null"); + + Events.Token = this; + Functions.Token = this; } } } diff --git a/NewPlatform.Flexberry.ORM.ODataService/NewPlatform.Flexberry.ORM.ODataService.csproj b/NewPlatform.Flexberry.ORM.ODataService/NewPlatform.Flexberry.ORM.ODataService.csproj index 6d5f993c..8a6c3f46 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/NewPlatform.Flexberry.ORM.ODataService.csproj +++ b/NewPlatform.Flexberry.ORM.ODataService/NewPlatform.Flexberry.ORM.ODataService.csproj @@ -190,10 +190,8 @@ - - diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/BaseODataServiceIntegratedTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/BaseODataServiceIntegratedTest.cs index c53b3314..7d03afb4 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/BaseODataServiceIntegratedTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/BaseODataServiceIntegratedTest.cs @@ -23,13 +23,20 @@ public class BaseODataServiceIntegratedTest : BaseIntegratedTest public class TestArgs { + private readonly Lazy _token; + public IUnityContainer UnityContainer { get; set; } - public ManagementToken Token { get; set; } + public ManagementToken Token => _token.Value; public IDataService DataService { get; set; } public HttpClient HttpClient { get; set; } + + public TestArgs(Func func) + { + _token = new Lazy(func); + } } /// @@ -81,8 +88,7 @@ public virtual void ActODataService(Action action) config.EnableCors(new EnableCorsAttribute("*", "*", "*")); config.DependencyResolver = new UnityDependencyResolver(container); - var token = config.MapODataServiceDataObjectRoute(_builder, new HttpServer()); - var args = new TestArgs { UnityContainer = container, DataService = dataService, HttpClient = client, Token = token }; + var args = new TestArgs(() => config.MapODataServiceDataObjectRoute(_builder, new HttpServer())) { UnityContainer = container, DataService = dataService, HttpClient = client }; action(args); } } diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterGetTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterGetTest.cs index 6d301a47..08d295f5 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterGetTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterGetTest.cs @@ -5,6 +5,11 @@ using ICSSoft.STORMNET; + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; + + using Unity; + using Xunit; /// @@ -22,7 +27,7 @@ public class AfterGetTest : BaseODataServiceIntegratedTest /// Метод вызываемый после вычитывания объектов. /// /// Считанные объекты. - public void AfterGet(ref DataObject[] objs) + public void AfterGet(DataObjectController controller, ref DataObject[] objs) { Objs = objs; } @@ -35,7 +40,8 @@ public void TestAfterGet() { ActODataService(args => { - args.Token.Events.CallbackAfterGet = AfterGet; + var eventsContainer = new FakeEventHandlerContainer { CallbackAfterGet = AfterGet }; + args.UnityContainer.RegisterInstance(eventsContainer); Медведь медв = new Медведь { Вес = 48, Пол = tПол.Мужской }; Медведь медв2 = new Медведь { Вес = 148, Пол = tПол.Мужской }; diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterInternalServerErrorTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterInternalServerErrorTest.cs index b74dfa1b..803af572 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterInternalServerErrorTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterInternalServerErrorTest.cs @@ -1,12 +1,15 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Tests.Events { + using System; using System.Net; using System.Net.Http; using ICSSoft.STORMNET; + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; + using Unity; using Xunit; - using System; /// /// Класс тестов для тестирования логики после возникновения исключения. @@ -21,7 +24,7 @@ public class AfterInternalServerErrorTest : BaseODataServiceIntegratedTest /// Исключение, которое возникло внутри ODataService. /// Возвращаемый код HTTP. По-умолчанияю 500. /// Исключение, которое будет отправлено клиенту. - public Exception AfterInternalServerError(Exception e, ref HttpStatusCode code) + public Exception AfterInternalServerError(DataObjectController controller, Exception e, ref HttpStatusCode code) { Ex = e; code = HttpStatusCode.InternalServerError; @@ -36,7 +39,8 @@ public void TestAfterInternalServerError() { ActODataService(args => { - args.Token.Events.CallbackAfterInternalServerError = AfterInternalServerError; + var eventsContainer = new FakeEventHandlerContainer { CallbackAfterInternalServerError = AfterInternalServerError }; + args.UnityContainer.RegisterInstance(eventsContainer); Медведь медв = new Медведь { Вес = 48, Пол = tПол.Мужской }; Медведь медв2 = new Медведь { Вес = 148, Пол = tПол.Мужской }; diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterSaveTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterSaveTest.cs index 1e77a3b3..b6ec45d5 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterSaveTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/AfterSaveTest.cs @@ -11,10 +11,13 @@ using ICSSoft.STORMNET.Exceptions; using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; using NewPlatform.Flexberry.ORM.ODataService.Tests.Extensions; using Newtonsoft.Json; + using Unity; + using Xunit; /// @@ -31,7 +34,7 @@ public class AfterSaveTest : BaseODataServiceIntegratedTest /// Метод вызываемый после создания объекта. /// /// Объект после создания. - public void AfterCreate(DataObject obj) + public void AfterCreate(DataObjectController controller, DataObject obj) { ParamObj = obj; } @@ -40,7 +43,7 @@ public void AfterCreate(DataObject obj) /// Метод вызываемый после обновления объекта. /// /// Объект после обновления. - public void AfterUpdate(DataObject obj) + public void AfterUpdate(DataObjectController controller, DataObject obj) { ParamObj = obj; } @@ -49,7 +52,7 @@ public void AfterUpdate(DataObject obj) /// Метод вызываемый после удаления объекта. /// /// Объект перед удалением. - public void AfterDelete(DataObject obj) + public void AfterDelete(DataObjectController controller, DataObject obj) { ParamObj = obj; } @@ -79,9 +82,8 @@ public void AfterSavePostComplexObjectTest() ActODataService(args => { - args.Token.Events.CallbackAfterCreate = AfterCreate; - args.Token.Events.CallbackAfterUpdate = AfterUpdate; - args.Token.Events.CallbackAfterDelete = AfterDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackAfterCreate = AfterCreate, CallbackAfterUpdate = AfterUpdate, CallbackAfterDelete = AfterDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // ------------------ Только создания объектов ------------------ // Подготовка тестовых данных в формате OData. @@ -226,9 +228,8 @@ public void AfterSavePatchSimpleObjectTest() { ActODataService(args => { - args.Token.Events.CallbackAfterCreate = AfterCreate; - args.Token.Events.CallbackAfterUpdate = AfterUpdate; - args.Token.Events.CallbackAfterDelete = AfterDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackAfterCreate = AfterCreate, CallbackAfterUpdate = AfterUpdate, CallbackAfterDelete = AfterDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // Создаем объект данных, который потом будем обновлять, и добавляем в базу обычным сервисом данных. Лес лес = new Лес { Название = "Чаща", Площадь = 100 }; @@ -279,9 +280,8 @@ public void AfterSaveDeleteObjectTest() { ActODataService(args => { - args.Token.Events.CallbackAfterCreate = AfterCreate; - args.Token.Events.CallbackAfterUpdate = AfterUpdate; - args.Token.Events.CallbackAfterDelete = AfterDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackAfterCreate = AfterCreate, CallbackAfterUpdate = AfterUpdate, CallbackAfterDelete = AfterDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // ------------------ Удаление простого объекта ----------------------------- // Создаем объект данных, который потом будем удалять, и добавляем в базу обычным сервисом данных. diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeGetTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeGetTest.cs index 8462c7a5..cd1dc157 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeGetTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeGetTest.cs @@ -7,6 +7,11 @@ using ICSSoft.STORMNET; using ICSSoft.STORMNET.Business; + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; + + using Unity; + using Xunit; /// @@ -21,7 +26,7 @@ public class BeforeGetTest : BaseODataServiceIntegratedTest /// /// /// - public bool BeforeGet(ref LoadingCustomizationStruct lcs) + public bool BeforeGet(DataObjectController controller, ref LoadingCustomizationStruct lcs) { this.lcs = lcs; return true; @@ -37,7 +42,8 @@ public void TestBeforeGet() ActODataService(args => { - args.Token.Events.CallbackBeforeGet = BeforeGet; + var eventsContainer = new FakeEventHandlerContainer { CallbackBeforeGet = BeforeGet }; + args.UnityContainer.RegisterInstance(eventsContainer); DateTime date = new DateTimeOffset(DateTime.Now).UtcDateTime; string prevDate = $"{date.AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ss")}%2B05:00"; diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeSaveTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeSaveTest.cs index 6b6338dc..3507d57d 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeSaveTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/BeforeSaveTest.cs @@ -9,10 +9,14 @@ using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Exceptions; + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; using NewPlatform.Flexberry.ORM.ODataService.Tests.Extensions; using Newtonsoft.Json; + using Unity; + using Xunit; /// @@ -29,7 +33,7 @@ public class BeforeSaveTest : BaseODataServiceIntegratedTest /// Метод вызываемый перед созданием объекта. /// /// Объект перед созданием. - public bool BeforeCreate(DataObject obj) + public bool BeforeCreate(DataObjectController controller, DataObject obj) { ParamObj = obj; return true; @@ -39,7 +43,7 @@ public bool BeforeCreate(DataObject obj) /// Метод вызываемый перед обновлением объекта. /// /// Объект перед обновлением. - public bool BeforeUpdate(DataObject obj) + public bool BeforeUpdate(DataObjectController controller, DataObject obj) { ParamObj = obj; return true; @@ -49,7 +53,7 @@ public bool BeforeUpdate(DataObject obj) /// Метод вызываемый перед удалением объекта. /// /// Объект перед удалением. - public bool BeforeDelete(DataObject obj) + public bool BeforeDelete(DataObjectController controller, DataObject obj) { ParamObj = obj; return true; @@ -80,9 +84,8 @@ public void BeforeSavePostComplexObjectTest() ActODataService(args => { - args.Token.Events.CallbackBeforeCreate = BeforeCreate; - args.Token.Events.CallbackBeforeUpdate = BeforeUpdate; - args.Token.Events.CallbackBeforeDelete = BeforeDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackBeforeCreate = BeforeCreate, CallbackBeforeUpdate = BeforeUpdate, CallbackBeforeDelete = BeforeDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // ------------------ Только создания объектов ------------------ // Подготовка тестовых данных в формате OData. @@ -227,9 +230,8 @@ public void BeforeSavePatchSimpleObjectTest() { ActODataService(args => { - args.Token.Events.CallbackBeforeCreate = BeforeCreate; - args.Token.Events.CallbackBeforeUpdate = BeforeUpdate; - args.Token.Events.CallbackBeforeDelete = BeforeDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackBeforeCreate = BeforeCreate, CallbackBeforeUpdate = BeforeUpdate, CallbackBeforeDelete = BeforeDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // Создаем объект данных, который потом будем обновлять, и добавляем в базу обычным сервисом данных. Лес лес = new Лес { Название = "Чаща", Площадь = 100 }; @@ -280,9 +282,8 @@ public void BeforeSaveDeleteObjectTest() { ActODataService(args => { - args.Token.Events.CallbackBeforeCreate = BeforeCreate; - args.Token.Events.CallbackBeforeUpdate = BeforeUpdate; - args.Token.Events.CallbackBeforeDelete = BeforeDelete; + var eventsContainer = new FakeEventHandlerContainer { CallbackBeforeCreate = BeforeCreate, CallbackBeforeUpdate = BeforeUpdate, CallbackBeforeDelete = BeforeDelete }; + args.UnityContainer.RegisterInstance(eventsContainer); // ------------------ Удаление простого объекта ----------------------------- // Создаем объект данных, который потом будем удалять, и добавляем в базу обычным сервисом данных. diff --git a/NewPlatform.Flexberry.ORM.ODataService/Events/Delegates.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/Delegates.cs similarity index 68% rename from NewPlatform.Flexberry.ORM.ODataService/Events/Delegates.cs rename to Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/Delegates.cs index 8cbc7935..e7ad3c75 100644 --- a/NewPlatform.Flexberry.ORM.ODataService/Events/Delegates.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/Delegates.cs @@ -1,61 +1,64 @@ -namespace NewPlatform.Flexberry.ORM.ODataService.Events +namespace NewPlatform.Flexberry.ORM.ODataService.Tests.Events { - using ICSSoft.STORMNET; - using ICSSoft.STORMNET.Business; using System; using System.Net; + using ICSSoft.STORMNET; + using ICSSoft.STORMNET.Business; + + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + /// /// Тип делегата, вызываемого перед выполнением запроса. /// /// . /// - public delegate bool DelegateBeforeGet(ref LoadingCustomizationStruct lcs); + public delegate bool DelegateBeforeGet(DataObjectController controller, ref LoadingCustomizationStruct lcs); /// /// Тип делегата, вызываемого перед созданием объекта. /// /// Объект. /// - public delegate bool DelegateBeforeCreate(DataObject obj); + public delegate bool DelegateBeforeCreate(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого перед изменением объекта. /// /// Объект. /// - public delegate bool DelegateBeforeUpdate(DataObject obj); + public delegate bool DelegateBeforeUpdate(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого перед удалением объекта. /// /// Объект. /// - public delegate bool DelegateBeforeDelete(DataObject obj); + public delegate bool DelegateBeforeDelete(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого после вычитывания объектов. /// /// Вычитанные объекты. - public delegate void DelegateAfterGet(ref DataObject[] objs); + public delegate void DelegateAfterGet(DataObjectController controller, ref DataObject[] objs); /// /// Тип делегата, вызываемого после создания объекта. /// /// Объект после создания. - public delegate void DelegateAfterCreate(DataObject obj); + public delegate void DelegateAfterCreate(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого после обновления объекта. /// /// Объект после обновления. - public delegate void DelegateAfterUpdate(DataObject obj); + public delegate void DelegateAfterUpdate(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого после удаления объекта. /// /// Объект перед удалением. - public delegate void DelegateAfterDelete(DataObject obj); + public delegate void DelegateAfterDelete(DataObjectController controller, DataObject obj); /// /// Тип делегата, вызываемого после возникновения исключения. @@ -63,6 +66,6 @@ /// Исключение, которое возникло внутри ODataService. /// Возвращаемый код HTTP. По-умолчанияю 500. /// Исключение, которое будет отправлено клиенту. - public delegate Exception DelegateAfterInternalServerError(Exception ex, ref HttpStatusCode code); + public delegate Exception DelegateAfterInternalServerError(DataObjectController controller, Exception ex, ref HttpStatusCode code); } diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/FakeEventHandlerContainer.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/FakeEventHandlerContainer.cs new file mode 100644 index 00000000..ff83efa6 --- /dev/null +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Events/FakeEventHandlerContainer.cs @@ -0,0 +1,121 @@ +namespace NewPlatform.Flexberry.ORM.ODataService.Tests.Events +{ + using System; + using System.Net; + + using ICSSoft.STORMNET; + using ICSSoft.STORMNET.Business; + + using NewPlatform.Flexberry.ORM.ODataService.Controllers; + using NewPlatform.Flexberry.ORM.ODataService.Events; + + public class FakeEventHandlerContainer : IEventHandlerContainer + { + /// + public ManagementToken Token { get; set; } + + /// + /// Делегат для вызова логики перед выполнением запроса. + /// + public DelegateBeforeGet CallbackBeforeGet { get; set; } + + /// + /// Делегат для вызова логики перед изменением объекта. + /// + public DelegateBeforeUpdate CallbackBeforeUpdate { get; set; } + + /// + /// Делегат для вызова логики перед созданием объекта. + /// + public DelegateBeforeCreate CallbackBeforeCreate { get; set; } + + /// + /// Делегат для вызова логики перед удалением объекта. + /// + public DelegateBeforeDelete CallbackBeforeDelete { get; set; } + + /// + /// Делегат для вызова логики после вычитывания объектов. + /// + public DelegateAfterGet CallbackAfterGet { get; set; } + + /// + /// Делегат для вызова логики после сохранения объекта. + /// + public DelegateAfterCreate CallbackAfterCreate { get; set; } + + /// + /// Делегат для вызова логики после обновления объекта. + /// + public DelegateAfterUpdate CallbackAfterUpdate { get; set; } + + /// + /// Делегат для вызова логики после удаления объекта. + /// + public DelegateAfterDelete CallbackAfterDelete { get; set; } + + /// + /// Делегат, вызываемый после возникновения исключения. + /// + public DelegateAfterInternalServerError CallbackAfterInternalServerError { get; set; } + + /// + public bool BeforeGet(DataObjectController controller, ref LoadingCustomizationStruct lcs) + { + return CallbackBeforeGet == null || CallbackBeforeGet(controller, ref lcs); + } + + /// + public bool BeforeCreate(DataObjectController controller, DataObject obj) + { + return CallbackBeforeCreate == null || CallbackBeforeCreate(controller, obj); + } + + /// + public bool BeforeUpdate(DataObjectController controller, DataObject obj) + { + return CallbackBeforeUpdate == null || CallbackBeforeUpdate(controller, obj); + } + + /// + public bool BeforeDelete(DataObjectController controller, DataObject obj) + { + return CallbackBeforeDelete == null || CallbackBeforeDelete(controller, obj); + } + + /// + public void AfterGet(DataObjectController controller, ref DataObject[] objs) + { + CallbackAfterGet?.Invoke(controller, ref objs); + } + + /// + public void AfterCreate(DataObjectController controller, DataObject obj) + { + CallbackAfterCreate?.Invoke(controller, obj); + } + + /// + public void AfterUpdate(DataObjectController controller, DataObject obj) + { + CallbackAfterUpdate?.Invoke(controller, obj); + } + + /// + public void AfterDelete(DataObjectController controller, DataObject obj) + { + CallbackAfterDelete?.Invoke(controller, obj); + } + + /// + public Exception AfterInternalServerError(DataObjectController controller, Exception ex, ref HttpStatusCode code) + { + if (CallbackAfterInternalServerError == null) + { + return ex; + } + + return CallbackAfterInternalServerError(controller, ex, ref code); + } + } +} \ No newline at end of file diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Handlers/PerRequestUpdateEdmModelHandlerTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Handlers/PerRequestUpdateEdmModelHandlerTest.cs index 68de7005..68fc6d38 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Handlers/PerRequestUpdateEdmModelHandlerTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Handlers/PerRequestUpdateEdmModelHandlerTest.cs @@ -3,15 +3,17 @@ using System.Reflection; using System.Web.OData.Routing; using System.Web.OData.Routing.Conventions; - using Xunit; + using NewPlatform.Flexberry.ORM.ODataService.Events; + using NewPlatform.Flexberry.ORM.ODataService.Functions; using NewPlatform.Flexberry.ORM.ODataService.Handlers; using NewPlatform.Flexberry.ORM.ODataService.Model; + using Xunit; + /// /// Unit test class for . /// - public class PerRequestUpdateEdmModelHandlerTest { /// @@ -29,7 +31,9 @@ public void TestWebApi() var assemblies = new Assembly[0]; var modelBuilder = new DefaultDataObjectEdmModelBuilder(assemblies); - new PerRequestUpdateEdmModelHandler(new ManagementToken(route, model), modelBuilder); + var eventHandlerContainer = new EventHandlerContainer(); + var functionContainer = new FunctionContainer(); + new PerRequestUpdateEdmModelHandler(new ManagementToken(route, model, eventHandlerContainer, functionContainer), modelBuilder); } } } diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/NewPlatform.Flexberry.ORM.ODataService.Tests.csproj b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/NewPlatform.Flexberry.ORM.ODataService.Tests.csproj index a8254c3f..e77074d3 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/NewPlatform.Flexberry.ORM.ODataService.Tests.csproj +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/NewPlatform.Flexberry.ORM.ODataService.Tests.csproj @@ -275,6 +275,8 @@ + + diff --git a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/SelfHostBaseODataServiceIntegratedTest.cs b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/SelfHostBaseODataServiceIntegratedTest.cs index b2403357..ae5a83cb 100644 --- a/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/SelfHostBaseODataServiceIntegratedTest.cs +++ b/Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/SelfHostBaseODataServiceIntegratedTest.cs @@ -79,8 +79,7 @@ public virtual void ActODataService(Action action) config.EnableCors(new EnableCorsAttribute("*", "*", "*")); config.DependencyResolver = new UnityDependencyResolver(container); - var token = config.MapODataServiceDataObjectRoute(_builder, new HttpServer()); - var args = new TestArgs { UnityContainer = container, DataService = dataService, HttpClient = client, Token = token }; + var args = new TestArgs(() => config.MapODataServiceDataObjectRoute(_builder, new HttpServer())) { UnityContainer = container, DataService = dataService, HttpClient = client }; try {