Skip to content

Commit

Permalink
Merge pull request #255 from Flexberry/feature-239-use-proper-di
Browse files Browse the repository at this point in the history
Feature 239 use proper di
  • Loading branch information
Anisimova2020 committed Mar 28, 2024
2 parents fa63801 + 96e1c37 commit a0409e2
Show file tree
Hide file tree
Showing 85 changed files with 1,444 additions and 1,432 deletions.
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,49 @@ This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]

### Added
1. Due to backward compatibility it is necessary now to initialize manually at start point:

`DataServiceProvider.DataService = ds; // ds - DataService.
ExternalLangDef.LanguageDef = new ExternalLangDef(ds); // ds - DataService.
DetailVariableDef.ViewGenerator = null; // or resolving of interface IViewGenerator.`

2. Interface `IBusinessServerProvider`.
3. Public property `IBusinessServerProvider BusinessServerProvider { get; protected set; }` to class `SQLDataService`.
4. Class `NewPlatform.Flexberry.ORM.CurrentUserService.EmptyCurrentUser : ICurrentUser` (a stub for empty user).
5. Interface `NewPlatform.Flexberry.ORM.CurrentUserService.ICurrentUser` (user credentials).
6. Help class `UnityServiceProvider` (it helps to organize connection between `IUnityContainer` and `IServiceProvider` for tests).
7. Dependency injection of `IConfigResolver` throught the property of `SQLDataService`.

### Changed
1. Method `LockService.ClearAllUserLocks` changed to unstatic.
2. Method `LockService.GetUserName` changed to unstatic.
3. Data services `MSSQLDataService`, `OracleDataService`, `PostgresDataService` need initialization of property `CurrentUser` if `value.FunctionDef.StringedView == "CurrentUser"`.
4. Static class `CurrentUserServiceExtensions` renamed to `CurrentUserExtensions`.
5. Constructor of class `LockService`.
6. Constructor of class `SQLDataService` (`DRDataService`, `MSSQLDataService`, `OracleDataService`, `PostgresDataService`): added dependency injection of `IAuditService` and `ISecurityManager` throught the constructor of `SQLDataService`.
7. Constructor of class `XMLFileDataService`.
8. Constructor of class `AuditService`.
9. Constructor of class `BusinessServerProvider`.


### Deprecated
1. `ExternalLangDef.LanguageDef` (correct way is creation of new instance of `ExternalLangDef` with proper DataService).
2. `UnityFactory`.
3. `DataServiceProvider.DataService`.

### Removed
1. Using of `UnityFactory` at code (there can be used not only Unity but other variant of DI supporting `IServiceProvider` interface).
2. Public properties `Current`, `ApplicationMode` and static method `InitAuditService` removed from class `AuditService`.
3. Enum `ICSSoft.STORMNET.Business.Audit.AppMode`.
4. Class `DataServiceWrapper`.
5. Public method `CheckAccessToAttribute` from class `Information`.
6. Class `DirectoryServicesTools`.
7. Class `ICSSoft.Services.CurrentUser`.
8. Class `CurrentUserService`.
9. Class `CurrentWindowsUser`.
10. Interface `ICSSoft.Services.CurrentUserService.IUser`.
11. [BREAKING CHANGE] Setting of `STORMAdvLimit.User` at setter of `STORMAdvLimit.Publish`.
12. Getting of `CommandTimeout` throught configuration file.

### Fixed

Expand Down
4 changes: 2 additions & 2 deletions Flexberry ORM.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30804.86
# Visual Studio Version 17
VisualStudioVersion = 17.5.33516.290
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet Package Properties", "NuGet Package Properties", "{8B2EC67F-05B1-4C15-8CAE-C0D58F75CE4C}"
ProjectSection(SolutionItems) = preProject
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
namespace ICSSoft.STORMNET.Windows.Forms
{
using ICSSoft.Services;

/// <summary>
/// Объектное представление сохраняемого в базе ограничения.
/// Не содержит логики по десериализации.
Expand All @@ -26,7 +24,6 @@ public virtual bool Published
set
{
fPublished = value;
User = value ? null : CurrentUserService.CurrentUser.FriendlyName;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@
{
using System;

using ICSSoft.Services;
using ICSSoft.STORMNET.FunctionalLanguage;

using Unity;
using Unity.Exceptions;

/// <summary>
/// Определение переменной ограничения, предназначенное для описания детейлов.
/// </summary>
Expand All @@ -17,6 +13,8 @@ public class DetailVariableDef : VariableDef
private string fConnectMasterPorp;
private string[] fownerConnectProp;

private static IViewGenerator viewGenerator;

public DetailVariableDef()
{
}
Expand Down Expand Up @@ -48,6 +46,28 @@ public DetailVariableDef(ICSSoft.STORMNET.FunctionalLanguage.ObjectType type, st
fView.AddProperty(ConnectMasterPorp);
}

/// <summary>
/// Динамический генератор ограничений.
/// Данная конструкция выполнена для очистки проекта от применения Unity напрямую.
/// </summary>
public static IViewGenerator ViewGenerator
{
private get
{
return viewGenerator;
}

set
{
if (viewGenerator != null)
{
throw new Exception("DetailVariableDef.ViewGenerator should not be reset.");
}

viewGenerator = value;
}
}

/// <summary>
/// Получение представления по его имени и типу.
/// Если представление не найдено среди статических, то есть возможность сформировать его динамически (используется в редакторе ограничений).
Expand All @@ -62,17 +82,7 @@ public static View GetPossibleDynamicView(string viewName, Type dataObjectType)
if (resultView == null)
{
// Если не удалось получить представление для детейла стандартным методом, то пробуем сделать это другим способом.
IUnityContainer container = UnityFactory.GetContainer();
IViewGenerator resolvedType;

try
{
resolvedType = container.Resolve<IViewGenerator>();
}
catch (ResolutionFailedException)
{
resolvedType = null;
}
IViewGenerator resolvedType = ViewGenerator;

if (resolvedType != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,55 +13,48 @@

public partial class ExternalLangDef : SQLWhereLanguageDef
{
/// <summary>
/// Сервис данных для построения подзапросов.
/// </summary>
private readonly IDataService dataService;

private static ExternalLangDef langDef;

/// <summary>
/// Внимание, используйте конструктор только в исключительных ситуациях.
/// </summary>
public ExternalLangDef()
/// <param name="dataService">Сервис данных для построения подзапросов.</param>
public ExternalLangDef(IDataService dataService)
{
fieldDataObjectType.SimplificationValue = DataObjectToSimpleValue;
fieldDataObjectType.UnSimplificationValue = SimpleValueToDataObject;
ChFuncNames = new List<string>
{
"Count", "SUM", funcCountWithLimit, "ExistExact", "Exist", "AVG", "MAX", "MIN", funcSumWithLimit, funcAvgWithLimit, funcMaxWithLimit, funcMinWithLimit, "ExistAll", "ExistAllExact",
};

this.dataService = dataService;
}

/// <summary>
/// Статический ExternalLangDef, используется для получения функций.
/// </summary>
public static ExternalLangDef LanguageDef { get; } = new ExternalLangDef();

/// <summary>
/// сервис данных для построения подзапросов.
/// </summary>
private Business.IDataService m_objDataService;

private readonly List<string> ChFuncNames;

/// <summary>
/// Сервис данных для построения подзапросов. Если не указан, используется DataServiceProvider.DataService.
/// </summary>
public Business.IDataService DataService
[Obsolete("It is better to use constructed entity of ExternalLangDef by new keyword.")]
public static new ExternalLangDef LanguageDef
{
get
{
if (m_objDataService != null)
{
return m_objDataService;
}
else
{
m_objDataService = Business.DataServiceProvider.DataService;
return m_objDataService;
}
return langDef ?? throw new NullReferenceException("ExternalLangDef.LanguageDef is not set.");
}

set
{
m_objDataService = value;
langDef = value;
}
}

private readonly List<string> ChFuncNames;

public string paramTrue
{
get { return "True"; }
Expand Down Expand Up @@ -555,7 +548,7 @@ private object SimpleValueToDataObject(object val)
v.AddProperty(prop);
}

DataService.LoadObject(v, dobj);
dataService.LoadObject(v, dobj);

return dobj;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,6 @@ public static View GetViewWithPropertiesUsedInFunction(View view, Function funct
throw new ArgumentNullException("function");
}

SQLWhereLanguageDef langdef = ExternalLangDef.LanguageDef;

// Создадим копию представления.
// ToDo: При текущей реализации клонирования происходят аномалии, т.к. вложенные объекты не копируются полностью, копируются только ссылки. В TFS создана ошибка №30700.
var enrichedView = view.Clone();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
<ProjectReference Include="..\ICSSoft.STORMNET.DataObject\ICSSoft.STORMNET.DataObject.csproj" />
<ProjectReference Include="..\ICSSoft.STORMNET.FunctionalLanguage\ICSSoft.STORMNET.FunctionalLanguage.csproj" />
<ProjectReference Include="..\NewPlatform.Flexberry.ORM.CurrentUserService\NewPlatform.Flexberry.ORM.CurrentUserService.csproj" />
<ProjectReference Include="..\NewPlatform.Flexberry.ORM.UnityFactory\NewPlatform.Flexberry.ORM.UnityFactory.csproj" />
</ItemGroup>

</Project>
49 changes: 18 additions & 31 deletions ICSSoft.STORMNET.Business.LockService/LockService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using ICSSoft.STORMNET.Exceptions;
using ICSSoft.STORMNET.FunctionalLanguage;
using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere;
using NewPlatform.Flexberry.ORM.CurrentUserService;

/// <summary>
/// Классический сервис блокировок.
Expand All @@ -17,26 +18,26 @@ public class LockService
/// <summary>
/// Сервис данных, через который по умолчанию нужно делать запрос к БД.
/// </summary>
private IDataService dataService = DataServiceProvider.DataService;
private readonly IDataService dataService;

/// <summary>
/// Конструктор без параметров. В качестве сервиса данных по умолчанию будет использоваться DataServiceProvider.DataService.
/// Сервис доступа к данным текущего пользовтаеля.
/// </summary>
public LockService()
: this(null)
{
}
private readonly ICurrentUser currentUser;

/// <summary>
/// Конструктор с определением сервиса данных.
/// Initializes a new instance of the <see cref="LockService" /> class.
/// </summary>
/// <param name="dataService">
/// Сервис данных, через который по умолчанию нужно делать запрос к БД.
/// Если передан null, то будет использоваться DataServiceProvider.DataService.
/// </param>
public LockService(IDataService dataService)
/// <param name="currentUser">
/// Сервис доступа к данным текущего пользовтаеля.
/// </param>
public LockService(IDataService dataService, ICurrentUser currentUser)
{
this.dataService = dataService ?? DataServiceProvider.DataService;
this.dataService = dataService ?? throw new ArgumentNullException(nameof(dataService));
this.currentUser = currentUser ?? throw new ArgumentNullException(nameof(currentUser));
}

#region Constants and Fields
Expand Down Expand Up @@ -71,44 +72,30 @@ public LockService(IDataService dataService)

/// <summary>
/// Удалить все блокировки текущего юзера (какие есть в базе).
/// В качестве сервиса данных используется переданный сервис данных.
/// <param name="dataService">Сервис данных.</param>
/// </summary>
public static void ClearAllUserLocks(IDataService dataService)
public void ClearAllUserLocks()
{
var ds = dataService ?? DataServiceProvider.DataService;

// убиваем все блокировки, оставшиеся с предыдущих времен
SQLWhereLanguageDef lg = SQLWhereLanguageDef.LanguageDef;
var vd = new VariableDef(lg.GetObjectTypeForNetType(typeof(string)), "UserName");

Function func = lg.GetFunction(
lg.funcEQ, vd, GetUserName() + (UseMachineNameInKey ? " @ " + Environment.MachineName : string.Empty));

var lcs1 = new LoadingCustomizationStruct(0);
LoadingCustomizationStruct lcs1 = new LoadingCustomizationStruct(0);

var view = new View(typeof(LockData), View.ReadType.WithRelated);
View view = new View(typeof(LockData), View.ReadType.WithRelated);

lcs1.Init(null, func, new[] { typeof(LockData) }, view, null);

DataObject[] arr = ds.LoadObjects(lcs1);
DataObject[] arr = dataService.LoadObjects(lcs1);

foreach (DataObject obj in arr)
{
obj.SetStatus(ObjectStatus.Deleted);
}

ds.UpdateObjects(ref arr);
}

/// <summary>
/// Удалить все блокировки текущего юзера (какие есть в базе).
/// В качестве сервиса данных используется DataServiceProvider.DataService.
/// Если нужно использовать другой DataService, используйте другую перегрузку метода.
/// </summary>
public static void ClearAllUserLocks()
{
ClearAllUserLocks(DataServiceProvider.DataService);
dataService.UpdateObjects(ref arr);
}

/// <summary>
Expand Down Expand Up @@ -536,9 +523,9 @@ public string SetWebLock(string LockKey, string userName, IDataService ds)
/// <returns>
/// The get user name.
/// </returns>
private static string GetUserName()
private string GetUserName()
{
return Services.CurrentUserService.CurrentUser.Login;
return currentUser?.Login;
}

/// <summary>
Expand Down
29 changes: 29 additions & 0 deletions ICSSoft.STORMNET.Business.MSSQLDataService/DRDataService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,39 @@
namespace ICSSoft.STORMNET.Business
{
using ICSSoft.STORMNET.Business.Audit;
using ICSSoft.STORMNET.Business.Interfaces;
using ICSSoft.STORMNET.Security;

/// <summary>
/// Сервис данных для грязного чтения (MSSQLServer).
/// </summary>
public class DRDataService : ICSSoft.STORMNET.Business.MSSQLDataService
{
/// <summary>
/// Создание сервиса данных для Microsoft SQL Server с указанием настроек проверки полномочий.
/// </summary>
/// <param name="securityManager">Менеджер полномочий.</param>
/// <param name="auditService">Сервис аудита.</param>
/// <param name="businessServerProvider">The provider for <see cref="BusinessServer"/> creation.</param>
public DRDataService(ISecurityManager securityManager, IAuditService auditService, IBusinessServerProvider businessServerProvider)
: base(securityManager, auditService, businessServerProvider)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="DRDataService"/> class with specified security manager, audit service and converter.
/// </summary>
/// <param name="securityManager">The security manager instance.</param>
/// <param name="auditService">The audit service instance.</param>
/// <param name="businessServerProvider">The provider for <see cref="BusinessServer"/> creation.</param>
/// <param name="converterToQueryValueString">The converter instance.</param>
/// <param name="notifierUpdateObjects">An instance of the class for custom process updated objects.</param>
public DRDataService(ISecurityManager securityManager, IAuditService auditService, IBusinessServerProvider businessServerProvider, IConverterToQueryValueString converterToQueryValueString, INotifyUpdateObjects notifierUpdateObjects = null)
: base(securityManager, auditService, businessServerProvider, converterToQueryValueString, notifierUpdateObjects)
{
}

/// <inheritdoc />
public override string GetJoinTableModifierExpression()
{
return " WITH (NOLOCK) ";
Expand Down
Loading

0 comments on commit a0409e2

Please sign in to comment.