diff --git a/_data/sidebars/flexberry-orm_sidebar.yml b/_data/sidebars/flexberry-orm_sidebar.yml index 04702de40..9872c8435 100644 --- a/_data/sidebars/flexberry-orm_sidebar.yml +++ b/_data/sidebars/flexberry-orm_sidebar.yml @@ -1,766 +1,762 @@ -# This is your sidebar TOC. The sidebar code loops through sections here and provides the appropriate formatting. - - -entries: -- title: Sidebar - product: Flexberry ORM - version: 6.0.0 - folders: - - - title: О Flexberry ORM - output: web, pdf - folderitems: - - title: About - title_ru: О модуле - url: /fo_landing_page.html - output: web - - - title: Объектная модель - output: web, pdf - folderitems: - - title: DataObject - title_ru: Объекты данных - url: /fo_data-object.html - output: web - - - title: Status and loading state of the data object - title_ru: Статус и состояние загрузки объекта данных - url: /fo_object-status.html - output: web - - - title: How to load data object properties - title_ru: Порядок загрузки свойств объекта данных - url: /fo_order-loading-property.html - output: web - - - title: Access to the object's own attributes and attributes of related objects - title_ru: Доступ к собственным атрибутам объекта и атрибутам связанных объектов - url: /fo_own-object-attributes.html - output: web - - - title: Data Class Attributes - title_ru: Атрибуты классов данных - url: /fo_attributes-class-data.html - output: web - - - title: Storing object data in a relational database - title_ru: Хранение объектных данных в реляционной базе данных - url: /fo_storing-data-objects.html - output: web - - - title: Designing Data Objects - title_ru: Конструирование объектов данных - url: /fo_construction-data-objects.html - output: web - - - title: Data object as a class attribute - title_ru: Атрибут класса типа объекта данных - url: /fo_data-object-as-attribute-type.html - output: web - - - title: DataObjectCopy - title_ru: Копия объекта данных - url: /fo_data-object-copy.html - output: web - - - title: - title_ru: Первичные ключи объектов - url: /fo_primary-keys-objects.html - output: web - - - title: Structure of data object classes - title_ru: Структура классов объектов данных - url: /fo_data-object-structure.html - output: web - - - title: Children's associations and their properties - title_ru: Детейловые ассоциации и их свойства - url: /fo_detail-associations-properties.html - output: web - - - title: Obtaining metadata for objects - title_ru: Получение метаданных объектов - url: /fo_methods-class-information.html - output: web - - - title: Prototyping - title_ru: Прототипизация - url: /fo_data-object-prototype.html - output: - - - title: Context-sensitive data object cache - title_ru: Контекстно-зависимый кэш объектов данных - url: /fo_context-sensitive-cache.html - output: web - - - title: Converting the data object property type to a storage type - title_ru: Преобразование типа свойства объекта данных к типу хранилища - url: /fo_convert-type-property.html - output: web - - - title: Copying Data Objects - title_ru: Копирование объектов данных - url: /fo_copying-data-objects.html - output: web - - - title: Checking the object field in the set method - title_ru: Проверка поля объекта в методе set - url: /fo_check-object-set.html - output: web - - - title: Getting a Presentation Value for a Data Object - title_ru: Получение презентационного значения для объекта данных - url: /fo_get-presentation-value.html - output: web - - - title: Set the current object when the application starts - title_ru: Установка текущего объекта при запуске приложения - url: /fo_define-default-object.html - output: web - - - title: Setting the value of the field of the object to be created - title_ru: Задание значения поля создаваемого объекта - url: /fo_define-field-created.html - output: web - - - title: DisableInsertPropertyAttribute - title_ru: DisableInsertPropertyAttribute - url: /fo_disable-insert-property-attribute.html - output: web - - - title: Features of setting the default value - title_ru: Особенности задания значения по умолчанию - url: /fo_features-dafault-value.html - output: web - - - title: Functionality when working with arrays of child objects - title_ru: Функциональность при работе с массивами детейловых объектов - url: /fo_functionality-work-detail-array.html - output: web - - - title: Information.GetPropertyStorageName - title_ru: Information.GetPropertyStorageName - url: /fo_information-get-property-storage-name.html - output: web - - - title: Variants of opening an object for Readonly - title_ru: Варианты открытия объекта только на чтение - url: /fo_read-only-object.html - output: web - - - title: Updating related objects - title_ru: Обновление связанных объектов - url: /fo_update-related-objects.html - output: web - - - title: Displaying the form of masters and children on the interface - title_ru: Отображение на интерфейсе формы мастеров и детейлов - url: /fo_masters-details.html - output: web - - - title: Example of loading and changing an object - title_ru: Пример загрузки и изменения объекта - url: /fo_load-alter-objects.html - output: web - - - title: Example of loading an object graph - title_ru: Пример загрузки графа объектов - url: /fo_load-multiple-details-example.html - output: web - - - title: Example of object prototyping - title_ru: Пример прототипизации объекта - url: /fo_prototyping-example.html - output: web - - - title: Example of loading an object graph - title_ru: Пример загрузки графа объектов - url: /fo_load-multiple-details-example.html - output: web - - - title: An example of an action when saving an object - title_ru: Пример действий при сохранении объекта - url: /fo_actions-saving-object.html - output: web - - - title: Сервисы данных - output: web, pdf - folderitems: - - title: Data service - title_ru: Сервис данных - url: /fo_data-service.html - output: web - - title: Flexberry ORM Standard Data Services - title_ru: Стандартные сервисы данных Flexberry ORM - url: /fo_standard-data-services.html - output: web - - title: SQLDataService - title_ru: SQLDataService - url: /fo_sql-data-service.html - output: web - - title: Data service for working with PostgreSQL - title_ru: Cервис данных для работы с PostgreSQL - url: /fo_postgres-data-service.html - output: web - - title: MSSQLDataService - title_ru: MSSQLDataService - url: /fo_mssql-data-service.html - output: web - - title: Data service for working with Oracle Server - title_ru: Cервис данных для работы с Oracle Server - url: /fo_oracle-data-service.html - output: web - - title: Data service for MongoDB - title_ru: Cервис данных для работы с MongoDB - url: /fo_mongodb-data-service.html - output: web - - title: Data service for access to the Access DBMS - title_ru: Cервис данных для доступа к СУБД Access - url: /fo_odbc-access-ds.html - output: web - - title: ODBCDataService - title_ru: ODBCDataService - url: /fo_odbc-data-service.html - output: web - - title: ODBCMySqlDataService - title_ru: ODBCMySqlDataService - url: /fo_odbc-mysql-data-service.html - output: web - - title: DRDataService - title_ru: DRDataService - url: /fo_dr-data-service.html - output: web - - title: Data service for working with XML - title_ru: Cервис данных для работы с XML - url: /fo_xml-file-ds.html - output: web - - title: Implementing an arbitrary data service - title_ru: Реализация собственного сервиса данных - url: /fo_implement-custom-ds.html - output: web - - title: Designing a Data Service - title_ru: Конструирование сервиса данных - url: /fo_construction-ds.html - output: web - - title: Insensitivity to the register in the data service - title_ru: Нечувствительность к регистру в сервисе данных - url: /fo_insensitivity-register-ds.html - output: web - - title: Creating and saving data objects - title_ru: Создание и сохранение объектов данных - url: /fo_instantiate-persist-objects.html - output: web - - title: Interception of the formation of SQL-query to the database - title_ru: Перехват формирования SQL-запроса к БД - url: /fo_intercept-formation-sql-query.html - output: web - - title: Processing of the status and status of object loading - title_ru: Обработка статуса и состояния загрузки объекта - url: /fo_processing-status-condition-load.html - output: web - - title: Setting up read options - title_ru: Настройка параметров чтения - url: /fo_loading-customization-struct.html - output: web - - title: Updating objects with empty rows - title_ru: Обновление объектов с пустыми строками - url: /fo_updating-objects-empty-rows.html - output: web - - title: Support for multiple data warehouses in a single application - title_ru: Поддержка нескольких хранилищ данных в одном приложении - url: /fo_multibase.html - output: web - - title: Processing of one object - title_ru: Обработка одного объекта - url: /fo_processing-one-object.html - output: web - - title: Processing of a set of objects - title_ru: Обработка множества объектов - url: /fo_processing-multiple-objects.html - output: web - - title: Handling registers in object names - title_ru: Обработка регистров в именах объектов - url: /fo_processing-registers-names.html - output: web - - title: Portion reading - title_ru: Порционное чтение - url: /fo_reading-portion.html - output: web - - title: Using Postgres as a repository - title_ru: Использование СУБД Postgres в качестве хранилища - url: /fo_switching-storages.html - output: web - - title: Tools for Oracle Data Service - title_ru: Инструменты для работы Oracle Data Service - url: /fo_tools-oracle-ds.html - output: web - - title: SQL-queries in Flexberry - title_ru: SQL-запросы в Flexberry - url: /fo_sql-query.html - output: web - - title: Integration with Business Server - title_ru: Интеграция с бизнес-сервером - url: /fo_user-operations-dataservice.html - output: web - - title: Cropping rows with data service - title_ru: Обрезка строк сервисом данных - url: /fo_trimmed-string-storage.html - output: web - - title: Support for binary arrays with data service - title_ru: Поддержка бинарных массивов сервисом данных - url: /fo_binary-array-ds.html - output: web - - - title: Типы данных - output: web, pdf - folderitems: - - title: Data types in Flexberry ORM - title_ru: Типы данных во Flexberry ORM - url: /fo_flexberry-orm-types.html - output: web - - title: Notstored (computable) properties of the data object - title_ru: Нехранимые (вычислимые) свойства объекта данных - url: /fo_not-stored-attributes.html - output: web - - title: Example of non-stored object properties - title_ru: Пример нехранимых свойств объектов - url: /fo_nonstored-calculated-properties.html - output: web - - title: The use of not-stored classes - title_ru: Применение нехранимых классов - url: /fo_using-not-stored-classes.html - output: web - - title: Using data types in the application structure - title_ru: Использование типов данных в структуре приложения - url: /fo_type-usage.html - output: web - - title: The problem of the types used - title_ru: Проблема используемых типов - url: /fo_type-usage-problem.html - output: web - output: web - - title: Creating a Custom Data Type - title_ru: Создание пользовательского типа данных - url: /fo_creating-stereotypes-example.html - output: web - - title: An example of using custom types - title_ru: Пример использования собственных типов - url: /fo_using-custom-types-example.html - output: web - - - title: Язык запросов - output: web, pdf - folderitems: - - title: Comparison functions - title_ru: Функции сравнения - url: /fo_compare-functions.html - output: web - - title: ExternalLangDef - title_ru: ExternalLangDef - url: /fo_external-lang-def.html - output: web - - title: Restrictions on detail - title_ru: Ограничения на детейлы - url: /fo_exist-details.html - output: web - - title: Restrictions on the part of the date - title_ru: Ограничения на части даты - url: /fo_restriction-datetime.html - output: web - - title: FuncAND - title_ru: FuncAND - url: /fo_func-and.html - output: web - - title: FuncBETWEEN - title_ru: FuncBETWEEN - url: /fo_func-between.html - output: web - - title: FuncEQ - title_ru: FuncEQ - url: /fo_func-eq.html - output: web - - title: FuncIN - title_ru: FuncIN - url: /fo_func-in.html - output: web - - title: FuncIsNull - title_ru: FuncIsNull - url: /fo_func-is-null.html - output: web - - title: FuncLike - title_ru: FuncLike - url: /fo_func-like.html - output: web - - title: FuncNEQ - title_ru: FuncNEQ - url: /fo_func-neq.html - output: web - - title: FuncNOT - title_ru: FuncNOT - url: /fo_func-not.html - output: web - - title: FuncOR - title_ru: FuncOR - url: /fo_func-or.html - output: web - - title: FuncSQL - title_ru: FuncSQL - url: /fo_func-sql.html - output: web - - title: FuncToChar - title_ru: FuncToChar - url: /fo_func-to-char.html - output: web - - title: SQLWhereLanguageDef - title_ru: SQLWhereLanguageDef - url: /fo_function-list.html - output: web - - title: FunctionBuilder - title_ru: FunctionBuilder - url: /fo_function-builder.html - output: web - - title: FunctionBuilder examples - title_ru: FunctionBuilder примеры - url: /fo_function-builder-examples.html - output: web - - title: Function of implication - title_ru: Функция импликации - url: /fo_function-implication.html - output: web - - title: Convert constraint function to linq-constraint - title_ru: Преобразование функции ограничения в linq-ограничение - url: /fo_lcs-to-linq.html - output: web - - title: Restriction on children using aggregator properties - title_ru: Ограничение на детейлы с использованием свойств агрегатора - url: /fo_limit-details.html - output: web - - title: Serializing LimitFunction - title_ru: Сериализация LimitFunction - url: /fo_limit-function-serialization.html - output: web - - title: Limit Function - title_ru: Функции ограничения - url: /fo_limit-function.html - output: web - - title: Filtering and data sampling - title_ru: Фильтрация и ограничение выборки данных - url: /fo_limitation.html - output: web - - title: LINQPad - title_ru: LINQPad - url: /fo_linq-pad.html - output: web - - title: LINQProvider - title_ru: LINQProvider - url: /fo_linq-provider.html - output: web - - title: Features of LinqProvider - title_ru: Возможности LinqProvider - url: /fo_linq-provider-faetures.html - output: web - - title: Reading objects with a constraint - title_ru: Чтение объектов с наложенным ограничением - url: /fo_load-by-limit.html - output: web - - title: Description of variables when constructing constraint functions - title_ru: Описание переменных при построении функций ограничения - url: /fo_variable-def.html - output: web - - title: An example of imposing restrictions on the loading of objects - title_ru: Пример наложения ограничений на загрузку объектов - url: /fo_load-limitation-example.html - output: web - - title: Psedodetails in LinqProvider - title_ru: Псевдодетейлы в LinqProvider - url: /fo_psedodetails-linq-provider.html - output: web - - title: Creating your own functions when using LanguageDef - title_ru: Создание собственных функций при использовании LanguageDef - url: /fo_using-languagedef.html - output: web - - - title: Представления - output: web, pdf - folderitems: - - title: Operations with views - title_ru: Операции с представлениями - url: /fo_view-operations.html - output: web - - - title: Adaptive representations for details - title_ru: Адаптивные представления для детейлов - url: /fo_adaptive-views-details.html - output: web - - - title: ViewPropertyAppender - title_ru: ViewPropertyAppender - url: /fo_view-property-appender.html - output: web - - - title: Static properties for accessing class representations - title_ru: Статические свойства для доступа к представлениям класса - url: /fo_static-view-accessors.html - output: web - - - title: An example of working with views - title_ru: Пример работы с представлениями - url: /fo_work-with-views-example.html - output: web - - - title: An example of advanced work with views - title_ru: Пример продвинутой работы с представлениями - url: /fo_advanced-working-with-views.html - output: web - - - title: Бизнес-серверы - output: web, pdf - folderitems: - - title: Business servers - title_ru: Бизнес-сервер - url: /fo_business-server.html - output: web - - title: Business logic - title_ru: Бизнес-логика - url: /fo_business-logic.html - output: web - - title: Order of calls of business servers - title_ru: Порядок вызовов бизнес-серверов - url: /fo_order-calls-bs.html - output: web - - title: Checking the validity of changes to object data in the business server - title_ru: Проверка валидности изменений данных объекта в бизнес-сервере - url: /fo_change-data-check.html - output: web - - title: Updating multiple objects with a single transaction - title_ru: Обновление нескольких объектов одной транзакцией - url: /fo_bs-transact.html - output: web - - title: Checking the uniqueness of the entered data in the business server - title_ru: Проверка уникальности введенных данных в бизнес-сервере - url: /fo_unique-data-check.html - output: web - - title: Cascading deletion of objects - title_ru: Каскадное удаление объектов - url: /fo_cascade-delete.html - output: web - - title: IReferencesCascadeDelete - title_ru: IReferencesCascadeDelete - url: /fo_i-references-cascade-delete.html - output: web - - title: IReferencesNullDelete - title_ru: IReferencesNullDelete - url: /fo_i-references-null-delete.html - output: web - - title: Cancellation of deletion of the used value from the directory - title_ru: Отмена удаления используемого значения из справочника - url: /fo_delete-cancel.html - output: web - - title: Example of using a business server - title_ru: Пример использования бизнес-сервера - url: /fo_bs-example.html - output: web - - - title: Модуль для Flexberry Designer - output: web, pdf - folderitems: - - title: Generic methods in Flexberry Designer - title_ru: Генерик-методы в Flexberry Designer - url: /fo_generic-methods.html - output: web - - title: Create a class diagram for the database - title_ru: Создание диаграммы классов по базе данных - url: /fo_reverse-data-base.html - output: web - - title: Generate documentation on charts - title_ru: Генерация документации по диаграммам - url: /fo_doc-gen.html - output: web - - title: Plugin for generating XSD schema - title_ru: XMLSchemaGenerator Features - url: /fo_xml-schema-generator.html - output: web - - title: Generating application code using uml models - title_ru: Генерации кода приложения по uml-моделям - url: /fo_orm-case-plugin.html - output: web - - title: Functions of creating a backup and history of changes - title_ru: Функции создания бэкапа и истории изменений - url: /fo_history-plugin.html - output: web - - title: Search function - title_ru: Функция поиска - url: /fo_intelli-search-plugin.html - output: web - - title: Location of assemblies after code generation - title_ru: Расположение сборок после генерации кода - url: /fo_location-assembly.html - output: web - - title: Move or copy function - title_ru: Функция перемещения или копирования - url: /fo_move-case-plugin.html - output: web - - title: Brackets of the programmer - title_ru: Скобки программиста - url: /fo_programmer-brackets.html - output: web - - - title: OData - output: web, pdf - folderitems: - - title: ODataService - title_ru: ODataService - url: /fo_orm-odata-service.html - output: web - - - title: Configuring ODataService with several types of data services - title_ru: Настройка ODataService с несколькими типами сервисов данных - url: /fo_multiple-data-services-in-odata.html - output: web - - - title: Configuring entity type names in OData metadata - title_ru: Настройка имен типов сущностей в метаданных OData - url: /fo_metadata-for-client.html - output: web - - - title: OData-controllers debugging - title_ru: Отладка OData-контроллеров - url: /fo_orm-odata-debug.html - output: web - - - title: Монитор SQL-запросов - output: web, pdf - folderitems: - - title: Business task monitor - title_ru: Монитор задач - url: /fo_business-task-monitor.html - output: web - - title: Service for writing SQL-scripts for data changes - title_ru: Сервис записи SQL-скриптов изменения данных - url: /fo_changes-sql-bt-monitor.html - output: web - - title: Creating and Connecting a Task Monitor - title_ru: Создание и подключение монитора задач - url: /fo_creating-connection-bt-monitor.html - output: web - - - title: Сервис текущего пользователя - output: web, pdf - folderitems: - - title: Current User Service - title_ru: Сервис текущего пользователя - url: /fo_current-user-service.html - output: web - - - title: Dependency Injection - output: web, pdf - folderitems: - - title: Default data service - title_ru: Сервис данных по умолчанию - url: /fo_ds-provider.html - output: web - - title: Flexberry UnityFactory - title_ru: Flexberry UnityFactory - url: /fo_unity-factory.html - output: web - - - title: Сервис блокировок - output: web, pdf - folderitems: - - title: Locking service - title_ru: Сервис блокировок - url: /fo_lock-service.html - output: web - - title: Data object locking - title_ru: Блокирование объекта данных - url: /fo_blocking-object-data.html - output: web - - - title: Дополнительные возможности - output: web, pdf - folderitems: - - title: Additional loading data object - title_ru: Дочитка объекта данных - url: /fo_additional-loading.html - output: web - - title: Serializing and Deserializing Data Objects - title_ru: Сериализация и десериализация объектов данных - url: /fo_aggregating-function.html - output: web - - title: Asynchronous requests in ORM - title_ru: Асинхронные запросы в ORM - url: /fo_asynchronous_requests_in_orm.html - output: web - - title: Associating pictures with data classes - title_ru: Ассоциирование картинок с классами данных - url: /fo_class-image.html - output: web - - title: Code Examples - title_ru: Примеры кода - url: /fo_code-samples.html - output: web - - title: Example of custom names for structures in a database - title_ru: Пример пользовательских наименований для структур в БД - url: /fo_custom-naming-db-structures.html - output: web - - title: Dynamic Properties - title_ru: Динамические свойства объекта - url: /fo_dynamic-properties.html - output: web - - title: Flexberry ORM Libraries - title_ru: Библиотеки Flexberry ORM - url: /fo_flexberry-orm-libraries.html - output: web - - title: Custom control as LookUp - title_ru: Произвольный контрол в качестве лукапа - url: /fo_custom-lookup.html - output: web - - title: Features of determining the load of properties - title_ru: Особенности определения загруженности свойств - url: /fo_definition-loaded-properties.html - output: web - - title: ISpecialEmptyValue - title_ru: ISpecialEmptyValue - url: /fo_i-special-empty-value.html - output: web - - title: ICSSoft.STORMNET.Tools.XmlTools - title_ru: ICSSoft.STORMNET.Tools.XmlTools - url: /fo_ics-soft-stormnet-tools.html - output: web - - title: Interpreting the Boolean NULL Value - title_ru: Интерпретация булевского значения NULL - url: /fo_interpretation-boolean-null.html - output: web - - title: ICSSoft.STORMNET.KeyGen.KeyGuid class - title_ru: Класс ICSSoft.STORMNET.KeyGen.KeyGuid - url: /fo_key-guid.html - output: web - - title: Overloading of attributes, associations, methods - title_ru: Перегрузка атрибутов, ассоциаций, методов - url: /fo_overloading.html - output: web - - title: Reading objects belonging to different classes in one view - title_ru: Чтение принадлежащих различным классам объектов в одном представлении - url: /fo_reading-several-types-objects.html - output: web - - title: Flexberry LogService - title_ru: FFlexberry LogService - url: /fo_log-service-log4net.html - output: web - - title: Flexberry LogService Objects - title_ru: Flexberry LogService Objects - url: /fo_log-service-objects.html - output: web - - - title: API references - title_ru: Справочники по API - output: web, pdf - folderitems: - - title: Flexberry ORM - title_ru: Flexberry ORM - url: /fo_flexberry-orm-api.html - output: web, pdf - - title: Flexberry ORM ODataService - title_ru: Flexberry ORM ODataService - url: /fo_orm-odata-service-api.html - output: web, pdf +# This is your sidebar TOC. The sidebar code loops through sections here and provides the appropriate formatting. + + +entries: +- title: Sidebar + product: Flexberry ORM + version: 6.0.0 + folders: + + - title: О Flexberry ORM + output: web, pdf + folderitems: + - title: About + title_ru: О модуле + url: /fo_landing_page.html + output: web + + - title: Объектная модель + output: web, pdf + folderitems: + - title: DataObject + title_ru: Объекты данных + url: /fo_data-object.html + output: web + + - title: Status and loading state of the data object + title_ru: Статус и состояние загрузки объекта данных + url: /fo_object-status.html + output: web + + - title: How to load data object properties + title_ru: Порядок загрузки свойств объекта данных + url: /fo_order-loading-property.html + output: web + + - title: Access to the object's own attributes and attributes of related objects + title_ru: Доступ к собственным атрибутам объекта и атрибутам связанных объектов + url: /fo_own-object-attributes.html + output: web + + - title: Data Class Attributes + title_ru: Атрибуты классов данных + url: /fo_attributes-class-data.html + output: web + + - title: Storing object data in a relational database + title_ru: Хранение объектных данных в реляционной базе данных + url: /fo_storing-data-objects.html + output: web + + - title: Designing Data Objects + title_ru: Конструирование объектов данных + url: /fo_construction-data-objects.html + output: web + + - title: Data object as a class attribute + title_ru: Атрибут класса типа объекта данных + url: /fo_data-object-as-attribute-type.html + output: web + + - title: DataObjectCopy + title_ru: Копия объекта данных + url: /fo_data-object-copy.html + output: web + + - title: + title_ru: Первичные ключи объектов + url: /fo_primary-keys-objects.html + output: web + + - title: Structure of data object classes + title_ru: Структура классов объектов данных + url: /fo_data-object-structure.html + output: web + + - title: Children's associations and their properties + title_ru: Детейловые ассоциации и их свойства + url: /fo_detail-associations-properties.html + output: web + + - title: Obtaining metadata for objects + title_ru: Получение метаданных объектов + url: /fo_methods-class-information.html + output: web + + - title: Prototyping + title_ru: Прототипизация + url: /fo_data-object-prototype.html + output: + + - title: Context-sensitive data object cache + title_ru: Контекстно-зависимый кэш объектов данных + url: /fo_context-sensitive-cache.html + output: web + + - title: Converting the data object property type to a storage type + title_ru: Преобразование типа свойства объекта данных к типу хранилища + url: /fo_convert-type-property.html + output: web + + - title: Copying Data Objects + title_ru: Копирование объектов данных + url: /fo_copying-data-objects.html + output: web + + - title: Checking the object field in the set method + title_ru: Проверка поля объекта в методе set + url: /fo_check-object-set.html + output: web + + - title: Getting a Presentation Value for a Data Object + title_ru: Получение презентационного значения для объекта данных + url: /fo_get-presentation-value.html + output: web + + - title: Set the current object when the application starts + title_ru: Установка текущего объекта при запуске приложения + url: /fo_define-default-object.html + output: web + + - title: Setting the value of the field of the object to be created + title_ru: Задание значения поля создаваемого объекта + url: /fo_define-field-created.html + output: web + + - title: DisableInsertPropertyAttribute + title_ru: DisableInsertPropertyAttribute + url: /fo_disable-insert-property-attribute.html + output: web + + - title: Features of setting the default value + title_ru: Особенности задания значения по умолчанию + url: /fo_features-dafault-value.html + output: web + + - title: Functionality when working with arrays of child objects + title_ru: Функциональность при работе с массивами детейловых объектов + url: /fo_functionality-work-detail-array.html + output: web + + - title: Information.GetPropertyStorageName + title_ru: Information.GetPropertyStorageName + url: /fo_information-get-property-storage-name.html + output: web + + - title: Variants of opening an object for Readonly + title_ru: Варианты открытия объекта только на чтение + url: /fo_read-only-object.html + output: web + + - title: Updating related objects + title_ru: Обновление связанных объектов + url: /fo_update-related-objects.html + output: web + + - title: Displaying the form of masters and children on the interface + title_ru: Отображение на интерфейсе формы мастеров и детейлов + url: /fo_masters-details.html + output: web + + - title: Example of loading and changing an object + title_ru: Пример загрузки и изменения объекта + url: /fo_load-alter-objects.html + output: web + + - title: Example of loading an object graph + title_ru: Пример загрузки графа объектов + url: /fo_load-multiple-details-example.html + output: web + + - title: Example of object prototyping + title_ru: Пример прототипизации объекта + url: /fo_prototyping-example.html + output: web + + - title: Example of loading an object graph + title_ru: Пример загрузки графа объектов + url: /fo_load-multiple-details-example.html + output: web + + - title: An example of an action when saving an object + title_ru: Пример действий при сохранении объекта + url: /fo_actions-saving-object.html + output: web + + - title: Сервисы данных + output: web, pdf + folderitems: + - title: Data service + title_ru: Сервис данных + url: /fo_data-service.html + output: web + - title: Flexberry ORM Standard Data Services + title_ru: Стандартные сервисы данных Flexberry ORM + url: /fo_standard-data-services.html + output: web + - title: SQLDataService + title_ru: SQLDataService + url: /fo_sql-data-service.html + output: web + - title: Data service for working with PostgreSQL + title_ru: Cервис данных для работы с PostgreSQL + url: /fo_postgres-data-service.html + output: web + - title: MSSQLDataService + title_ru: MSSQLDataService + url: /fo_mssql-data-service.html + output: web + - title: Data service for working with Oracle Server + title_ru: Cервис данных для работы с Oracle Server + url: /fo_oracle-data-service.html + output: web + - title: Data service for MongoDB + title_ru: Cервис данных для работы с MongoDB + url: /fo_mongodb-data-service.html + output: web + - title: Data service for access to the Access DBMS + title_ru: Cервис данных для доступа к СУБД Access + url: /fo_odbc-access-ds.html + output: web + - title: ODBCMySqlDataService + title_ru: ODBCMySqlDataService + url: /fo_odbc-mysql-data-service.html + output: web + - title: DRDataService + title_ru: DRDataService + url: /fo_dr-data-service.html + output: web + - title: Data service for working with XML + title_ru: Cервис данных для работы с XML + url: /fo_xml-file-ds.html + output: web + - title: Implementing an arbitrary data service + title_ru: Реализация собственного сервиса данных + url: /fo_implement-custom-ds.html + output: web + - title: Designing a Data Service + title_ru: Конструирование сервиса данных + url: /fo_construction-ds.html + output: web + - title: Insensitivity to the register in the data service + title_ru: Нечувствительность к регистру в сервисе данных + url: /fo_insensitivity-register-ds.html + output: web + - title: Creating and saving data objects + title_ru: Создание и сохранение объектов данных + url: /fo_instantiate-persist-objects.html + output: web + - title: Interception of the formation of SQL-query to the database + title_ru: Перехват формирования SQL-запроса к БД + url: /fo_intercept-formation-sql-query.html + output: web + - title: Processing of the status and status of object loading + title_ru: Обработка статуса и состояния загрузки объекта + url: /fo_processing-status-condition-load.html + output: web + - title: Setting up read options + title_ru: Настройка параметров чтения + url: /fo_loading-customization-struct.html + output: web + - title: Updating objects with empty rows + title_ru: Обновление объектов с пустыми строками + url: /fo_updating-objects-empty-rows.html + output: web + - title: Support for multiple data warehouses in a single application + title_ru: Поддержка нескольких хранилищ данных в одном приложении + url: /fo_multibase.html + output: web + - title: Processing of one object + title_ru: Обработка одного объекта + url: /fo_processing-one-object.html + output: web + - title: Processing of a set of objects + title_ru: Обработка множества объектов + url: /fo_processing-multiple-objects.html + output: web + - title: Handling registers in object names + title_ru: Обработка регистров в именах объектов + url: /fo_processing-registers-names.html + output: web + - title: Portion reading + title_ru: Порционное чтение + url: /fo_reading-portion.html + output: web + - title: Using Postgres as a repository + title_ru: Использование СУБД Postgres в качестве хранилища + url: /fo_switching-storages.html + output: web + - title: Tools for Oracle Data Service + title_ru: Инструменты для работы Oracle Data Service + url: /fo_tools-oracle-ds.html + output: web + - title: SQL-queries in Flexberry + title_ru: SQL-запросы в Flexberry + url: /fo_sql-query.html + output: web + - title: Integration with Business Server + title_ru: Интеграция с бизнес-сервером + url: /fo_user-operations-dataservice.html + output: web + - title: Cropping rows with data service + title_ru: Обрезка строк сервисом данных + url: /fo_trimmed-string-storage.html + output: web + - title: Support for binary arrays with data service + title_ru: Поддержка бинарных массивов сервисом данных + url: /fo_binary-array-ds.html + output: web + + - title: Типы данных + output: web, pdf + folderitems: + - title: Data types in Flexberry ORM + title_ru: Типы данных во Flexberry ORM + url: /fo_flexberry-orm-types.html + output: web + - title: Notstored (computable) properties of the data object + title_ru: Нехранимые (вычислимые) свойства объекта данных + url: /fo_not-stored-attributes.html + output: web + - title: Example of non-stored object properties + title_ru: Пример нехранимых свойств объектов + url: /fo_nonstored-calculated-properties.html + output: web + - title: The use of not-stored classes + title_ru: Применение нехранимых классов + url: /fo_using-not-stored-classes.html + output: web + - title: Using data types in the application structure + title_ru: Использование типов данных в структуре приложения + url: /fo_type-usage.html + output: web + - title: The problem of the types used + title_ru: Проблема используемых типов + url: /fo_type-usage-problem.html + output: web + output: web + - title: Creating a Custom Data Type + title_ru: Создание пользовательского типа данных + url: /fo_creating-stereotypes-example.html + output: web + - title: An example of using custom types + title_ru: Пример использования собственных типов + url: /fo_using-custom-types-example.html + output: web + + - title: Язык запросов + output: web, pdf + folderitems: + - title: Comparison functions + title_ru: Функции сравнения + url: /fo_compare-functions.html + output: web + - title: ExternalLangDef + title_ru: ExternalLangDef + url: /fo_external-lang-def.html + output: web + - title: Restrictions on detail + title_ru: Ограничения на детейлы + url: /fo_exist-details.html + output: web + - title: Restrictions on the part of the date + title_ru: Ограничения на части даты + url: /fo_restriction-datetime.html + output: web + - title: FuncAND + title_ru: FuncAND + url: /fo_func-and.html + output: web + - title: FuncBETWEEN + title_ru: FuncBETWEEN + url: /fo_func-between.html + output: web + - title: FuncEQ + title_ru: FuncEQ + url: /fo_func-eq.html + output: web + - title: FuncIN + title_ru: FuncIN + url: /fo_func-in.html + output: web + - title: FuncIsNull + title_ru: FuncIsNull + url: /fo_func-is-null.html + output: web + - title: FuncLike + title_ru: FuncLike + url: /fo_func-like.html + output: web + - title: FuncNEQ + title_ru: FuncNEQ + url: /fo_func-neq.html + output: web + - title: FuncNOT + title_ru: FuncNOT + url: /fo_func-not.html + output: web + - title: FuncOR + title_ru: FuncOR + url: /fo_func-or.html + output: web + - title: FuncSQL + title_ru: FuncSQL + url: /fo_func-sql.html + output: web + - title: FuncToChar + title_ru: FuncToChar + url: /fo_func-to-char.html + output: web + - title: SQLWhereLanguageDef + title_ru: SQLWhereLanguageDef + url: /fo_function-list.html + output: web + - title: FunctionBuilder + title_ru: FunctionBuilder + url: /fo_function-builder.html + output: web + - title: FunctionBuilder examples + title_ru: FunctionBuilder примеры + url: /fo_function-builder-examples.html + output: web + - title: Function of implication + title_ru: Функция импликации + url: /fo_function-implication.html + output: web + - title: Convert constraint function to linq-constraint + title_ru: Преобразование функции ограничения в linq-ограничение + url: /fo_lcs-to-linq.html + output: web + - title: Restriction on children using aggregator properties + title_ru: Ограничение на детейлы с использованием свойств агрегатора + url: /fo_limit-details.html + output: web + - title: Serializing LimitFunction + title_ru: Сериализация LimitFunction + url: /fo_limit-function-serialization.html + output: web + - title: Limit Function + title_ru: Функции ограничения + url: /fo_limit-function.html + output: web + - title: Filtering and data sampling + title_ru: Фильтрация и ограничение выборки данных + url: /fo_limitation.html + output: web + - title: LINQPad + title_ru: LINQPad + url: /fo_linq-pad.html + output: web + - title: LINQProvider + title_ru: LINQProvider + url: /fo_linq-provider.html + output: web + - title: Features of LinqProvider + title_ru: Возможности LinqProvider + url: /fo_linq-provider-faetures.html + output: web + - title: Reading objects with a constraint + title_ru: Чтение объектов с наложенным ограничением + url: /fo_load-by-limit.html + output: web + - title: Description of variables when constructing constraint functions + title_ru: Описание переменных при построении функций ограничения + url: /fo_variable-def.html + output: web + - title: An example of imposing restrictions on the loading of objects + title_ru: Пример наложения ограничений на загрузку объектов + url: /fo_load-limitation-example.html + output: web + - title: Psedodetails in LinqProvider + title_ru: Псевдодетейлы в LinqProvider + url: /fo_psedodetails-linq-provider.html + output: web + - title: Creating your own functions when using LanguageDef + title_ru: Создание собственных функций при использовании LanguageDef + url: /fo_using-languagedef.html + output: web + + - title: Представления + output: web, pdf + folderitems: + - title: Operations with views + title_ru: Операции с представлениями + url: /fo_view-operations.html + output: web + + - title: Adaptive representations for details + title_ru: Адаптивные представления для детейлов + url: /fo_adaptive-views-details.html + output: web + + - title: ViewPropertyAppender + title_ru: ViewPropertyAppender + url: /fo_view-property-appender.html + output: web + + - title: Static properties for accessing class representations + title_ru: Статические свойства для доступа к представлениям класса + url: /fo_static-view-accessors.html + output: web + + - title: An example of working with views + title_ru: Пример работы с представлениями + url: /fo_work-with-views-example.html + output: web + + - title: An example of advanced work with views + title_ru: Пример продвинутой работы с представлениями + url: /fo_advanced-working-with-views.html + output: web + + - title: Бизнес-серверы + output: web, pdf + folderitems: + - title: Business servers + title_ru: Бизнес-сервер + url: /fo_business-server.html + output: web + - title: Business logic + title_ru: Бизнес-логика + url: /fo_business-logic.html + output: web + - title: Order of calls of business servers + title_ru: Порядок вызовов бизнес-серверов + url: /fo_order-calls-bs.html + output: web + - title: Checking the validity of changes to object data in the business server + title_ru: Проверка валидности изменений данных объекта в бизнес-сервере + url: /fo_change-data-check.html + output: web + - title: Updating multiple objects with a single transaction + title_ru: Обновление нескольких объектов одной транзакцией + url: /fo_bs-transact.html + output: web + - title: Checking the uniqueness of the entered data in the business server + title_ru: Проверка уникальности введенных данных в бизнес-сервере + url: /fo_unique-data-check.html + output: web + - title: Cascading deletion of objects + title_ru: Каскадное удаление объектов + url: /fo_cascade-delete.html + output: web + - title: IReferencesCascadeDelete + title_ru: IReferencesCascadeDelete + url: /fo_i-references-cascade-delete.html + output: web + - title: IReferencesNullDelete + title_ru: IReferencesNullDelete + url: /fo_i-references-null-delete.html + output: web + - title: Cancellation of deletion of the used value from the directory + title_ru: Отмена удаления используемого значения из справочника + url: /fo_delete-cancel.html + output: web + - title: Example of using a business server + title_ru: Пример использования бизнес-сервера + url: /fo_bs-example.html + output: web + + - title: Модуль для Flexberry Designer + output: web, pdf + folderitems: + - title: Generic methods in Flexberry Designer + title_ru: Генерик-методы в Flexberry Designer + url: /fo_generic-methods.html + output: web + - title: Create a class diagram for the database + title_ru: Создание диаграммы классов по базе данных + url: /fo_reverse-data-base.html + output: web + - title: Generate documentation on charts + title_ru: Генерация документации по диаграммам + url: /fo_doc-gen.html + output: web + - title: Plugin for generating XSD schema + title_ru: XMLSchemaGenerator Features + url: /fo_xml-schema-generator.html + output: web + - title: Generating application code using uml models + title_ru: Генерации кода приложения по uml-моделям + url: /fo_orm-case-plugin.html + output: web + - title: Functions of creating a backup and history of changes + title_ru: Функции создания бэкапа и истории изменений + url: /fo_history-plugin.html + output: web + - title: Search function + title_ru: Функция поиска + url: /fo_intelli-search-plugin.html + output: web + - title: Location of assemblies after code generation + title_ru: Расположение сборок после генерации кода + url: /fo_location-assembly.html + output: web + - title: Move or copy function + title_ru: Функция перемещения или копирования + url: /fo_move-case-plugin.html + output: web + - title: Brackets of the programmer + title_ru: Скобки программиста + url: /fo_programmer-brackets.html + output: web + + - title: OData + output: web, pdf + folderitems: + - title: ODataService + title_ru: ODataService + url: /fo_orm-odata-service.html + output: web + + - title: Configuring ODataService with several types of data services + title_ru: Настройка ODataService с несколькими типами сервисов данных + url: /fo_multiple-data-services-in-odata.html + output: web + + - title: Configuring entity type names in OData metadata + title_ru: Настройка имен типов сущностей в метаданных OData + url: /fo_metadata-for-client.html + output: web + + - title: OData-controllers debugging + title_ru: Отладка OData-контроллеров + url: /fo_orm-odata-debug.html + output: web + + - title: Монитор SQL-запросов + output: web, pdf + folderitems: + - title: Business task monitor + title_ru: Монитор задач + url: /fo_business-task-monitor.html + output: web + - title: Service for writing SQL-scripts for data changes + title_ru: Сервис записи SQL-скриптов изменения данных + url: /fo_changes-sql-bt-monitor.html + output: web + - title: Creating and Connecting a Task Monitor + title_ru: Создание и подключение монитора задач + url: /fo_creating-connection-bt-monitor.html + output: web + + - title: Сервис текущего пользователя + output: web, pdf + folderitems: + - title: Current User Service + title_ru: Сервис текущего пользователя + url: /fo_current-user-service.html + output: web + + - title: Dependency Injection + output: web, pdf + folderitems: + - title: Default data service + title_ru: Сервис данных по умолчанию + url: /fo_ds-provider.html + output: web + - title: Flexberry UnityFactory + title_ru: Flexberry UnityFactory + url: /fo_unity-factory.html + output: web + + - title: Сервис блокировок + output: web, pdf + folderitems: + - title: Locking service + title_ru: Сервис блокировок + url: /fo_lock-service.html + output: web + - title: Data object locking + title_ru: Блокирование объекта данных + url: /fo_blocking-object-data.html + output: web + + - title: Дополнительные возможности + output: web, pdf + folderitems: + - title: Additional loading data object + title_ru: Дочитка объекта данных + url: /fo_additional-loading.html + output: web + - title: Serializing and Deserializing Data Objects + title_ru: Сериализация и десериализация объектов данных + url: /fo_aggregating-function.html + output: web + - title: Asynchronous requests in ORM + title_ru: Асинхронные запросы в ORM + url: /fo_asynchronous_requests_in_orm.html + output: web + - title: Associating pictures with data classes + title_ru: Ассоциирование картинок с классами данных + url: /fo_class-image.html + output: web + - title: Code Examples + title_ru: Примеры кода + url: /fo_code-samples.html + output: web + - title: Example of custom names for structures in a database + title_ru: Пример пользовательских наименований для структур в БД + url: /fo_custom-naming-db-structures.html + output: web + - title: Dynamic Properties + title_ru: Динамические свойства объекта + url: /fo_dynamic-properties.html + output: web + - title: Flexberry ORM Libraries + title_ru: Библиотеки Flexberry ORM + url: /fo_flexberry-orm-libraries.html + output: web + - title: Custom control as LookUp + title_ru: Произвольный контрол в качестве лукапа + url: /fo_custom-lookup.html + output: web + - title: Features of determining the load of properties + title_ru: Особенности определения загруженности свойств + url: /fo_definition-loaded-properties.html + output: web + - title: ISpecialEmptyValue + title_ru: ISpecialEmptyValue + url: /fo_i-special-empty-value.html + output: web + - title: ICSSoft.STORMNET.Tools.XmlTools + title_ru: ICSSoft.STORMNET.Tools.XmlTools + url: /fo_ics-soft-stormnet-tools.html + output: web + - title: Interpreting the Boolean NULL Value + title_ru: Интерпретация булевского значения NULL + url: /fo_interpretation-boolean-null.html + output: web + - title: ICSSoft.STORMNET.KeyGen.KeyGuid class + title_ru: Класс ICSSoft.STORMNET.KeyGen.KeyGuid + url: /fo_key-guid.html + output: web + - title: Overloading of attributes, associations, methods + title_ru: Перегрузка атрибутов, ассоциаций, методов + url: /fo_overloading.html + output: web + - title: Reading objects belonging to different classes in one view + title_ru: Чтение принадлежащих различным классам объектов в одном представлении + url: /fo_reading-several-types-objects.html + output: web + - title: Flexberry LogService + title_ru: FFlexberry LogService + url: /fo_log-service-log4net.html + output: web + - title: Flexberry LogService Objects + title_ru: Flexberry LogService Objects + url: /fo_log-service-objects.html + output: web + + - title: API references + title_ru: Справочники по API + output: web, pdf + folderitems: + - title: Flexberry ORM + title_ru: Flexberry ORM + url: /fo_flexberry-orm-api.html + output: web, pdf + - title: Flexberry ORM ODataService + title_ru: Flexberry ORM ODataService + url: /fo_orm-odata-service-api.html + output: web, pdf diff --git a/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.en.md b/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.en.md index a00f2d4e8..c4ab9904c 100644 --- a/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.en.md +++ b/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.en.md @@ -35,10 +35,10 @@ protected override void PreApplyToControls() { var заказ = ctrlЗаказ.SelectedMasterPK; ctrlЗаказ.MasterViewName = Заказ.Views.ЗаказL.Name; - + var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(СтрокаЗаказа), СтрокаЗаказа.Views.СтрокаЗаказаE); lcs.LimitFunction = FunctionBuilder.BuildEquals<СтрокаЗаказа>(x => x.Заказ, заказ); - var строкиЗаказа = DataServiceProvider.DataService.LoadObjects(lcs); + var строкиЗаказа = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead foreach (var s in строкиЗаказа) { diff --git a/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.ru.md b/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.ru.md index f91ed1e63..a3dc81621 100644 --- a/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.ru.md +++ b/pages/guides/practical-guides/flexberry-asp-net/gpg_auto-get-data-from-lookup.ru.md @@ -33,10 +33,10 @@ protected override void PreApplyToControls() { var заказ = ctrlЗаказ.SelectedMasterPK; ctrlЗаказ.MasterViewName = Заказ.Views.ЗаказL.Name; - + var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(СтрокаЗаказа), СтрокаЗаказа.Views.СтрокаЗаказаE); lcs.LimitFunction = FunctionBuilder.BuildEquals<СтрокаЗаказа>(x => x.Заказ, заказ); - var строкиЗаказа = DataServiceProvider.DataService.LoadObjects(lcs); + var строкиЗаказа = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей foreach (var s in строкиЗаказа) { @@ -47,7 +47,7 @@ protected override void PreApplyToControls() } ``` -В данном методе выполняется проверка, произошел ли `PostBack`, после чего с помощью сервиса данных подгружаются детейлы для класса `Заказ` (в подгружаемом представлении есть детейлы), так как по умолчанию они не загружаются. +В данном методе выполняется проверка, произошел ли `PostBack`, после чего с помощью сервиса данных подгружаются детейлы для класса `Заказ` (в подгружаемом представлении есть детейлы), так как по умолчанию они не загружаются. После загрузки в цикле формируются и заполняются детейлы. Не забываем изменить значение параметра `flexberryautogenerated` на `false`, чтобы форма не потерять изменения при перегенерации. @@ -67,4 +67,4 @@ protected override void PreApplyToControls() ## Перейти * [Обработка исключений](gpg_set-exception.html) -* [Работа с бизнес-сервером](gpg_business-server.html) +* [Работа с бизнес-сервером](gpg_business-server.html) diff --git a/pages/guides/practical-guides/flexberry-asp-net/gpg_business-server.en.md b/pages/guides/practical-guides/flexberry-asp-net/gpg_business-server.en.md index 5b6629f22..fba804fa7 100644 --- a/pages/guides/practical-guides/flexberry-asp-net/gpg_business-server.en.md +++ b/pages/guides/practical-guides/flexberry-asp-net/gpg_business-server.en.md @@ -32,14 +32,14 @@ Such as, in order to check the availability of goods in stock at the time the or 5.Then register in parentheses programmer the following lines (to select the options use a combination of `Ctrl` Space): ```csharp -// *** Start programmer edit section *** (Using statements) +// *** Start programmer edit section *** (Using statements) using System.Collections; using ICSSoft.STORMNET; using ICSSoft.STORMNET.FunctionalLanguage; using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; -// *** End programmer edit section *** (Using statements) +// *** End programmer edit section *** (Using statements) ``` 6.Later in the code business servers to handle all of the following: @@ -47,17 +47,17 @@ using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; ```csharp public virtual ICSSoft.STORMNET.DataObject[] OnUpdateЗаказ(АСУ_Склад.Заказ UpdatedObject) { - // *** Start programmer edit section *** (OnUpdateЗаказ) + // *** Start programmer edit section *** (OnUpdateЗаказ) - // Define the array that will return for updates. + // Define the array that will return for updates. DataObject[] ret = new DataObject[0]; - // Check that the received object is exactly what we need (created or modified and the status is set to Paid). - if ((UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Created || UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Altered) && Array.IndexOf(UpdatedObject.GetAlteredPropertyNames(), Status) >= 0 && UpdatedObject.Статус == СостояниеЗаказа.Оплаченный) - { - // Build the restriction and subtract all the objects in Tavarnelle that suit us. - Заказ заказ = UpdatedObject; - ICSSoft.STORMNET.FunctionalLanguage.Function lf = null; + // Check that the received object is exactly what we need (created or modified and the status is set to Paid). + if ((UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Created || UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Altered) && Array.IndexOf(UpdatedObject.GetAlteredPropertyNames(), Status) >= 0 && UpdatedObject.Статус == СостояниеЗаказа.Оплаченный) + { + // Build the restriction and subtract all the objects in Tavarnelle that suit us. + Заказ заказ = UpdatedObject; + ICSSoft.STORMNET.FunctionalLanguage.Function lf = null; for (int i = 0; i < заказ.СтрокаЗаказа.Count; i++) { @@ -78,9 +78,9 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateЗаказ(АСУ_Скла ICSSoft.STORMNET.Business.LoadingCustomizationStruct lcs = ICSSoft.STORMNET.Business.LoadingCustomizationStruct.GetSimpleStruct(typeof(ТоварНаСкладе),"Tavernacle"); lcs.LimitFunction = lf; - ICSSoft.STORMNET.DataObject[] objs = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcs); + ICSSoft.STORMNET.DataObject[] objs = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead - // Place the read objects in a sorted list for easy access later on. + // Place the read objects in a sorted list for easy access later on. System.Collections.SortedList sl = new System.Collections.SortedList(); for (int i = 0; i < objs.Length; i++) @@ -97,11 +97,11 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateЗаказ(АСУ_Скла } } - // Define the string for the error message. + // Define the string for the error message. string errStr = string.Empty; ArrayList retObjs = new ArrayList(); - // Check the availability of goods in warehouses, if not enough, then give error message if missing, then subtract the number. + // Check the availability of goods in warehouses, if not enough, then give error message if missing, then subtract the number. for (int i = 0; i < заказ.СтрокаЗаказа.Count; i++) { if (sl.ContainsKey(заказ.СтрокаЗаказа[i].Товар.__PrimaryKey)) @@ -149,18 +149,18 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateЗаказ(АСУ_Скла } } - // In case something is not enough, we inform the user. + // In case something is not enough, we inform the user. if (errStr != string.Empty) { throw new Exception(errStr); } - // If everything is fine, then return an array of objects that need to be updated. + // If everything is fine, then return an array of objects that need to be updated. ret = new DataObject[retObjs.Count]; retObjs.CopyTo(ret, 0); } return ret; - // *** End programmer edit section *** (OnUpdateЗаказ) + // *** End programmer edit section *** (OnUpdateЗаказ) } ``` diff --git a/pages/guides/practical-guides/flexberry-ember/gpg_server-logic-implementation.md b/pages/guides/practical-guides/flexberry-ember/gpg_server-logic-implementation.md index ea49d7f7f..9e6d7a538 100644 --- a/pages/guides/practical-guides/flexberry-ember/gpg_server-logic-implementation.md +++ b/pages/guides/practical-guides/flexberry-ember/gpg_server-logic-implementation.md @@ -149,15 +149,15 @@ public virtual DataObject[] OnUpdateOrder(IIS.Shop.Order UpdatedObject) ## Реализация основной части логики -Теперь, когда для логики перевода Заказа в статус "Оплаченный" создан отдельный метод, можно реализовывать основной функционал. Аналогичная логика реализована в разделе "[Работа с бизнес-сервером](gpg_business-server.html)" (Практическое руководство по веб-разработке на Flexberry ASP.NET). +Теперь, когда для логики перевода Заказа в статус "Оплаченный" создан отдельный метод, можно реализовывать основной функционал. Аналогичная логика реализована в разделе "[Работа с бизнес-сервером](gpg_business-server.html)" (Практическое руководство по веб-разработке на Flexberry ASP.NET). {% include important.html content="Всю дальнейшую логику мы будем проверять на примере Заказа 2." %} -В числе вносимых в код **изменений** (по сравнению с кодом, который представлен по ссылке выше) мы добавим возможность сортировки вычитываемых товарных позиций со складов по номеру склада. Для этого нужно обновить класс StoreProduct во **Flexberry Designer**: необходимо добавить невидимый атрибут **Storehouse.Number** в представление **StoreProductE**. +В числе вносимых в код **изменений** (по сравнению с кодом, который представлен по ссылке выше) мы добавим возможность сортировки вычитываемых товарных позиций со складов по номеру склада. Для этого нужно обновить класс StoreProduct во **Flexberry Designer**: необходимо добавить невидимый атрибут **Storehouse.Number** в представление **StoreProductE**. ![Добавление свойства Storehouse.Number в представление StoreProductE](/images/pages/guides/flexberry-ember/7-2-server-logic-implementation/7-2-7.png) -После этого следует **обновить проект с объектами данных на бэкенде** (выполнить перегенерацию соответствующего проекта). Теперь мы легко получим доступ из объекта конкретной позиции товара на складе к характеристике самого склада, в частности к его номеру. Условимся, что товары будут списываться всегда со складов в порядке увеличения порядкового номера склада. +После этого следует **обновить проект с объектами данных на бэкенде** (выполнить перегенерацию соответствующего проекта). Теперь мы легко получим доступ из объекта конкретной позиции товара на складе к характеристике самого склада, в частности к его номеру. Условимся, что товары будут списываться всегда со складов в порядке увеличения порядкового номера склада. Реализуем теперь основную логику. Прежде всего, нужно **вычитать список всех требуемых товарных позиций со всех складов**: @@ -189,7 +189,7 @@ private static DataObject[] changeOrderStatusPaid(IIS.Shop.Order UpdatedObject) sortColumns.Add(new ColumnsSortDef("Storehouse.Number", SortOrder.Asc)); lcs.ColumnsSort = sortColumns.ToArray(); - DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); + DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей return ret; // БРЕЙКПОИНТ } @@ -210,7 +210,7 @@ private static DataObject[] changeOrderStatusPaid(IIS.Shop.Order UpdatedObject) { ... - DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); + DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей // Разместим вычитанные объекты в отсортированном списке для удобного доступа в дальнейшем. SortedList sl = new SortedList(); @@ -295,7 +295,7 @@ private static DataObject[] changeOrderStatusPaid(IIS.Shop.Order UpdatedObject) } } - // Определим строчку для сообщения об ошибке. + // Определим строчку для сообщения об ошибке. string errStr = string.Empty; ArrayList retObjs = new ArrayList(); @@ -390,7 +390,7 @@ private static DataObject[] changeOrderStatusPaid(IIS.Shop.Order UpdatedObject) ## Самостоятельная работа Вы можете выполнить следующие доработки в приложении самостоятельно для более полной реализации функционала приложения: -1. при изменении статуса Заказа на "Оплаченный" создавать на стороне сервера Накладную, к которой был бы уже прикреплен заказ, установлены статус "Новый" и выставлена текущая дата создания. +1. при изменении статуса Заказа на "Оплаченный" создавать на стороне сервера Накладную, к которой был бы уже прикреплен заказ, установлены статус "Новый" и выставлена текущая дата создания. ## Перейти diff --git a/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.en.md b/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.en.md index 8b875d411..2c0d44697 100644 --- a/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.en.md +++ b/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.en.md @@ -1,45 +1,45 @@ ---- -title: Detaylari in the advanced editor limitations -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET -toc: true -permalink: en/fa_details-limit-editor.html -lang: en -autotranslated: true -hash: 77276ff64e83be9dd9c455c5831ca8c1b04f80dbc2032d9dc01002f85401b041 ---- +--- +title: Detaylari in the advanced editor limitations +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET +toc: true +permalink: en/fa_details-limit-editor.html +lang: en +autotranslated: true +hash: 77276ff64e83be9dd9c455c5831ca8c1b04f80dbc2032d9dc01002f85401b041 +--- -## Work with detaylari in the advanced editor, limitations in the web +## Work with detaylari in the advanced editor, limitations in the web -You should pay attention (especially associated with the [conversion functions restrictions in linq-expression](fo_lcs-to-linq.html)): +You should pay attention (especially associated with the [conversion functions restrictions in linq-expression](fo_lcs-to-linq.html)): -* When you set the constraint of universality on detaily (in lcs is [ExistExact](fo_exist-details.html)) in the view of detail should be included a reference to the aggregator. -* When setting limits on detaily using the advanced editor restrictions to the view of the aggregator may want to include a link to detali. +* When you set the constraint of universality on detaily (in lcs is [ExistExact](fo_exist-details.html)) in the view of detail should be included a reference to the aggregator. +* When setting limits on detaily using the advanced editor restrictions to the view of the aggregator may want to include a link to detali. -## Work with pseudocatalase in the advanced editor, limitations in the web +## Work with pseudocatalase in the advanced editor, limitations in the web -For pseudocatalase in the expanded constraint editor](fa_advanced-limit-editor.html) you must do the following: -* When [specify display order of the properties in the advanced editor, limitations](fa_prop-order-limit-editor.html) add interest pseudometal (problem of specifying limits on pseudometal described [here](fo_linq-provider.html)) -* In the constraint editor, you can open stored in the lcs limits, or designing a new one. +For pseudocatalase in the expanded constraint editor](fa_advanced-limit-editor.html) you must do the following: +* When [specify display order of the properties in the advanced editor, limitations](fa_prop-order-limit-editor.html) add interest pseudometal (problem of specifying limits on pseudometal described [here](fo_linq-provider.html)) +* In the constraint editor, you can open stored in the lcs limits, or designing a new one. -![](/images/pages/products/flexberry-aspnet/ogranicheniye/le-pseudo-detail.png) +![](/images/pages/products/flexberry-aspnet/ogranicheniye/le-pseudo-detail.png) -## Dynamic view of datalow +## Dynamic view of datalow -For the work of datalow in the expanded constraint editor in the web](fa_advanced-limit-editor.html) in the application of restrictions on [WOLV](fa_web-object-list-view.html), you may need: -* [Ask detaily to view](fa_prop-order-limit-editor.html) if they are not already there. -* Ask [property AutoAddUsedInLimitationProperties](fa_prop-order-limit-editor.html) that the view formed dynamically. -* To determine the mechanism of formation of dynamic representations for detailov through the interface ICSSoft.STORMNET.Windows.Forms.IViewGenerator (located in the Assembly ExternalLangDef). For example, in the version after 14.01.2015 in config add the following line: +For the work of datalow in the expanded constraint editor in the web](fa_advanced-limit-editor.html) in the application of restrictions on [WOLV](fa_web-object-list-view.html), you may need: +* [Ask detaily to view](fa_prop-order-limit-editor.html) if they are not already there. +* Ask [property AutoAddUsedInLimitationProperties](fa_prop-order-limit-editor.html) that the view formed dynamically. +* To determine the mechanism of formation of dynamic representations for detailov through the interface ICSSoft.STORMNET.Windows.Forms.IViewGenerator (located in the Assembly ICSSoft.STORMNET.Business.ExternalLangDef). For example, in the version after 14.01.2015 in config add the following line: ```xml - ... + ... ... - + -``` +``` diff --git a/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.ru.md b/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.ru.md index 294061dc3..511846deb 100644 --- a/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.ru.md +++ b/pages/products/flexberry-aspnet/controls/limit-editor/fa_details-limit-editor.ru.md @@ -17,7 +17,7 @@ lang: ru ## Работа с псевдодетейлами в расширенном редакторе ограничений в web Для работы с псевдодетейлами в [расширенном редакторе ограничений](fa_advanced-limit-editor.html) необходимо сделать следующее: -* При [задании порядка отображения свойств в расширенном редакторе ограничений](fa_prop-order-limit-editor.html) добавить интересующие псевдодетейлы (постановка задачи задания ограничений на псевдодетейлы описана [здесь](fo_linq-provider.html)) +* При [задании порядка отображения свойств в расширенном редакторе ограничений](fa_prop-order-limit-editor.html) добавить интересующие псевдодетейлы (постановка задачи задания ограничений на псевдодетейлы описана [здесь](fo_linq-provider.html)) * В редакторе ограничений можно открывать сохранённые в виде lcs ограничения, либо конструировать новые. ![](/images/pages/products/flexberry-aspnet/ogranicheniye/le-pseudo-detail.png) @@ -27,14 +27,14 @@ lang: ru Для работы детейлов в [расширенном редакторе ограничений в web](fa_advanced-limit-editor.html) при применении ограничения на [WOLV](fa_web-object-list-view.html), может потребоваться: * [Задать детейлы в представление](fa_prop-order-limit-editor.html), если их ещё там нет. * Задать [свойство AutoAddUsedInLimitationProperties](fa_prop-order-limit-editor.html), чтобы представление формировалось динамически. -* Определить механизм формирования динамического представления для детейлов через интерфейс ICSSoft.STORMNET.Windows.Forms.IViewGenerator (расположен в сборке ExternalLangDef). Например, в версии после 14.01.2015 можно в конфиг добавить следующую строчку: +* Определить механизм формирования динамического представления для детейлов через интерфейс ICSSoft.STORMNET.Windows.Forms.IViewGenerator (расположен в сборке ICSSoft.STORMNET.Business.ExternalLangDef). Например, в версии после 14.01.2015 можно в конфиг добавить следующую строчку: ```xml - ... + ... ... - + ``` diff --git a/pages/products/flexberry-aspnet/controls/limit-editor/fa_limit-function-parameters.en.md b/pages/products/flexberry-aspnet/controls/limit-editor/fa_limit-function-parameters.en.md index c33eb1e06..3b233b4b1 100644 --- a/pages/products/flexberry-aspnet/controls/limit-editor/fa_limit-function-parameters.en.md +++ b/pages/products/flexberry-aspnet/controls/limit-editor/fa_limit-function-parameters.en.md @@ -24,7 +24,7 @@ public static Function SubstituteParameters(Function function, IDictionary /// Подставить конкретные значения вместо параметров функции. /// /// Сама функция, в которой будут заменять параметры. -/// Справочник значений параметров (название параметра - значение). +/// Справочник значений параметров (название параметра - значение). /// Функция, в которой все параметры заменены на соответствующие значения. public static Function SubstituteParameters(Function function, IDictionary paramValues) -``` +``` ## Пример ```csharp -ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; - +ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). + // Ограничивающая функция. ICSSoft.STORMNET.FunctionalLanguage.Function limitFunction = externalLangDef.GetFunction( externalLangDef.funcEQ, - new ParameterDef("Дата", externalLangDef.DateTimeType, false, "")); + new ParameterDef("Дата", externalLangDef.DateTimeType, false, "")); // Функция с подставленным значением параметра. limitFunction = AdvLimitUtils.SubstituteParameters( diff --git a/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.en.md b/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.en.md index f64986a7f..675f4149b 100644 --- a/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.en.md +++ b/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.en.md @@ -33,7 +33,7 @@ Expression is Empty/is nonempty can be applied to: If you have a class with a property `Кредит` `СуммаКредита` real type, the translation in [LINQProvider|LinqProvider) it will be presented as follows: ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Кредит> limit = ds.Query<Кредит>(Кредит.Views.C__КредитE).Where(x => (x.СуммаКредита as object) == null); ``` diff --git a/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.ru.md b/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.ru.md index 266a7b02b..fe8cf41b4 100644 --- a/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.ru.md +++ b/pages/products/flexberry-aspnet/controls/limit-editor/fa_web-limit-editor-null.ru.md @@ -13,7 +13,7 @@ lang: ru ![](/images/pages/products/flexberry-aspnet/controls/limit-editor/web-limit-editor-null.png) -`Пусто` соответствует функции [funcIsNull](fo_func-is-null.html) из [SQLWhereLanguageDef](fo_function-list.html). +`Пусто` соответствует функции [funcIsNull](fo_func-is-null.html) из [SQLWhereLanguageDef](fo_function-list.html). `Непусто` соответствует функции funcNotIsNull из [ExternalLangDef](fo_external-lang-def.html). @@ -31,7 +31,7 @@ lang: ru Если имеется класс `Кредит` со свойством `СуммаКредита` вещественного типа, то при переводе в [LINQProvider|LinqProvider) оно будет представляться следующим образом: ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей IQueryable<Кредит> limit = ds.Query<Кредит>(Кредит.Views.C__КредитE).Where(x => (x.СуммаКредита as object) == null); ``` diff --git a/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.en.md b/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.en.md index d0bc784fe..ba90f2e96 100644 --- a/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.en.md +++ b/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.en.md @@ -1,76 +1,76 @@ ---- -title: Imposing restrictions on the LookUp in the Web -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET Restrictions -toc: true -permalink: en/fa_lookup-limit-web.html -lang: en -autotranslated: true -hash: 04768470055c851384a6bede1855f0d85f9eb0043b7ff05faff98727e5941a8c ---- +--- +title: Imposing restrictions on the LookUp in the Web +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET Restrictions +toc: true +permalink: en/fa_lookup-limit-web.html +lang: en +autotranslated: true +hash: 04768470055c851384a6bede1855f0d85f9eb0043b7ff05faff98727e5941a8c +--- -By default, when opening forms in the [LookUp](fa_lookup-overview.html) displays the entire list of objects from which to select. However, often the situation arises when a complete list is impossible. +By default, when opening forms in the [LookUp](fa_lookup-overview.html) displays the entire list of objects from which to select. However, often the situation arises when a complete list is impossible. -Therefore, the question arises: how to limit the output if you picked up on LookUp? +Therefore, the question arises: how to limit the output if you picked up on LookUp? -## Example 1 +## Example 1 -Given the following diagram. +Given the following diagram. -![](/images/pages/products/flexberry-aspnet/controls/lookup/filter-ex-diagram.png) +![](/images/pages/products/flexberry-aspnet/controls/lookup/filter-ex-diagram.png) -When you create a new object of type `Кредит` need to choose `Клиента` to which the loan. For example, that a restriction to lend only to persons resident in the city of Perm (i.e. if `Прописка` Client contains a "Perm"). +When you create a new object of type `Кредит` need to choose `Клиента` to which the loan. For example, that a restriction to lend only to persons resident in the city of Perm (i.e. if `Прописка` Client contains a "Perm"). -To build a restriction using [LINQProvider](fo_linq-provider.html): +To build a restriction using [LINQProvider](fo_linq-provider.html): ```csharp -var ds = (SQLDataService) DataServiceProvider.DataService; +var ds = (SQLDataService) DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Клиент> limit = ds.Query<Клиент>(Клиент.Views.КлиентL).Where(klient => klient.Прописка.Contains("Perm")); -``` +``` -Then get a restraining function using the class `LinqToLcs`: +Then get a restraining function using the class `LinqToLcs`: ```csharp Function onlyPermKlients = LinqToLcs.GetLcs(limit.Expression, Клиент.Views.КлиентL).LimitFunction; -``` +``` -Restrict LookUp field by selecting `LimitFunction`: +Restrict LookUp field by selecting `LimitFunction`: ```csharp ctrlКлиент.LimitFunction = onlyPermKlients; -``` +``` -As a result, when you open lookup-shape Clients this page displays only Clients that have the word "Perm" in the field "Registration". +As a result, when you open lookup-shape Clients this page displays only Clients that have the word "Perm" in the field "Registration". -## Example 2 +## Example 2 -The more difficult task: let the residence, is in a class thus, it is necessary to impose restrictions on master: +The more difficult task: let the residence, is in a class thus, it is necessary to impose restrictions on master: -![](/images/pages/products/flexberry-aspnet/controls/lookup/kredit-diagramm.png) +![](/images/pages/products/flexberry-aspnet/controls/lookup/kredit-diagramm.png) -Additionally, you want to show only working `КредитныхИнспекторов`. +Additionally, you want to show only working `КредитныхИнспекторов`. -1.Build constraints by filling a LINQ provider: +1.Build constraints by filling a LINQ provider: ```csharp -var ds = (SQLDataService) DataServiceProvider.DataService; +var ds = (SQLDataService) DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Клиент> limit1 = ds.Query<Клиент>(Клиент.Views.КлиентL).Where(klient => klient.Прописка.Город == "Perm"); IQueryable<КредитныйИнспектор> limit2 = ds.Query<КредитныйИнспектор>(КредитныйИнспектор.Views.КредитныйИнспекторL).Where(insp => insp.Работает); -``` +``` -2.To restrictive feature: +2.To restrictive feature: ```csharp Function onlyPermKlients = LinqToLcs.GetLcs(limit1.Expression, Клиент.Views.КлиентL).LimitFunction; Function onlyWorkingInspektors = LinqToLcs.GetLcs(limit2.Expression, КредитныйИнспектор.Views.КредитныйИнспекторL).LimitFunction; -``` +``` -3.The limitations on LookUpы for Customers and Inspectors: +3.The limitations on LookUpы for Customers and Inspectors: ```csharp ctrlКлиент.LimitFunction = onlyPermKlients; ctrlКредитныйИнспектор.LimitFunction = onlyWorkingInspektors; -``` +``` diff --git a/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.ru.md b/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.ru.md index 163af82c6..bea97fdb2 100644 --- a/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.ru.md +++ b/pages/products/flexberry-aspnet/controls/lookup/fa_lookup-limit-web.ru.md @@ -22,7 +22,7 @@ lang: ru Построить ограничение, используя [LINQProvider](fo_linq-provider.html): ```csharp -var ds = (SQLDataService) DataServiceProvider.DataService; +var ds = (SQLDataService) DataServiceProvider.DataService;// DataServiceProvider устарел; вместо него используйте внедрение зависимостей IQueryable<Клиент> limit = ds.Query<Клиент>(Клиент.Views.КлиентL).Where(klient => klient.Прописка.Contains("Пермь")); ``` @@ -48,10 +48,10 @@ ctrlКлиент.LimitFunction = onlyPermKlients; Дополнительно, необходимо отображать только работающих `КредитныхИнспекторов`. -1.Построить ограничения, испльзуя LINQ-провайдер: +1.Построить ограничения, испльзуя LINQ-провайдер: ```csharp -var ds = (SQLDataService) DataServiceProvider.DataService; +var ds = (SQLDataService) DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей IQueryable<Клиент> limit1 = ds.Query<Клиент>(Клиент.Views.КлиентL).Where(klient => klient.Прописка.Город == "Пермь"); IQueryable<КредитныйИнспектор> limit2 = ds.Query<КредитныйИнспектор>(КредитныйИнспектор.Views.КредитныйИнспекторL).Where(insp => insp.Работает); ``` diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.en.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.en.md index 6a8acdc6e..0640e6983 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.en.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.en.md @@ -1,69 +1,69 @@ ---- -title: Adding a button in the toolbar or in line WebObjectListView -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET -toc: true -permalink: en/fa_wolv-add-button.html -lang: en -autotranslated: true -hash: 9c977306d7971331e36f9b69a38782032c221de1353c21613165db971a289baf ---- +--- +title: Adding a button in the toolbar or in line WebObjectListView +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET +toc: true +permalink: en/fa_wolv-add-button.html +lang: en +autotranslated: true +hash: 9c977306d7971331e36f9b69a38782032c221de1353c21613165db971a289baf +--- -## Add buttons to the toolbar WOLV +## Add buttons to the toolbar WOLV -To add a button in Toolbar WOLV, you must use the method `AddImageButton(...)` list. -However, before you can add the button in the Toolbar, is to determine which handler will have this button: +To add a button in Toolbar WOLV, you must use the method `AddImageButton(...)` list. +However, before you can add the button in the Toolbar, is to determine which handler will have this button: -* Server -* Client -* The server and client. +* Server +* Client +* The server and client. -### Server processor +### Server processor -If the handler needs to be a server, you must use the following method overload `AddImageButton`: +If the handler needs to be a server, you must use the following method overload `AddImageButton`: ```csharp -/// -/// Method to add custom buttons to the toolbar with the possibility of -/// a server handler. -/// -/// Server ID of the button. -/// CSS class that is applied to the button. -/// the tooltip Text to the button. -/// Server-side handler for the button click. +/// +/// Method to add custom buttons to the toolbar with the possibility of +/// a server handler. +/// +/// Server ID of the button. +/// CSS class that is applied to the button. +/// the tooltip Text to the button. +/// Server-side handler for the button click. public void AddImageButton(string id, string cssClass, string alternateText, ToolBarBtnEventHandler clickHandler) -``` +``` -As you can see, the method is passed the ID of the button, CSS class, tooltip text, and a backend handler for the clicking of the following types: +As you can see, the method is passed the ID of the button, CSS class, tooltip text, and a backend handler for the clicking of the following types: ```csharp public delegate void ToolBarBtnEventHandler(LinkButton sender, ToolBarBtnEventArgs eventArgs); -``` +``` -#### ToolBarBtnEventArgs +#### ToolBarBtnEventArgs -`ToolBarBtnEventArgs` - arguments to be passed to the server handler for the button click in the Toolbar e WOLV. +`ToolBarBtnEventArgs` - arguments to be passed to the server handler for the button click in the Toolbar e WOLV. -The information can be obtained from `ToolBarBtnEventArgs`: +The information can be obtained from `ToolBarBtnEventArgs`: -| Name | Description | -| -------- | -------- | -| `List PrimaryKeys` | List of keys of selected objects in the list. __Important: if the option "Select all on all pages", it will return an empty list__. | -| `bool IsAllSelected` | if the option "Select all on all pages". | -| `WebObjectListView WOLV` | Instance list button on a Toolbar which button was pressed. | -| `Function LimitFunction` | Limiting function is superimposed on the list. | +| Name | Description | +| -------- | -------- | +| `List PrimaryKeys` | List of keys of selected objects in the list. __Important: if the option "Select all on all pages", it will return an empty list__. | +| `bool IsAllSelected` | if the option "Select all on all pages". | +| `WebObjectListView WOLV` | Instance list button on a Toolbar which button was pressed. | +| `Function LimitFunction` | Limiting function is superimposed on the list. | -#### Example usage +#### Example usage ```csharp protected override void Preload() { ... WebObjectListView1.AddImageButton( - "TestToolbarServerButton", // The ID of the button - "wolv-test-toolbar-server-button", // CSS Class - "Test server button of the toolbar", // Tooltip text - CustomToolbarButtonClickHandler); // Handler + "TestToolbarServerButton", // The ID of the button + "wolv-test-toolbar-server-button", // CSS Class + "Test server button of the toolbar", // Tooltip text + CustomToolbarButtonClickHandler); // Handler ... } ... @@ -72,18 +72,18 @@ private void CustomToolbarButtonClickHandler(object sender, ToolBarBtnEventArgs { TestToolbarButtonLabel.Visible = true; - // Check properties Wolv event arguments. + // Check properties Wolv event arguments. if (eventArgs.Wolv != WebObjectListView1) { throw new Exception("WOLV instance in the handler of button click of the toolbar is incorrect."); } - // Check the properties of PrimaryKeys. + // Check the properties of PrimaryKeys. if (eventArgs.PrimaryKeys.Count > 0) { var objects = eventArgs.PrimaryKeys.Select(x => new Город { __PrimaryKey = Guid.Parse(x) }) .Cast().ToArray(); - DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); + DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); // DataServiceProvider is deprecated; inject IDataService instead SelectedCitiesLabel.Visible = SelectedCitiesList.Visible = true; foreach (var obj in objects) @@ -92,69 +92,69 @@ private void CustomToolbarButtonClickHandler(object sender, ToolBarBtnEventArgs } } - // Check properties IsAllSelected. + // Check properties IsAllSelected. AllIsSelectedLabel.Visible = eventArgs.IsAllSelected; } -``` +``` -### Client handler +### Client handler -If the handler needs to be a client, you should use the following overload of the method `AddImageButton`: +If the handler needs to be a client, you should use the following overload of the method `AddImageButton`: ```csharp -/// -/// Method to add custom buttons to the toolbar with the possibility of -/// client handler. -/// -/// Server ID of the button. -/// CSS class that is applied to the button. -/// the tooltip Text to the button. -/// the name of the JS function in a global object client-side handler for the button click. -/// Additional options for the JS handler. +/// +/// Method to add custom buttons to the toolbar with the possibility of +/// client handler. +/// +/// Server ID of the button. +/// CSS class that is applied to the button. +/// the tooltip Text to the button. +/// the name of the JS function in a global object client-side handler for the button click. +/// Additional options for the JS handler. public void AddImageButton(string id, string cssClass, string alternateText, string clientClickHandler, string clientClickAddParams) -``` +``` -In addition to ID, CSS class and the tooltip text in the method is also passed the name of the JS function and the parameters that should pass to this function. +In addition to ID, CSS class and the tooltip text in the method is also passed the name of the JS function and the parameters that should pass to this function. -{% include note.html content="Is the name of the JS function, not its code." %} +{% include note.html content="Is the name of the JS function, not its code." %} -#### Example usage +#### Example usage ```csharp protected override void Preload() { ... WebObjectListView1.AddImageButton( - "TestToolbarClientButton", // The ID of the button - "wolv-test-toolbar-client-button", // CSS class - "Test client button of the toolbar", // Tooltip text - "ToolbarBtnClickAlert", // Name of the JS function. - // In principle, the option alert(\"Pressed custom button toolbar client handler\"); - // also rolls, but for more complex handlers may not work correctly. - // Recommended to pass the function name, and describe it separately! - string.Empty); // The parameters passed to the function ToolbarBtnClickAlert. + "TestToolbarClientButton", // The ID of the button + "wolv-test-toolbar-client-button", // CSS class + "Test client button of the toolbar", // Tooltip text + "ToolbarBtnClickAlert", // Name of the JS function. + // In principle, the option alert(\"Pressed custom button toolbar client handler\"); + // also rolls, but for more complex handlers may not work correctly. + // Recommended to pass the function name, and describe it separately! + string.Empty); // The parameters passed to the function ToolbarBtnClickAlert. ... } -``` +``` -### Server and client handler +### Server and client handler -To add the button at the same time and a server and a client-side handler, you must use the following method overload `AddImageButton(...)`: +To add the button at the same time and a server and a client-side handler, you must use the following method overload `AddImageButton(...)`: ```csharp -/// -/// Adding buttons to the toolbar. -/// -/// Click to add. -public void AddImageButton(LinkButton lb) -``` +/// +/// Adding buttons to the toolbar. +/// +/// Click to add. +public void AddImageButton(LinkButton lb) +``` -Using this method, it is important to understand the following: +Using this method, it is important to understand the following: -1. To use this method is necessary only when other methods are not suitable. -2. All button settings (including appearance and styles) falls on the application developer. +1. To use this method is necessary only when other methods are not suitable. +2. All button settings (including appearance and styles) falls on the application developer. -#### Example usage +#### Example usage ```csharp var twoHandlersButton = new LinkButton @@ -166,56 +166,56 @@ var twoHandlersButton = new LinkButton twoHandlersButton.Click += CustomToolbarButtonClickHandler1; twoHandlersButton.ToolTip = "Button with two handlers."; WebObjectListView1.AddImageButton(twoHandlersButton); -``` +``` -## Add buttons in the rows WOLV +## Add buttons in the rows WOLV To add a button in Toolbar WOLV, you must use the method `AddImageButtonToRow(...)` list. -However, before you can add the button in the Toolbar, is to determine which handler will have this button: +However, before you can add the button in the Toolbar, is to determine which handler will have this button: -* Server -* Client. +* Server +* Client. -### Server processor +### Server processor -If the handler needs to be a server, you must use the following method overload `AddImageButtonToRow`: +If the handler needs to be a server, you must use the following method overload `AddImageButtonToRow`: ```csharp -/// -/// Add a button to each row -/// -/// the ID of the button (will be added to the index of the row) -/// the Class of the control -/// Signature -/// Server-side event that will come clicking -/// The PrimaryKey of the object in the row can be obtained as follows: -/// primaryKey = (sender as ImageButton).Attributes["pk"]; -/// +/// +/// Add a button to each row +/// +/// the ID of the button (will be added to the index of the row) +/// the Class of the control +/// Signature +/// Server-side event that will come clicking +/// The PrimaryKey of the object in the row can be obtained as follows: +/// primaryKey = (sender as ImageButton).Attributes["pk"]; +/// public void AddImageButtonToRow(string id, string cssClass, string alternateText, ToolBarBtnEventHandler clickHandler) -``` +``` -As in the case of the add server button on the Toolbar is passed into the method ID of a button, CSS class, tooltip text, and a backend handler for the clicking of the following types: +As in the case of the add server button on the Toolbar is passed into the method ID of a button, CSS class, tooltip text, and a backend handler for the clicking of the following types: ```csharp public delegate void ToolBarBtnEventHandler(LinkButton sender, ToolBarBtnEventArgs eventArgs); -``` +``` -#### ToolBarBtnEventArgs +#### ToolBarBtnEventArgs -Similarly EventArgs'am Toolbar a. +Similarly EventArgs'am Toolbar a. -#### Example usage +#### Example usage ```csharp protected override void Preload() { ... WebObjectListView1.AddImageButtonToRow( - "TestRowServerButton", // The ID of the button - "ics-wolv-toolbar-button ics-wolv-toolbar-button-icon wolv-test-row-server-button", // CSS class - "Test server button in the row", // Tooltip text - CustomToolbarButtonClickHandler); // A server handler for the clicking + "TestRowServerButton", // The ID of the button + "ics-wolv-toolbar-button ics-wolv-toolbar-button-icon wolv-test-row-server-button", // CSS class + "Test server button in the row", // Tooltip text + CustomToolbarButtonClickHandler); // A server handler for the clicking ... } @@ -225,18 +225,18 @@ private void CustomToolbarButtonClickHandler(object sender, ToolBarBtnEventArgs { TestToolbarButtonLabel.Visible = true; - // Check properties Wolv event arguments. + // Check properties Wolv event arguments. if (eventArgs.Wolv != WebObjectListView1) { throw new Exception("WOLV instance in the handler of button click of the toolbar is incorrect."); } - // Check the properties of PrimaryKeys. + // Check the properties of PrimaryKeys. if (eventArgs.PrimaryKeys.Count > 0) { var objects = eventArgs.PrimaryKeys.Select(x => new Город { __PrimaryKey = Guid.Parse(x) }) .Cast().ToArray(); - DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); + DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); // DataServiceProvider is deprecated; inject IDataService instead SelectedCitiesLabel.Visible = SelectedCitiesList.Visible = true; foreach (var obj in objects) @@ -245,49 +245,49 @@ private void CustomToolbarButtonClickHandler(object sender, ToolBarBtnEventArgs } } - // Check properties IsAllSelected. + // Check properties IsAllSelected. AllIsSelectedLabel.Visible = eventArgs.IsAllSelected; } -``` +``` -### Client handler +### Client handler -If the handler needs to be a client, you should use the following overload of the method `AddImageButton`: +If the handler needs to be a client, you should use the following overload of the method `AddImageButton`: ```csharp -/// -/// Add a button to each row -/// -/// the ID of the button (will be added to the index of the row) -/// the Class of the control -/// Signature -/// the name of the client function that will be invoked when clicked -/// Additional parameters that will be passed to the client function +/// +/// Add a button to each row +/// +/// the ID of the button (will be added to the index of the row) +/// the Class of the control +/// Signature +/// the name of the client function that will be invoked when clicked +/// Additional parameters that will be passed to the client function public void AddImageButtonToRow(string id, string cssClass, string alternateText, string clientClickHandler, string clientClickAddParams) -``` +``` -In addition to ID, CSS class and the tooltip text in the method is also passed the name of the JS function and the parameters that should pass to this function. +In addition to ID, CSS class and the tooltip text in the method is also passed the name of the JS function and the parameters that should pass to this function. -{% include note.html content="Is the name of the JS function, not its code." %} +{% include note.html content="Is the name of the JS function, not its code." %} -#### Example usage +#### Example usage ```csharp protected override void Preload() { ... WebObjectListView1.AddImageButton( - "TestRowClientButton", // The ID of the button - "ics-wolv-toolbar-button ics-wolv-toolbar-button-icon wolv-test-row-client-button", // CSS class - "Test client button in the line", // Tooltip text - "RowBtnClickAlert", // Name of the JS function. - // In principle, the option alert(\"you Pressed the custom button in the row with the client handler\"); - // also rolls, but for more complex handlers may not work correctly. - // Recommended to pass the function name, and describe it separately! - string.Empty); // The parameters passed to the function RowBtnClickAlert. + "TestRowClientButton", // The ID of the button + "ics-wolv-toolbar-button ics-wolv-toolbar-button-icon wolv-test-row-client-button", // CSS class + "Test client button in the line", // Tooltip text + "RowBtnClickAlert", // Name of the JS function. + // In principle, the option alert(\"you Pressed the custom button in the row with the client handler\"); + // also rolls, but for more complex handlers may not work correctly. + // Recommended to pass the function name, and describe it separately! + string.Empty); // The parameters passed to the function RowBtnClickAlert. ... } -``` +``` diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.ru.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.ru.md index 97a09b68d..b41bb1e73 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.ru.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-add-button.ru.md @@ -81,7 +81,7 @@ private void CustomToolbarButtonClickHandler(object sender, ToolBarBtnEventArgs { var objects = eventArgs.PrimaryKeys.Select(x => new Город { __PrimaryKey = Guid.Parse(x) }) .Cast().ToArray(); - DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); + DataServiceProvider.DataService.LoadObjects(objects, Город.Views.ГородL, true); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей SelectedCitiesLabel.Visible = SelectedCitiesList.Visible = true; foreach (var obj in objects) @@ -144,7 +144,7 @@ protected override void Preload() /// Добавление кнопки на тулбар. /// /// Кнопка для добавления. -public void AddImageButton(LinkButton lb) +public void AddImageButton(LinkButton lb) ``` При использовании этого метода важно понимать следующее: diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.en.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.en.md index 4b70168d5..b33345afe 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.en.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.en.md @@ -1,184 +1,184 @@ ---- -title: Events WebObjectListView -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET -toc: true -permalink: en/fa_wolv-events.html -lang: en -autotranslated: true -hash: 055e486e5f1d3633f793f72a507739eb8f8f322fe873ef6ee08acbe0c37f95b4 ---- - -All the event arguments [WebObjectListView](fa_web-object-list-view.html) inherited from base: +--- +title: Events WebObjectListView +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET +toc: true +permalink: en/fa_wolv-events.html +lang: en +autotranslated: true +hash: 055e486e5f1d3633f793f72a507739eb8f8f322fe873ef6ee08acbe0c37f95b4 +--- + +All the event arguments [WebObjectListView](fa_web-object-list-view.html) inherited from base: ```csharp -/// -/// Argument type for events WOLV. -/// +/// +/// Argument type for events WOLV. +/// public class WolvEventArgs : CancelEventArgs { } -``` +``` -## the List of events +## the List of events -| Event | Description | -| ------- | -------- | -| `ObjectAdding` | Transition to object creation. | -| `ObjectEditing` | Transition to the edit form of the object. | -| `ObjectPrototyping` | Transition to the prototyping object. | -| `ObjectDeleting` | object Deletion started. The event will be called for each deleted object. | -| `ObjectsDeleted` | Objects departed. You cannot generate event delete for each object. | +| Event | Description | +| ------- | -------- | +| `ObjectAdding` | Transition to object creation. | +| `ObjectEditing` | Transition to the edit form of the object. | +| `ObjectPrototyping` | Transition to the prototyping object. | +| `ObjectDeleting` | object Deletion started. The event will be called for each deleted object. | +| `ObjectsDeleted` | Objects departed. You cannot generate event delete for each object. | -* Have the ability to customize their message to users after deleting the object. For the formation of the message, you can use the list of deleted objects and -the list of objects that failed to delete. -* Also has the ability to convey the status of the removal of honey early removal and end removal. +* Have the ability to customize their message to users after deleting the object. For the formation of the message, you can use the list of deleted objects and +the list of objects that failed to delete. +* Also has the ability to convey the status of the removal of honey early removal and end removal. -## the event Arguments +## the event Arguments -Events `ObjectEditing` and `ObjectPrototyping` in the arguments contains the primary key of the data object - `DataObjectPrimaryKey`. +Events `ObjectEditing` and `ObjectPrototyping` in the arguments contains the primary key of the data object - `DataObjectPrimaryKey`. -Through the event arguments `ObjectDeleting` you can get to the deleted object data `DataObj`, and change it. +Through the event arguments `ObjectDeleting` you can get to the deleted object data `DataObj`, and change it. -The event arguments `ObjectsDeleted` allow you to edit or clear a message to the user - `UserMessage`. +The event arguments `ObjectsDeleted` allow you to edit or clear a message to the user - `UserMessage`. -To store application metadata between the event and the event `ObjectDeleting` `ObjectsDeleted` used `DeletingState` and `DeletedState` available through the arguments of these events. +To store application metadata between the event and the event `ObjectDeleting` `ObjectsDeleted` used `DeletingState` and `DeletedState` available through the arguments of these events. -## Cancel events +## Cancel events -Any event can be cancelled by selecting the arguments `Cancel = true`, because all the arguments are inherited from `CancelEventArgs`. +Any event can be cancelled by selecting the arguments `Cancel = true`, because all the arguments are inherited from `CancelEventArgs`. -If an exception occurred when deleting an object, you can handle signing up for the event `ExceptionThrown`. +If an exception occurred when deleting an object, you can handle signing up for the event `ExceptionThrown`. -## Own event handler `ObjectDeleting` +## Own event handler `ObjectDeleting` -If you implement your own handler `ObjectDeleting` and set the arguments `Cancel = true`, then you need in the event handler `ObjectsDeleted` to clean or change its message to the user, which is stored `args.UserMessage`. Otherwise, the message "deleted object: 1, because some objects have been locked.", even if the objects were removed successfully. +If you implement your own handler `ObjectDeleting` and set the arguments `Cancel = true`, then you need in the event handler `ObjectsDeleted` to clean or change its message to the user, which is stored `args.UserMessage`. Otherwise, the message "deleted object: 1, because some objects have been locked.", even if the objects were removed successfully. -## Example manual handling events `ObjectDeleting` for processing the [cascade deleting objects](fo_cascade-delete.html) +## Example manual handling events `ObjectDeleting` for processing the [cascade deleting objects](fo_cascade-delete.html) -The concept of event processing: +The concept of event processing: -1. Subscribe to the event `ObjectDeleting`. -2. To write a handler to handle the cascade delete related objects to be deleted. -3. Write code for the business server, which will inform the handler about the objects associated with the deleted. -4. If any, then prompt the user for permission to delete related objects (showing him what the objects are removed). -5. If the user will be allowed to cascade delete, then execute it. +1. Subscribe to the event `ObjectDeleting`. +2. To write a handler to handle the cascade delete related objects to be deleted. +3. Write code for the business server, which will inform the handler about the objects associated with the deleted. +4. If any, then prompt the user for permission to delete related objects (showing him what the objects are removed). +5. If the user will be allowed to cascade delete, then execute it. -### the First stage. Event subscription +### the First stage. Event subscription -__The first option.__ To sign up statically (in the markup page that contains [WebObjectListView](fa_web-object-list-view.html). She called `wolv_page.aspx`). +__The first option.__ To sign up statically (in the markup page that contains [WebObjectListView](fa_web-object-list-view.html). She called `wolv_page.aspx`). ```xml <%-- Разметка из wolv_page.aspx --%>; ; -``` +``` -__The second option.__ To subscribe from code (in the code-behind page that contains WOLV. Let the code file is called `wolv_page.aspx.cs`). +__The second option.__ To subscribe from code (in the code-behind page that contains WOLV. Let the code file is called `wolv_page.aspx.cs`). ```csharp -// Code from wolv_page.aspx.cs +// Code from wolv_page.aspx.cs protected override void Preload() { WebObjectListView1.ObjectDeleting += WebObjectListView1_ObjectDeleting; } -``` +``` -{% include note.html content="When you subscribe to an event from code Studio will offer automatic generation of event handler. If you press `Tab` after -printed =, it will generate the name of the handler `WebObjectListView1_ObjectDeleting.` +{% include note.html content="When you subscribe to an event from code Studio will offer automatic generation of event handler. If you press `Tab` after +printed =, it will generate the name of the handler `WebObjectListView1_ObjectDeleting.` -If you again press `Tab` will be generated pattern handler: +If you again press `Tab` will be generated pattern handler: ```csharp protected void WebObjectListView1_ObjectDeleting(WebObjectListView sender, WolvEventArgs args) -``` -"%} +``` +"%} -### the Second stage. Processing events +### the Second stage. Processing events ```csharp -// Code from wolv_page.aspx.cs +// Code from wolv_page.aspx.cs -// Collection objects in the format [{objectPK: the String representation of the primary key of the deleted addresses, confirmMessage: message Text of reference to the address object}, ...] +// Collection objects in the format [{objectPK: the String representation of the primary key of the deleted addresses, confirmMessage: message Text of reference to the address object}, ...] private List _deletingObjectsCollection = new List(); -// This handler will be consistently invoked for each object selected for deletion. +// This handler will be consistently invoked for each object selected for deletion. protected void WebObjectListView1_ObjectDeleting(WebObjectListView sender, WolvObjectDeletingEventArgs args) -{ - // Mark the received object to delete (in this example it is the address of the facility). +{ + // Mark the received object to delete (in this example it is the address of the facility). args.DataObj.SetStatus(ICSSoft.STORMNET.ObjectStatus.Deleted); try - { // Try to remove (further processing occurs in the Business server, Adress.cs). - // If during uninstall an error occurs, we will be able to handle it in the catch block. - // If Adress.cs will find companies that reference the deleted address, it will throw ConfirmAdresDeletingException. - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.UpdateObject(args.DataObj); + { // Try to remove (further processing occurs in the Business server, Adress.cs). + // If during uninstall an error occurs, we will be able to handle it in the catch block. + // If Adress.cs will find companies that reference the deleted address, it will throw ConfirmAdresDeletingException. + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.UpdateObject(args.DataObj); // DataServiceProvider is deprecated; inject IDataService instead } - // Handle the exception business server + // Handle the exception business server catch (ConfirmAdresDeletingException ex) - { - // If we got this piece of code was a means for the detected objects referencing the deleted address. - // Confirmation is required cascade delete. - // Store information about references to deleted address. After a page reload, it will take the client code. - // objectPK is the primary key of the referencing object, confirmMessage the message object generated in the business server. + { + // If we got this piece of code was a means for the detected objects referencing the deleted address. + // Confirmation is required cascade delete. + // Store information about references to deleted address. After a page reload, it will take the client code. + // objectPK is the primary key of the referencing object, confirmMessage the message object generated in the business server. _deletingObjectsCollection.Add(new { objectPK = args.DataObj.__PrimaryKey.ToString(), confirmMessage = ex.Message }); } - //Cancel the further execution of the removal of WOLV-Ohm, because we have fulfilled it with your hands. - //If this is not done, then the code on the business server will run again. + //Cancel the further execution of the removal of WOLV-Ohm, because we have fulfilled it with your hands. + //If this is not done, then the code on the business server will run again. args.Cancel = true; } -// Returns the serialized JSON string of the format "[{"objectPK": "the String representation of the primary key of the deleted addresses", "confirmMessage": "the text of the reference, to the address of the object"}, ...]". +// Returns the serialized JSON string of the format "[{"objectPK": "the String representation of the primary key of the deleted addresses", "confirmMessage": "the text of the reference, to the address of the object"}, ...]". public string DeletingObjects { get { - //The JavaScriptSerializer is in the System namespace.Web.Script.Serialization; + //The JavaScriptSerializer is in the System namespace.Web.Script.Serialization; JavaScriptSerializer serializer = new JavaScriptSerializer(); - //Escapes quotes + //Escapes quotes return serializer.Serialize(_deletingObjectsCollection).Replace("\"", "\\\""); } } -``` +``` -### the Third stage. Getting in the business server information on the connected objects +### the Third stage. Getting in the business server information on the connected objects ```csharp -//Code from Adress.cs +//Code from Adress.cs public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInstitutionsGuide.Адрес UpdatedObject) { - // *** Start programmer edit section *** (OnUpdateАдрес) - //In case the processing is interrupted, return an empty array DataObject[] + // *** Start programmer edit section *** (OnUpdateАдрес) + //In case the processing is interrupted, return an empty array DataObject[] DataObject[] result = new DataObject[0]; if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) { - //Get the list of institutions referring to the deleted address - var ds = (SQLDataService)DataServiceProvider.DataService; + //Get the list of institutions referring to the deleted address + var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead МедицинскоеУчреждение[] mil = ds.Query<МедицинскоеУчреждение>(МедицинскоеУчреждение.Views.MIG_МедицинскоеУчреждениеE) .Where(o => o.Адрес.__PrimaryKey == UpdatedObject.__PrimaryKey) .ToArray(); - //If list is not empty, then it will need the cascading delete - //Need to check whether the user confirmation, and if not, request it + //If list is not empty, then it will need the cascading delete + //Need to check whether the user confirmation, and if not, request it if (mil.Length > 0) { - //If user confirmed a cascading delete, in DynamicProperties of the property is a flag that the key "DeletingAllowed" + //If user confirmed a cascading delete, in DynamicProperties of the property is a flag that the key "DeletingAllowed" if (UpdatedObject.DynamicProperties.ContainsKey("DeletingAllowed")) { - //Mark Agency for the removal + //Mark Agency for the removal foreach (МедицинскоеУчреждение mi in mil) { mi.SetStatus(ObjectStatus.Deleted); } - //Return the deleted companies, so they were removed in the same transaction + //Return the deleted companies, so they were removed in the same transaction result = mil; } else { - //Need to prompt the user for confirmation on delete cascade institutions, followed by their address - //Generated string with the names of the institutions + //Need to prompt the user for confirmation on delete cascade institutions, followed by their address + //Generated string with the names of the institutions string referencedObjects = String.Join(", ", mil.Select(o => String.Format("'{0}'", o.Название))); - //Early removal, by sending in the drop handler, the message about referencing objects - //Method UpdatedObject.ToString(true) just returns the address string, for example "Russia, Perm region, Perm, Brothers Ignatovich, 2" - throw new MIG_ConfirmAdresDeletingException(String.Format("Вы уверены, что хотите удалить адрес: '{0}'? На него ссылаются следующие медицинские учреждения: {1}. + //Early removal, by sending in the drop handler, the message about referencing objects + //Method UpdatedObject.ToString(true) just returns the address string, for example "Russia, Perm region, Perm, Brothers Ignatovich, 2" + throw new MIG_ConfirmAdresDeletingException(String.Format("Вы уверены, что хотите удалить адрес: '{0}'? На него ссылаются следующие медицинские учреждения: {1}. Они так же будут удалены вместе с информацией об их телефонах и расходах.", UpdatedObject.ToString(true), referencedObjects)); @@ -186,33 +186,33 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInsti } } return result; - // *** End programmer edit section *** (OnUpdateАдрес) + // *** End programmer edit section *** (OnUpdateАдрес) } -``` +``` -### the Fourth stage. Confirmation on cascade delete of objects +### the Fourth stage. Confirmation on cascade delete of objects -The confirmation message with [JavaScript API](fa_js-api-core.html): +The confirmation message with [JavaScript API](fa_js-api-core.html): ```javascript -//Code from wolv_page.aspx -//wiki forbids SCRIPT tag-and therefore facing underline, in real code it should not be. +//Code from wolv_page.aspx +//wiki forbids SCRIPT tag-and therefore facing underline, in real code it should not be. <_script type="text/javascript"> - //Client processing cascade delete addresses, and of referencing them, the objects + //Client processing cascade delete addresses, and of referencing them, the objects $(document).ready(function () { - //Collect from the server (via a public property DeletingObjects)serialized JSON string format of the form - //"[{"objectPK": "the String representation of the primary key of the deleted addresses", - // "confirmMessage": "the text of the reference, to the address of the object"}, ...]" and deserialize it + //Collect from the server (via a public property DeletingObjects)serialized JSON string format of the form + //"[{"objectPK": "the String representation of the primary key of the deleted addresses", + // "confirmMessage": "the text of the reference, to the address of the object"}, ...]" and deserialize it var deletingObjects = $.parseJSON("<%=DeletingObjects%>"); - //Perform processing only if at least one address is required cascade delete + //Perform processing only if at least one address is required cascade delete if (deletingObjects.length > 0) { - //String to tell the user + //String to tell the user var confirmMessage = ""; - //String JSON format for the primary keys of the deleted addresses (for sending to the server, in the case of a delete confirmation) + //String JSON format for the primary keys of the deleted addresses (for sending to the server, in the case of a delete confirmation) var deletingObjectsPK = ""; var lastIndex = deletingObjects.length - 1; - //Generated string + //Generated string for (var i = 0; i < deletingObjects.length; i++) { confirmMessage = confirmMessage + (i + 1) + "). " + deletingObjects[i].confirmMessage + "\n"; deletingObjectsPK = deletingObjectsPK + "\"" + deletingObjects[i].objectPK + "\""; @@ -221,7 +221,7 @@ The confirmation message with [JavaScript API](fa_js-api-core.html): } } deletingObjectsPK = "[" + deletingObjectsPK + "]"; - //Display a confirmation window + //Display a confirmation window $.ics.dialog.confirm({ message: confirmMessage, title: 'Подтверждение каскадного удаления связанных объектов', @@ -229,13 +229,13 @@ The confirmation message with [JavaScript API](fa_js-api-core.html): cancelButtonText: "Cancel", callback: function (res) { if (res) { - //When OK is pressed. - //Initiate the PostBack, passing, as argument, - //the JSON string format with primary keys odulami addresses. - //'confirmDeletingOkBtn' - the name of the button on the confirmation dialog, which initiates the PostBack. + //When OK is pressed. + //Initiate the PostBack, passing, as argument, + //the JSON string format with primary keys odulami addresses. + //'confirmDeletingOkBtn' - the name of the button on the confirmation dialog, which initiates the PostBack. __doPostBack('confirmDeletingOkBtn', deletingObjectsPK); } else { - //When pressing Cancel. + //When pressing Cancel. alert("Cascade deletion canceled."); } } @@ -244,58 +244,58 @@ The confirmation message with [JavaScript API](fa_js-api-core.html): }); -``` +``` -The user will receive the following confirmation window: +The user will receive the following confirmation window: -![](/images/pages/products/flexberry-aspnet/controls/wolv/confirm-cascade-deleting.png) +![](/images/pages/products/flexberry-aspnet/controls/wolv/confirm-cascade-deleting.png) -### the Fifth stage. To perform a cascade delete objects if the user has consented +### the Fifth stage. To perform a cascade delete objects if the user has consented ```csharp -// Code from wolv_page.aspx.cs +// Code from wolv_page.aspx.cs protected override void Preload() { - // *** Start programmer edit section *** (PostBack handling) + // *** Start programmer edit section *** (PostBack handling) if (Page.IsPostBack) { - //Handle the case where the PostBack occurred when confirmation by the user - //cascade delete selected addresses and referencing them, the objects. + //Handle the case where the PostBack occurred when confirmation by the user + //cascade delete selected addresses and referencing them, the objects. - //Get the name of the object that caused the PostBack + //Get the name of the object that caused the PostBack string targetID = Request.Form["__EVENTTARGET"]; if (!String.IsNullOrEmpty(targetID)) { - //If the object is a "OK" button of confirmation window + //If the object is a "OK" button of confirmation window if (targetID.Equals("confirmDeletingOkBtn")) { - //Get the JSON string format with the primary keys of the deleted addresses + //Get the JSON string format with the primary keys of the deleted addresses string argument = Request.Form["__EVENTARGUMENT"]; - //Perform deserialization of string + //Perform deserialization of string JavaScriptSerializer serializer = new JavaScriptSerializer(); List deletingObjectsPK = serializer.Deserialize>(argument); - //Forming an array of deleted addresses + //Forming an array of deleted addresses DataObject[] deletingAdreses = deletingObjectsPK.Select(pk => { - //Create an object of class "Address" with the desired primary key + //Create an object of class "Address" with the desired primary key Адрес deletingAdres = new Адрес(); deletingAdres.SetExistObjectPrimaryKey(new Guid(pk)); - //Confirm the cascade delete of the objects that link to this address - //by the presence, in DynamicProperties the key "DeletingAllowed", the business server will understand that cascading deletes are allowed + //Confirm the cascade delete of the objects that link to this address + //by the presence, in DynamicProperties the key "DeletingAllowed", the business server will understand that cascading deletes are allowed deletingAdres.DynamicProperties.Add("DeletingAllowed", true); - //Mark the address for deletion + //Mark the address for deletion deletingAdres.SetStatus(ObjectStatus.Deleted); - //Add to the array + //Add to the array return deletingAdres; }).ToArray<Адрес>(); - //Delete. (Further processing takes place in Adress) - DataServiceProvider.DataService.UpdateObjects(ref deletingAdreses); + //Delete. (Further processing takes place in Adress) + DataServiceProvider.DataService.UpdateObjects(ref deletingAdreses); // DataServiceProvider is deprecated; inject IDataService instead } } } - // *** End programmer edit section *** (PostBack handling) + // *** End programmer edit section *** (PostBack handling) } -``` +``` diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.ru.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.ru.md index 6d666c343..d86372d80 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.ru.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-events.ru.md @@ -30,7 +30,7 @@ public class WolvEventArgs : CancelEventArgs * Есть возможность настроить своё сообщение для пользователей после удаления объекта. Для формирования сообщения можно использовать список удаленных объектов и список объектов, которые не удалось удалить. -* Также есть возможность передавать статус удаления меду событиями начала удаления и окончания удаления. +* Также есть возможность передавать статус удаления меду событиями начала удаления и окончания удаления. ## Аргументы событий @@ -101,18 +101,18 @@ private List _deletingObjectsCollection = new List(); // Данный обработчик будет последовательно вызван для каждого объекта, выбранного на удаление. protected void WebObjectListView1_ObjectDeleting(WebObjectListView sender, WolvObjectDeletingEventArgs args) -{ +{ // Помечаем пришедший объект на удаление (в данном примере это будет адрес медицинского учреждения). args.DataObj.SetStatus(ICSSoft.STORMNET.ObjectStatus.Deleted); try { // Пытаемся удалить (дальнейшая обработка происходит в Бизнес-сервере АдресБС.cs). // Если во время удаления произойдет ошибка, мы сможем ее обработать в блоке catch. // Если АдресБС.cs найдет учреждения, ссылающиеся на удаляемый адрес, он кинет ConfirmAdresDeletingException. - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.UpdateObject(args.DataObj); + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.UpdateObject(args.DataObj); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей } // Обрабатываем исключение бизнес-сервера catch (ConfirmAdresDeletingException ex) - { + { // Если мы попали в этот участок кода, значит были обнаружены объекты ссылающиеся на удаляемый адрес. // Требуется подтверждение каскадного удаления. // Запоминаем информацию о ссылках на удаляемый адрес. После перезагрузки страницы, её заберёт клиентский код. @@ -150,7 +150,7 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInsti if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) { //Получим список учреждений ссылающихся на удаляемый адрес - var ds = (SQLDataService)DataServiceProvider.DataService; + var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей МедицинскоеУчреждение[] mil = ds.Query<МедицинскоеУчреждение>(МедицинскоеУчреждение.Views.MIG_МедицинскоеУчреждениеE) .Where(o => o.Адрес.__PrimaryKey == UpdatedObject.__PrimaryKey) .ToArray(); @@ -176,7 +176,7 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInsti string referencedObjects = String.Join(", ", mil.Select(o => String.Format("'{0}'", o.Название))); //Прерываем удаление, отправив в обработчик удаления, сообщения о ссылающихся объектах //Метод UpdatedObject.ToString(true) просто возвращает строку с адресом, например "Россия, Пермский край, Пермь, Братьев Игнатовых, 2" - throw new MIG_ConfirmAdresDeletingException(String.Format("Вы уверены, что хотите удалить адрес: '{0}'? На него ссылаются следующие медицинские учреждения: {1}. + throw new MIG_ConfirmAdresDeletingException(String.Format("Вы уверены, что хотите удалить адрес: '{0}'? На него ссылаются следующие медицинские учреждения: {1}. Они так же будут удалены вместе с информацией об их телефонах и расходах.", UpdatedObject.ToString(true), referencedObjects)); @@ -199,8 +199,8 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInsti <_script type="text/javascript"> //Клиенская обработка каскадного удаления адресов и ссылающихся, на них, объектов $(document).ready(function () { - //Забираем с сервера (через публичное свойство DeletingObjects)сериализованную строку JSON формата вида - //"[{"objectPK": "Строковое представление первичного ключа удаляемого адреса", + //Забираем с сервера (через публичное свойство DeletingObjects)сериализованную строку JSON формата вида + //"[{"objectPK": "Строковое представление первичного ключа удаляемого адреса", // "confirmMessage": "Текст сообщения о ссылающихся, на адрес, объектах"}, ...]" и десериализуем её var deletingObjects = $.parseJSON("<%=DeletingObjects%>"); //Выполняем обработку, только если хотя бы для одного адреса требуется каскадное удаление @@ -228,7 +228,7 @@ public virtual ICSSoft.STORMNET.DataObject[] OnUpdateАдрес(IIS.MedicalInsti callback: function (res) { if (res) { //При нажатии OK. - //Инициируем PostBack, передав, в качестве аргумента, + //Инициируем PostBack, передав, в качестве аргумента, //строку JSON формата с первичными ключами удалямых адресов. //'confirmDeletingOkBtn' - имя кнопки на окне подтверждения, которая инициирует PostBack. __doPostBack('confirmDeletingOkBtn', deletingObjectsPK); @@ -257,7 +257,7 @@ protected override void Preload() // *** Start programmer edit section *** (PostBack handling) if (Page.IsPostBack) { - //Обрабатываем случай, когда PostBack произошел при подтверждении, пользователем, + //Обрабатываем случай, когда PostBack произошел при подтверждении, пользователем, //каскадного удаления выбранных адресов и ссылающихся, на них, объектов. //Получаем имя объекта вызвавшего PostBack @@ -287,7 +287,7 @@ protected override void Preload() return deletingAdres; }).ToArray<Адрес>(); //Удаляем. (Дальнейшая обработка происходит в АдресБС) - DataServiceProvider.DataService.UpdateObjects(ref deletingAdreses); + DataServiceProvider.DataService.UpdateObjects(ref deletingAdreses); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей } } } diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.en.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.en.md index 3728a2662..b953cc0d7 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.en.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.en.md @@ -1,86 +1,86 @@ ---- -title: Export data to Excel from WebObjectListView -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET Flexberry Reports, database -toc: true -permalink: en/fa_wolv-export-excel.html -lang: en -autotranslated: true -hash: 16df50707017d4ce65041e114c0b25eaba51f97163fcc01d8cac34096f4013a9 ---- +--- +title: Export data to Excel from WebObjectListView +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET Flexberry Reports, database +toc: true +permalink: en/fa_wolv-export-excel.html +lang: en +autotranslated: true +hash: 16df50707017d4ce65041e114c0b25eaba51f97163fcc01d8cac34096f4013a9 +--- -## download to Excel (instructions to the programmer) +## download to Excel (instructions to the programmer) -[WebObjectListView](fa_web-object-list-view.html) allows to download data in Excel format. +[WebObjectListView](fa_web-object-list-view.html) allows to download data in Excel format. -This feature is included with the operation: +This feature is included with the operation: ```csharp -/// -/// Called the first in the Page_Load. -/// +/// +/// Called the first in the Page_Load. +/// protected override void Preload() { WebObjectListView1.Operations.ExportToExcel = true; } -``` +``` -### the View to export +### the View to export -Ask a [view](fd_view-definition.html), the default for export is possible from code by setting the `ExportView` [WOLV](fa_web-object-list-view.html): +Ask a [view](fd_view-definition.html), the default for export is possible from code by setting the `ExportView` [WOLV](fa_web-object-list-view.html): ```csharp WebObjectListView1.ExportView = Клиент.View.КлиентExport; -``` +``` -### Unloading of datalow +### Unloading of datalow -Unloading of datalow occurs if they are present in a [view](fd_view-definition.html). The user can configure the settings metalowego column as well as other properties of the object. +Unloading of datalow occurs if they are present in a [view](fd_view-definition.html). The user can configure the settings metalowego column as well as other properties of the object. -There are 2 settings on the [web edit](fa_editform.html) to control the unloading of detailov. +There are 2 settings on the [web edit](fa_editform.html) to control the unloading of detailov. -1. Detailov fields in separate columns. -2. Detaily in a single row. +1. Detailov fields in separate columns. +2. Detaily in a single row. -* If 1 of the settings is not set, then detaily unloaded in 1 cell in the line: +* If 1 of the settings is not set, then detaily unloaded in 1 cell in the line: -| Aggregator | Detail| -|------------|--------| -| Field of the aggregator | Detail: 1st Field детейла; Detail: Field детейла; Detail 2nd: Field 3rd детейла;| +| Aggregator | Detail| +|------------|--------| +| Field of the aggregator | Detail: 1st Field детейла; Detail: Field детейла; Detail 2nd: Field 3rd детейла;| -* If there is a setting `Поля of datalow in a separate столбцы`, detaily unloaded in 1 cell in a column: +* If there is a setting `Поля of datalow in a separate столбцы`, detaily unloaded in 1 cell in a column: -| Aggregator | Detail| -|------------|---------| -| Aggregator field | Field 1st of detail| -||2nd field of detail| -||3rd field of detail| +| Aggregator | Detail| +|------------|---------| +| Aggregator field | Field 1st of detail| +||2nd field of detail| +||3rd field of detail| -* If you set both settings at once, each detail will be displayed in a new line, and a field aggregator with different strings will be merged into 1 cell. +* If you set both settings at once, each detail will be displayed in a new line, and a field aggregator with different strings will be merged into 1 cell. -![](/images/pages/products/flexberry-aspnet/controls/wolv/two-options.png) +![](/images/pages/products/flexberry-aspnet/controls/wolv/two-options.png) -* To set only the setting `Детейлы in a separate строки` until bessmyslenno, conducted a revision this setting. +* To set only the setting `Детейлы in a separate строки` until bessmyslenno, conducted a revision this setting. -__Note__: if you have an idea of the field of detail not specified title as the title field when uploading, you will use the field name. +__Note__: if you have an idea of the field of detail not specified title as the title field when uploading, you will use the field name. -### data Service +### data Service -The default for the Excel spreadsheets used the data service `DataServiceProvider.DataService`. If you want to ask another, separate service data to unload in Excel, this can be done in `Web.config` by registering a service under the name `ExcelExportDataService` in `Unity`. The example configuration below for the Excel spreadsheets used the data service `IcsharpSoft.STORMNET.Business.DRDataService`: +The default for the Excel spreadsheets used the data service `DataServiceProvider.DataService`. If you want to ask another, separate service data to unload in Excel, this can be done in `Web.config` by registering a service under the name `ExcelExportDataService` in `Unity`. The example configuration below for the Excel spreadsheets used the data service `ICSSoft.STORMNET.Business.DRDataService`: ```xml - + -``` +``` -#### Ogranichenie on the maximum number of objects +#### Ogranichenie on the maximum number of objects -To configure the maximum number of exported objects should be vopspolzovatsya configuration parameter `WOLVExportLimit`: +To configure the maximum number of exported objects should be vopspolzovatsya configuration parameter `WOLVExportLimit`: ```xml @@ -89,48 +89,48 @@ To configure the maximum number of exported objects should be vopspolzovatsya co -``` +``` -Negative values of the parameter, and 0 disables the limit on the maximum number of exported objects. +Negative values of the parameter, and 0 disables the limit on the maximum number of exported objects. -### adding a table for storing settings +### adding a table for storing settings -To add a database table to store user settings, you must have a data structure that is used [UserSettingsService](fa_user-settings-service.html). The table is generated automatically. +To add a database table to store user settings, you must have a data structure that is used [UserSettingsService](fa_user-settings-service.html). The table is generated automatically. -## download to Excel (user manual) +## download to Excel (user manual) -To unload data from a list, click on `Выгрузить in Excel` ![](/images/pages/products/flexberry-aspnet/controls/wolv/export-button.png) on the toolbar, in the opened window configure the format of uploaded data and confirm the unload by clicking on the button `OK`. +To unload data from a list, click on `Выгрузить in Excel` ![](/images/pages/products/flexberry-aspnet/controls/wolv/export-button.png) on the toolbar, in the opened window configure the format of uploaded data and confirm the unload by clicking on the button `OK`. -![](/images/pages/products/flexberry-aspnet/controls/wolv/export-form.png) +![](/images/pages/products/flexberry-aspnet/controls/wolv/export-form.png) -On the form you can: +On the form you can: -* Specify the visibility of the fields by selecting or deselecting the check box at the left of each row. -* Specify the direction of the sort (no sorting, ascending or descending) for each column of data. -* To specify the sort priority (if one of the sorts) -* Specify the name of the data column -* To change the order of columns of data -* The buttons `вверх` and `вниз` the right side of each row -* Or by dragging rows +* Specify the visibility of the fields by selecting or deselecting the check box at the left of each row. +* Specify the direction of the sort (no sorting, ascending or descending) for each column of data. +* To specify the sort priority (if one of the sorts) +* Specify the name of the data column +* To change the order of columns of data +* The buttons `вверх` and `вниз` the right side of each row +* Or by dragging rows -By default, unloaded all data contained in the list subject to the imposed filters and sorting. +By default, unloaded all data contained in the list subject to the imposed filters and sorting. -If you highlight any record with ticks, it will be loaded only the selected records. +If you highlight any record with ticks, it will be loaded only the selected records. -Setting of discharge can be saved for later use. The settings are individual users and cannot be shared with other users. +Setting of discharge can be saved for later use. The settings are individual users and cannot be shared with other users. -To create a configuration, you must select the menu item `Создать set of fields for export...`. In the opened window it is necessary to produce the necessary configuration, specify the name of the configuration and click `Сохранить`. Saved settings are available from the list menu. When you select a saved settings are automatically prompted to save the Excel file. +To create a configuration, you must select the menu item `Создать set of fields for export...`. In the opened window it is necessary to produce the necessary configuration, specify the name of the configuration and click `Сохранить`. Saved settings are available from the list menu. When you select a saved settings are automatically prompted to save the Excel file. -To edit or delete settings can be set by selecting the appropriate menu item. +To edit or delete settings can be set by selecting the appropriate menu item. -![](/images/pages/products/flexberry-aspnet/controls/wolv/export-menu.png) +![](/images/pages/products/flexberry-aspnet/controls/wolv/export-menu.png) -Files are uploaded in XML, which is interpreted `Microsoft Excel`, the file extension is exposed as *.xls (the default extension of Excel documents). When you open -the resulting file in Excel you will see the following warning: +Files are uploaded in XML, which is interpreted `Microsoft Excel`, the file extension is exposed as *.xls (the default extension of Excel documents). When you open +the resulting file in Excel you will see the following warning: -![](/images/pages/products/flexberry-aspnet/controls/wolv/export-warning.png) +![](/images/pages/products/flexberry-aspnet/controls/wolv/export-warning.png) -{% include note.html content="If authentication is turned off or not working then the possibility of creating settings will be disabled." %} +{% include note.html content="If authentication is turned off or not working then the possibility of creating settings will be disabled." %} diff --git a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.ru.md b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.ru.md index eedf67d22..60f146175 100644 --- a/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.ru.md +++ b/pages/products/flexberry-aspnet/controls/wolv/fa_wolv-export-excel.ru.md @@ -41,13 +41,13 @@ WebObjectListView1.ExportView = Клиент.View.КлиентExport; 2. Детейлы в отдельные строки. * Если ни 1 из настроек не выставлена, то детейлы выгружаются в 1 ячейку в строку: - + | Аггрегатор | Детейл| |------------|--------| | Поле аггрегатора | Детейл: Поле 1го детейла; Детейл: Поле 2го детейла; Детейл: Поле 3го детейла;| * Если выставлена настройка `Поля детейлов в отдельные столбцы`, то детейлы выгружаются в 1 ячейку в столбец: - + | Аггрегатор | Детейл| |------------|---------| | Поле аггрегатора | Поле 1го детейла| @@ -64,12 +64,12 @@ __Примечание__: если в представление у поля д ### Сервис данных -По умолчанию для выгрузки в Excel используется сервис данных `DataServiceProvider.DataService`. Если требуется задать другой, отдельный сервис данных для выгрузки в Excel, то это может быть сделано в `Web.config` путем регистрации сервиса под именем `ExcelExportDataService` в `Unity`. Пример конфигурации, чтобы для выгрузки в Excel использовался сервис данных `IcsharpSoft.STORMNET.Business.DRDataService`: +По умолчанию для выгрузки в Excel используется сервис данных `DataServiceProvider.DataService`. Если требуется задать другой, отдельный сервис данных для выгрузки в Excel, то это может быть сделано в `Web.config` путем регистрации сервиса под именем `ExcelExportDataService` в `Unity`. Пример конфигурации, чтобы для выгрузки в Excel использовался сервис данных `ICSSoft.STORMNET.Business.DRDataService`: ```xml - + @@ -111,7 +111,7 @@ __Примечание__: если в представление у поля д * При помощи кнопок `вверх` и `вниз` в правой части каждой строки * Или при помощи перетаскивания строк -По умолчанию выгружаются все данные, содержащиеся в списке с учётом наложенных фильтров и сортировки. +По умолчанию выгружаются все данные, содержащиеся в списке с учётом наложенных фильтров и сортировки. Если в списке выделить какие-либо записи при помощи галочек, то будут выгружаться только выбранные записи. diff --git a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.en.md b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.en.md index 623925c50..17fbf22c2 100644 --- a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.en.md +++ b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.en.md @@ -59,7 +59,8 @@ using ICSSoft.STORMNET.Business.Audit; protected void Application_Start(object sender, EventArgs e) { // Initialize audit service - AuditSetter.InitAuditService(BridgeToDS.GetDataService()); + IServiceProvider serviceProvider; // use dependency injection to get IServiceProvider; one could use IUnityContainer instead + var IAuditService = serviceProvider.GetService(BridgeToDS.GetDataService()); // ... } ``` diff --git a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.ru.md b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.ru.md index ad9939c63..04b0b3b50 100644 --- a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.ru.md +++ b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-example-manual.ru.md @@ -37,7 +37,7 @@ lang: ru ``` -А также +А также ```xml @@ -51,13 +51,14 @@ lang: ru В файле `Global.asax.cs` необходимо добавить: ```csharp -using ICSSoft.STORMNET.Business.Audit; +using ICSSoft.STORMNET.Business.Audit; // ... protected void Application_Start(object sender, EventArgs e) { // Инициализация сервиса аудита - AuditSetter.InitAuditService(BridgeToDS.GetDataService()); + IServiceProvider serviceProvider; // Используйте внедрение зависимостей чтобы получить IServiceProvider; вместо IServiceProvider можно использовать IUnityContainer + var IAuditService = serviceProvider.GetService(BridgeToDS.GetDataService()); // ... } ``` diff --git a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.en.md b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.en.md index a8289d7f2..fa21e310d 100644 --- a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.en.md +++ b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.en.md @@ -27,7 +27,7 @@ For example, the address may be as follows: http://some:1111/Forms/Audit/AuditEn A separate line is the change [primary key object](fo_primary-keys-objects.html) (this string is generated when you change detail or wizard). There are two modes of display these lines: they do not appear or they are hiding in a tree structure (the second option was implemented in [older versions of audit](efs_audit.html)). By default, implements the first option, but you can change the following initialization: ```csharp -AuditService.Current.ShowPrimaryKey = true; +AuditService.Current.ShowPrimaryKey = true; // AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService. ``` ## object-oriented forms of audit @@ -73,7 +73,7 @@ The list of fields to audit is sorted by the time of the operation (top new). To disable the display of records containing [primary keys](fo_primary-keys-objects.html) [masters](fd_master-association.html) and [datalow](fo_detail-associations-properties.html), you can perform the following settings: ```csharp -AuditService.Current.ShowPrimaryKey = false; +AuditService.Current.ShowPrimaryKey = false; // AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService ``` If AuditService.Current.ShowPrimaryKey is set to true, the list of fields displayed changes [in hierarchy](fa_wolv-hierarhy.html) same as in tapicerowane forms of audit. diff --git a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.ru.md b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.ru.md index fb35a3ec6..5213a908f 100644 --- a/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.ru.md +++ b/pages/products/flexberry-aspnet/subsystems/audit/fa_audit-web-forms.ru.md @@ -25,7 +25,7 @@ lang: ru Отдельной строкой идёт изменение [первичного ключа объекта](fo_primary-keys-objects.html) (такая строка формируется при изменении детейла или мастера). Доступно два режима отображения этих строчек: они совсем не отображаются или они скрываются в древовидную структуру (второй вариант был реализован в [старой версии аудита](efs_audit.html)). По умолчанию реализуется первый вариант, но это можно изменить следующей инициализацией: ```csharp -AuditService.Current.ShowPrimaryKey = true; +AuditService.Current.ShowPrimaryKey = true; // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. ``` ## Объектноориентированные формы аудита @@ -71,7 +71,7 @@ AuditService.Current.ShowPrimaryKey = true; Чтобы отключить отображение записей, содержащих [первичные ключи](fo_primary-keys-objects.html) [мастеров](fd_master-association.html) и [детейлов](fo_detail-associations-properties.html), можно выполнить следующую настройку: ```csharp -AuditService.Current.ShowPrimaryKey = false; +AuditService.Current.ShowPrimaryKey = false; // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. ``` Если AuditService.Current.ShowPrimaryKey имеет значение true, то список изменений полей отображается [в виде иерархии](fa_wolv-hierarhy.html) аналогично тому, как это сделано в записеориентированных формах аудита. diff --git a/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.en.md b/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.en.md index 255035961..7d7a52b4d 100644 --- a/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.en.md +++ b/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.en.md @@ -1,21 +1,21 @@ ---- -title: CaseberryMembershipProvider -sidebar: flexberry-aspnet_sidebar -keywords: Flexberry ASP-NET Flexberry Security -toc: true -permalink: en/fa_membership-provider.html -lang: en -autotranslated: true -hash: fa61a7df84814149abd6869726115f1fd4c77aefdecc9ee266fd6ba554220107 ---- +--- +title: CaseberryMembershipProvider +sidebar: flexberry-aspnet_sidebar +keywords: Flexberry ASP-NET Flexberry Security +toc: true +permalink: en/fa_membership-provider.html +lang: en +autotranslated: true +hash: fa61a7df84814149abd6869726115f1fd4c77aefdecc9ee266fd6ba554220107 +--- -## the credentials for web applications +## the credentials for web applications -For web applications developed a special `MembershipProvider` which you can check the [powers](efs_right-manager-module.html) in the database of office without the presence of AzManBridgeService. +For web applications developed a special `MembershipProvider` which you can check the [powers](efs_right-manager-module.html) in the database of office without the presence of AzManBridgeService. -## Connection +## Connection -Connect as follows: +Connect as follows: ``` xml @@ -51,44 +51,44 @@ Connect as follows: -``` - -`CaseberryMembershipProvider ` is in the Assembly `CheckingLibrary.dll` -To the authority were checked, the node requires the following assemblies: - -* Security(Objects) -* Security(BusinessServers) -* Repository -* Microsoft.Practices.Unity -* LogService -* log4net -* IIS.Audit(Objects) -* IIS.Audit(BusinessServers) -* AppSettingsService -* CheckingLibrary -* ExternalLangDef -* ICSSoft.STORMNET.AzManBridge -* ICSSoft.STORMNET.Business -* ICSSoft.STORMNET.Business.MSSQLDataService -* ICSSoft.STORMNET.Business.OracleDataService -* ICSSoft.STORMNET.Collections -* ICSSoft.STORMNET.DataObject -* ICSSoft.STORMNET.FunctionalLanguage -* ICSSoft.STORMNET.RightManager -* ICSSoft.STORMNET.Tools -* ICSSoft.STORMNET.UserDataTypes -* ICSSoft.STORMNET.Web.Tools - -### features of setting the connection string - -Work with the connection string to the database of the authority is as follows: - -* If the connection string is set with the name `CaseberrySecurity`, the connection string to the database authority is used. -* If the connection string `CaseberrySecurity` is not specified, it looks for a connection string named `CustomizationStrings_applicationname`; that is, if you specified that `applicationName="SLAuthSample"`, the name of the connection string must be in the form `CustomizationStrings_SLAuthsample`. - -## edit Form of authority in WEB - -In Flexberry ASP.NET there are forms for editing permissions which are in the folder: /forms/Security +``` + +`CaseberryMembershipProvider ` is in the Assembly `CheckingLibrary.dll` +To the authority were checked, the node requires the following assemblies: + +* Security(Objects) +* Security(BusinessServers) +* Repository +* Microsoft.Practices.Unity +* LogService +* log4net +* IIS.Audit(Objects) +* IIS.Audit(BusinessServers) +* AppSettingsService +* CheckingLibrary +* ICSSoft.STORMNET.Business.ExternalLangDef +* ICSSoft.STORMNET.AzManBridge +* ICSSoft.STORMNET.Business +* ICSSoft.STORMNET.Business.MSSQLDataService +* ICSSoft.STORMNET.Business.OracleDataService +* ICSSoft.STORMNET.Collections +* ICSSoft.STORMNET.DataObject +* ICSSoft.STORMNET.FunctionalLanguage +* ICSSoft.STORMNET.RightManager +* ICSSoft.STORMNET.Tools +* ICSSoft.STORMNET.UserDataTypes +* ICSSoft.STORMNET.Web.Tools + +### features of setting the connection string + +Work with the connection string to the database of the authority is as follows: + +* If the connection string is set with the name `CaseberrySecurity`, the connection string to the database authority is used. +* If the connection string `CaseberrySecurity` is not specified, it looks for a connection string named `CustomizationStrings_applicationname`; that is, if you specified that `applicationName="SLAuthSample"`, the name of the connection string must be in the form `CustomizationStrings_SLAuthsample`. + +## edit Form of authority in WEB + +In Flexberry ASP.NET there are forms for editing permissions which are in the folder: /forms/Security diff --git a/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.ru.md b/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.ru.md index 82f720c88..59561e65f 100644 --- a/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.ru.md +++ b/pages/products/flexberry-aspnet/subsystems/security/fa_membership-provider.ru.md @@ -1,5 +1,5 @@ --- -title: CaseberryMembershipProvider +title: CaseberryMembershipProvider sidebar: flexberry-aspnet_sidebar keywords: Flexberry ASP-NET, Flexberry Security toc: true @@ -64,7 +64,7 @@ lang: ru * IIS.Аудит(BusinessServers) * AppSettingsService * CheckingLibrary -* ExternalLangDef +* ICSSoft.STORMNET.Business.ExternalLangDef * ICSSoft.STORMNET.AzManBridge * ICSSoft.STORMNET.Business * ICSSoft.STORMNET.Business.MSSQLDataService diff --git a/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.en.md b/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.en.md index efb6ca1c5..3934bdb75 100644 --- a/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.en.md +++ b/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.en.md @@ -69,7 +69,7 @@ Example query: ``` ##### In the query using LCS ```c# - var ldef = ExternalLangDef.LanguageDef; + var ldef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Map), new View(gisView, typeof (Map))); lcs.LimitFunction = ldef.GetFunction(ldef.funcGeoIntersects, new VariableDef(ldef.GeographyType, "BoundingBox"), geo); diff --git a/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.ru.md b/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.ru.md index 8b0ce3694..5a470a72d 100644 --- a/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.ru.md +++ b/pages/products/flexberry-gis/services/gis-odata-service/gos_gis-odata-service.ru.md @@ -1,75 +1,75 @@ ---- -title: gis-odata-service -keywords: ember -sidebar: flexberry-gis_sidebar -toc: false -permalink: ru/gos_gis-odata-service.html -folder: products/flexberry-gis/ -lang: ru ---- - -### Особенности настройки OData-сервиса для ГИС-приложений - -##### Перед использованием необходимо скачать проекты с github: -[https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisPostgresDataService](https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisPostgresDataService) и -[https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisMSSQLDataService](https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisMSSQLDataService) или загрузить сборки с nuget.org [NewPlatform.Flexberry.ORM.GisPostgresDataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.GisPostgresDataService) и [NewPlatform.Flexberry.ORM.GisMSSQLDataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.GisMSSQLDataService). - -##### После успешной компиляции подключить созданные сборки к проекту. Требуется также версия ODataService не ниже 2.0.1-alpha01. Её можно загрузить с nuget.org [NewPlatform.Flexberry.ORM.ODataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.ODataService/2.0.1-alpha01). - -##### Необходимо изменить файл `Web.config`, отредактировав соответствующую строку таким образом для MSSQL сервер: -```xml - -... - -... - -``` -или для PostgreSQL сервер: -```xml - -... - -... - -``` -### Типы данных -##### MSSQL сервер -Поле в таблице для MSSQL сервера должна иметь тип `Geography` -##### PostgreSQL сервер -Поле в таблице для PostgreSQL сервера должна иметь тип `Geography` -##### .Net -Тип свойства в классе наследуемом от `DataObject` должен быть `Microsoft.Spatial.Geography` - -### Использование -##### В запросе к ODataService -Фильтрация объектов данных в опции запроса $filter возможна с использованием пользовательской функции `geo.intersects(geography1=geo1, geography2=geo2)` в OData, где "geo1" и "geo2" могут быть как полями объектов данных типа Edm.Geography, так и географически привязанными геометриями заданными в формате EWKT, например так: `geo.intersects(geography1=boundingBox, geography2=geography'SRID=<Код используемой системы координат>;POLYGON(<Координаты полигона>)')`, где `geography` - метод для преобразования строки с координатами в формате EWKT в тип Edm.Geography. - -Пример запроса: -`http://localhost/odata/КлассСМножествомТиповs?$filter=PropertyInt eq 5 and geo.intersects(geography1=PropertyGeography, geography2=geography'SRID=4326;POINT(3 3)')`. - -##### В запросе к LINQProvider -```c# - Geography geo = "POINT(3 3)".CreateGeography(); - ViewAttribute gisView = new ViewAttribute("gisView", new string[] { - "Name as \'Наименование\'", - "Description as \'Описание\'", - "KeyWords as \'Ключевые слова\'", - "Lat as \'Широта\'", - "Lng as \'Долгота\'", - "Zoom as \'Зум\'", - "Public as \'Общая\'", - "Scale as \'Масштаб\'", - "CoordinateReferenceSystem as \'Система координат\'", - "BoundingBox as \'Граница\'"}); - list = ds.Query(new View(gisView, typeof(Map))).Where(d => d.BoundingBox.GeoIntersects(geo)).ToList(); -``` -##### В запросе с использованием LCS -```c# - var ldef = ExternalLangDef.LanguageDef; - var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Map), new View(gisView, typeof (Map))); - lcs.LimitFunction = - ldef.GetFunction(ldef.funcGeoIntersects, new VariableDef(ldef.GeographyType, "BoundingBox"), geo); - list = ds.LoadObjects(lcs); -``` +--- +title: gis-odata-service +keywords: ember +sidebar: flexberry-gis_sidebar +toc: false +permalink: ru/gos_gis-odata-service.html +folder: products/flexberry-gis/ +lang: ru +--- + +### Особенности настройки OData-сервиса для ГИС-приложений + +##### Перед использованием необходимо скачать проекты с github: +[https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisPostgresDataService](https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisPostgresDataService) и +[https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisMSSQLDataService](https://github.com/Flexberry/NewPlatform.Flexberry.ORM.GisMSSQLDataService) или загрузить сборки с nuget.org [NewPlatform.Flexberry.ORM.GisPostgresDataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.GisPostgresDataService) и [NewPlatform.Flexberry.ORM.GisMSSQLDataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.GisMSSQLDataService). + +##### После успешной компиляции подключить созданные сборки к проекту. Требуется также версия ODataService не ниже 2.0.1-alpha01. Её можно загрузить с nuget.org [NewPlatform.Flexberry.ORM.ODataService](https://www.nuget.org/packages/NewPlatform.Flexberry.ORM.ODataService/2.0.1-alpha01). + +##### Необходимо изменить файл `Web.config`, отредактировав соответствующую строку таким образом для MSSQL сервер: +```xml + +... + +... + +``` +или для PostgreSQL сервер: +```xml + +... + +... + +``` +### Типы данных +##### MSSQL сервер +Поле в таблице для MSSQL сервера должна иметь тип `Geography` +##### PostgreSQL сервер +Поле в таблице для PostgreSQL сервера должна иметь тип `Geography` +##### .Net +Тип свойства в классе наследуемом от `DataObject` должен быть `Microsoft.Spatial.Geography` + +### Использование +##### В запросе к ODataService +Фильтрация объектов данных в опции запроса $filter возможна с использованием пользовательской функции `geo.intersects(geography1=geo1, geography2=geo2)` в OData, где "geo1" и "geo2" могут быть как полями объектов данных типа Edm.Geography, так и географически привязанными геометриями заданными в формате EWKT, например так: `geo.intersects(geography1=boundingBox, geography2=geography'SRID=<Код используемой системы координат>;POLYGON(<Координаты полигона>)')`, где `geography` - метод для преобразования строки с координатами в формате EWKT в тип Edm.Geography. + +Пример запроса: +`http://localhost/odata/КлассСМножествомТиповs?$filter=PropertyInt eq 5 and geo.intersects(geography1=PropertyGeography, geography2=geography'SRID=4326;POINT(3 3)')`. + +##### В запросе к LINQProvider +```c# + Geography geo = "POINT(3 3)".CreateGeography(); + ViewAttribute gisView = new ViewAttribute("gisView", new string[] { + "Name as \'Наименование\'", + "Description as \'Описание\'", + "KeyWords as \'Ключевые слова\'", + "Lat as \'Широта\'", + "Lng as \'Долгота\'", + "Zoom as \'Зум\'", + "Public as \'Общая\'", + "Scale as \'Масштаб\'", + "CoordinateReferenceSystem as \'Система координат\'", + "BoundingBox as \'Граница\'"}); + list = ds.Query(new View(gisView, typeof(Map))).Where(d => d.BoundingBox.GeoIntersects(geo)).ToList(); +``` +##### В запросе с использованием LCS +```c# + var ldef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). + var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Map), new View(gisView, typeof (Map))); + lcs.LimitFunction = + ldef.GetFunction(ldef.funcGeoIntersects, new VariableDef(ldef.GeographyType, "BoundingBox"), geo); + list = ds.LoadObjects(lcs); +``` diff --git a/pages/products/flexberry-orm/additional-features/fo_additional-loading.en.md b/pages/products/flexberry-orm/additional-features/fo_additional-loading.en.md index 6f69ef18d..0c81d175e 100644 --- a/pages/products/flexberry-orm/additional-features/fo_additional-loading.en.md +++ b/pages/products/flexberry-orm/additional-features/fo_additional-loading.en.md @@ -56,7 +56,7 @@ Thus it is necessary to temporarily disable the re-initialization of the copy of ``` csharp dobj.DisableInitDataCopy(); // disallow copy initialization data -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // dochitcu data object +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // DataServiceProvider is deprecated; inject IDataService instead dobj.EnableInitDataCopy();// return the initialized copy of the data dobj.GetStatus();//To the object status was calculated by modified properties relative to copies of the data. ``` @@ -67,7 +67,7 @@ This option applies only to the case when pogruzheny object is read-only and wil ``` csharp dobj.DisableInitDataCopy(); // disallow copy initialization data -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // dochitcu data object +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // DataServiceProvider is deprecated; inject IDataService instead // manually updated the internal copy of the data ТипОбъекта внутренКопия = dobj.GetDataCopy(); @@ -87,7 +87,7 @@ Alternatively, the reload data is create a separate instance of the same type wi ТипОбъекта dobj_forLoading = new ТипОбъекта(); dobj_forLoading.SetExistingPrimaryKey(dobj.__PrimaryKey); // view is required view. Its composition depends on the task. - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj_forLoading); + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj_forLoading); // DataServiceProvider is deprecated; inject IDataService instead ``` {% include note.html content="If you call a method `LoadObject` not explicitly specify a [view](fd_view-definition.html), will be deducted all private object fields and references to the wizard without their own field masters. Detaily object to be deducted **will**." %} @@ -95,7 +95,7 @@ Alternatively, the reload data is create a separate instance of the same type wi To read the object thus, it is necessary to use a method overload without a parameter `LoadObject` type `View`. For example, suitable for the simplest overload: ```csharp -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(dobj_forLoading); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(dobj_forLoading); // DataServiceProvider is deprecated; inject IDataService instead ``` In this case, the object `dobj_forLoading` also do not persist in the database. It should be understood that if the contact object has changed properties (status `Altered`), in `dobj_forLoading` they will not get, as yet not saved to the database. In practice, the logic should not depend on this factor, as gecitkoy dynamically determines the composition of the properties that you want to reload, and the altered properties (with proper verification) shall not be taken into account: diff --git a/pages/products/flexberry-orm/additional-features/fo_additional-loading.ru.md b/pages/products/flexberry-orm/additional-features/fo_additional-loading.ru.md index 9994bec73..c9f65f7ce 100644 --- a/pages/products/flexberry-orm/additional-features/fo_additional-loading.ru.md +++ b/pages/products/flexberry-orm/additional-features/fo_additional-loading.ru.md @@ -55,9 +55,10 @@ virtual public void LoadObject( ``` csharp dobj.DisableInitDataCopy(); // запрещаем инициализацию копии данных ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // дочитка объекта данных -dobj.EnableInitDataCopy();// возвращаем инициализацию копии данных +// DataServiceProvider устарел; вместо него используйте внедрение зависимостей +dobj.EnableInitDataCopy();// возвращаем инициализацию копии данных dobj.GetStatus();//Для того чтобы статус объекта был вычислен по изменённым свойствам относительно копии данных. -``` +``` Важно понимать что после дочитки [статус объекта данных](fo_object-status.html) будет установлен в `UnAltered`, поэтому, если планируется дальнейшее обновление объекта в БД, то не забудьте вызвать `dobj.GetStatus()`, что приведёт к перевычислению статуса по изменённым свойствам относительно [копии данных](fo_data-object-copy.html). @@ -66,17 +67,18 @@ dobj.GetStatus();//Для того чтобы статус объекта был ``` csharp dobj.DisableInitDataCopy(); // запрещаем инициализацию копии данных ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj, false, false); // дочитка объекта данных +// DataServiceProvider устарел; вместо него используйте внедрение зависимостей // вручную обновляем внутреннюю копию данных ТипОбъекта внутренКопия = dobj.GetDataCopy(); внутренКопия.Поле1 = dobj.Поле1; внутренКопия.Поле2 = dobj.Поле2; //... - + внутренКопия.ПолеN = dobj.ПолеN; dobj.EnableInitDataCopy();// возвращаем инициализацию копии данных -``` +``` Альтернативным вариантом догрузки данных является создания отдельного экземпляра того же типа с таким же [первичным ключом](fo_primary-keys-objects.html) и вычитка по необходимому [представлению](fd_view-definition.html). При этом [представление](fd_view-definition.html) может быть полное или содержать только те атрибуты, которые будут использоваться в дальнейшем: @@ -85,7 +87,7 @@ dobj.EnableInitDataCopy();// возвращаем инициализацию к ТипОбъекта dobj_forLoading = new ТипОбъекта(); dobj_forLoading.SetExistingPrimaryKey(dobj.__PrimaryKey); // view - требуемое представление. Его состав зависит от задачи. - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj_forLoading); + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(view, dobj_forLoading); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей ``` {% include note.html content="Если при вызове метода `LoadObject` явно не указать [представление](fd_view-definition.html), то будут вычитываться все собственные поля объекта и ссылки на мастера без собственных полей мастеров. При этом детейлы объекта вычитываться **не будут**." %} @@ -93,7 +95,7 @@ dobj.EnableInitDataCopy();// возвращаем инициализацию к Чтобы дочитать объект таким образом, необходимо использовать перегрузку метода `LoadObject` без параметра типа `View`. К примеру, подойдет самая простая перегрузка: ```csharp -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(dobj_forLoading); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(dobj_forLoading); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей ``` В этом случае объект `dobj_forLoading` также не предназначен для сохранения в базу данных. При этом необходимо понимать, что если объект dobj имеет изменённые свойства (статус `Altered`), то в `dobj_forLoading` они не попадут, так как ещё не сохранены в базу данных. На практике логика не должна зависеть от этого фактора, так как перед дочиткой динамически определяется состав свойств, которые требуется догрузить, при этом изменённые свойства (при правильной проверке) не должны учитываться: @@ -130,7 +132,7 @@ if (viewДочитки.Properties.Length > 0) ``` csharp /// -/// Метод для дочитки объекта данных. Загруженные ранее свойства не затираются, изменённые свойства не затираются. Подменяются поштучно свойства копии данных. +/// Метод для дочитки объекта данных. Загруженные ранее свойства не затираются, изменённые свойства не затираются. Подменяются поштучно свойства копии данных. /// /// представление /// бъект данных, который требуется загрузить @@ -143,7 +145,7 @@ DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache ### Дочитка собственных свойств -* Все собственные свойства обновляются только если не были загружены ранее. +* Все собственные свойства обновляются только если не были загружены ранее. #### Копия данных @@ -156,7 +158,7 @@ DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache * Если мастер не был вычитан ранее, то он будет зачитан со всеми его мастерами * Если мастер уже был вычитан, то будут обновлены его свойства по общему принципу -* **Если мастер был зачитан ранее, но был заменён на другой, то будет зачитан новый объект** +* **Если мастер был зачитан ранее, но был заменён на другой, то будет зачитан новый объект** * При дочитке мастер проставляется в LoadedProperties даже если явно не был указан в представлении предка и в БД его нет (изменена [стандартная логика](fo_definition-loaded-properties.html)). Мастер не будет указан в LoadedProperties только если LoadingState объекта: `LoadingState.NotLoaded` ##### Копия данных @@ -166,4 +168,4 @@ DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache #### Дочитка детейлов * Если детейл не участвовал в loadedProperties, то он зачитывается отдельным массивом и присваивается -* Если детейл был загружен, то производится поэлементное слияние. Объекты, которые не были найдены в коллекции, но были загружены из БД будут добавлены \ No newline at end of file +* Если детейл был загружен, то производится поэлементное слияние. Объекты, которые не были найдены в коллекции, но были загружены из БД будут добавлены diff --git a/pages/products/flexberry-orm/additional-features/fo_asynchronous_requests_in_orm.ru.md b/pages/products/flexberry-orm/additional-features/fo_asynchronous_requests_in_orm.ru.md index 2d206c535..00ece159b 100644 --- a/pages/products/flexberry-orm/additional-features/fo_asynchronous_requests_in_orm.ru.md +++ b/pages/products/flexberry-orm/additional-features/fo_asynchronous_requests_in_orm.ru.md @@ -1,97 +1,97 @@ ---- -title: Асинхронные запросы в ORM -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, запрос, асинхронный, загрузка данных -summary: Особенности работы и используемые параметры при ассинхронной загрузке данных -toc: true -permalink: ru/fo_asynchronous_requests_in_orm.html -lang: ru ---- - -В [ORM](fo_flexberry-orm.html) существует возможность загружать данные в асинхронном режиме (async/await). [SQLDataService](fo_data-service.html) реализует интерфейс `IAsyncDataService`, который описывает асинхронные методы загрузки. - -### Асинхронные методы - -| Метод | Описание | Параметры | -| -------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------- | -| GetObjectsCountAsync | Загрузить количество объектов | `LoadingCustomizationStruct` - запрос LCS | -| LoadObjectAsync | Загрузка одного объекта данных | [DataObject](fo_data-object.html) - объект, который нужно загрузить. `View` - представление для загрузки. | -| LoadObjectsAsync | Загрузка нескольких объектов данных | `DataObject[]` - массив объектов, которые нужно загрузить. `View` - представление для загрузки. | -| UpdateObjectAsync | Сохранение объекта данных | `DataObject` - объект, который нужно сохранить. | -| UpdateObjectsAsync | Сохранение нескольких объектов данных | `DataObject[]`` - массив объектов, который нужно сохранить. | - -__Дополнительные параметры__ - -- `clearDataObject` (для загрузки) - очищать объект (`DataObject.Clear`) перед вычиткой (по умолчанию `true`); -- `alwaysThrowException` (для обновления) - сразу же останавливать метод при возникновении ошибки (если `false` - будет произведена попытка выполнить часть запросов несмотря на ошибки; по умолчанию `false`); -- `dataObjectCache` (для загрузки и обновления) - по умолчанию для каждого запроса используется отдельный кеш объектов, но можно передать свой кеш (например, чтобы кешировать объекты между несколькими запросами). - -### Особенности работы - -Асинхронные методы изменяют переданные в метод экземпляры объектов, т.е. работают с объектами как с mutable object. Это требует особого внимания при работе с объектами до завершения операций загрузки/обновления (состояние объектов может измениться). Во избежание ошибок, следует использовать `await` или `Task.Wait` до того, как будет продолжена работа с объектом (либо клонировать исходный объект). - -### Примеры использования - -#### Загрузка объекта данных по ключу - -```csharp -using ICSSoft.STORMNET.Business; -var DS = DataServiceProvider.DataService as SQLDataService; - -// объект для загрузки -var userToLoad = new Пользователь(); -userToLoad.SetExistObjectPrimaryKey(user1.__PrimaryKey); //указываем ключ существующего объекта - -// поля для загрузки: -var view = new View { DefineClassType = typeof(Пользователь) }; -view.AddProperties( - Information.ExtractPropertyPath<Пользователь>(x => x.ФИО), - Information.ExtractPropertyPath<Пользователь>(x => x.ДатаРегистрации)); - -await DS.LoadObjectAsync(userToLoad, view); //обновляется объект userToLoad (догружаются указанные поля) -``` - -#### Загрузка нескольких объектов данных с помощью LCS - -```csharp -var lcsDateAfter2000 = LoadingCustomizationStruct.GetSimpleStruct(typeof(Пользователь), view); - -lcsDateAfter2000.LimitFunction = FunctionBuilder.BuildGreaterOrEqual<Пользователь>(x => x.ДатаРегистрации, new System.DateTime(2020, 01, 01)); // дата регистрации >= 01.01.2020 - -var loadedObjects = (await ds.LoadObjectsAsync(lcsDateAfter2000)).Cast<Пользователь>(); -``` - -Другие примеры можно посмотреть в тестах [DataServiceAsyncTests](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/blob/3ec3dc517469e6df519035d750a3da6c44a91bac/NewPlatform.Flexberry.ORM.IntegratedTests/ICSSoft.STORMNET.Business/DataServiceAsyncTests.cs) - -### Переход на асинхронный код - -1. В прикладных функциях заменить `IDataService` на `IAsyncDataService`, либо использовать реализацию (напр. `PostgresDataService` или `SQLDataService`). -2. Вызывать асинхронные методы датасервиса из асинхронного кода (с модификатором `async`): - -На текущий момент можно добавить модификатор `async`: -- для контроллеров WebApi в `ODataBackend`; -- для OData функций; -- для метода `Main` в консольных программах/сервисах (код сервиса рекомендуется также сделать асинхронным); -- для библиотек классов; - -Нельзя добавить модификатор `async`: -- для бизнес-серверов (OnUpdate/OnDelete/OnInsert); -- для методов класса `Startup.cs`; если вам все-же нужны асинхронные операции в `Startup.cs`, см. статью ["Асинхронный код в Startup ASP.NET Core: 4 способа обхода GetAwaiter().GetResult()"](https://habr.com/ru/company/dododev/blog/496300/) (решение №2 и №3). - -__Преимущества перехода__ - -1. Пропускная способность (throughput) асинхронного кода при нагрузке гораздо выше. Это особенно заметно, когда количество потоков, выполняемых одновременно, превышает thread pool (["Measuring performance for async vs sync code in ASP.NET Core"](https://stackoverflow.com/a/62919974)): - -```csharp -5000 sync calls 5546ms 35 threads -5000 async calls 29ms 35 threads -``` - -Прирост пропуской способности достигается за счёт освобождения потока при вызове `await`. Синхронный код (без async/await) под нагрузкой требует больше потоков (["Async vs Sync Benchmark (.NET)"](https://artemmikulich.medium.com/async-vs-sync-benchmark-net-f1e752a57755)), соответственно его пропускная способность под нагрузкой ниже. - -2. Код выполнится быстрее, если задействовать для задачи несколько потоков, работающих одновременно. В этом случае прирост к скорости будет приобретён ценой возросшей нагрузки на одну задачу. Прирост заметен только когда в thread pool есть свободные потоки (при невысокой нагрузке). -3. В UI приложениях (напр. [Windows Forms](fw_landing_page.html)) текущий поток может быть освобождён, и интерфейс не будет блокироваться ("замораживаться"). - -__Недостатки__ - -1. Сложность использования в синхронном коде. Асинхронный код можно вызывать через `Task.Run()`, но могут возникнуть проблемы (подробнее об этом в статье ["Avoid using Task.Run for long running work that blocks the thread"](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#avoid-using-taskrun-for-long-running-work-that-blocks-the-thread)). \ No newline at end of file +--- +title: Асинхронные запросы в ORM +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, запрос, асинхронный, загрузка данных +summary: Особенности работы и используемые параметры при ассинхронной загрузке данных +toc: true +permalink: ru/fo_asynchronous_requests_in_orm.html +lang: ru +--- + +В [ORM](fo_flexberry-orm.html) существует возможность загружать данные в асинхронном режиме (async/await). [SQLDataService](fo_data-service.html) реализует интерфейс `IAsyncDataService`, который описывает асинхронные методы загрузки. + +### Асинхронные методы + +| Метод | Описание | Параметры | +| -------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------- | +| GetObjectsCountAsync | Загрузить количество объектов | `LoadingCustomizationStruct` - запрос LCS | +| LoadObjectAsync | Загрузка одного объекта данных | [DataObject](fo_data-object.html) - объект, который нужно загрузить. `View` - представление для загрузки. | +| LoadObjectsAsync | Загрузка нескольких объектов данных | `DataObject[]` - массив объектов, которые нужно загрузить. `View` - представление для загрузки. | +| UpdateObjectAsync | Сохранение объекта данных | `DataObject` - объект, который нужно сохранить. | +| UpdateObjectsAsync | Сохранение нескольких объектов данных | `DataObject[]`` - массив объектов, который нужно сохранить. | + +__Дополнительные параметры__ + +- `clearDataObject` (для загрузки) - очищать объект (`DataObject.Clear`) перед вычиткой (по умолчанию `true`); +- `alwaysThrowException` (для обновления) - сразу же останавливать метод при возникновении ошибки (если `false` - будет произведена попытка выполнить часть запросов несмотря на ошибки; по умолчанию `false`); +- `dataObjectCache` (для загрузки и обновления) - по умолчанию для каждого запроса используется отдельный кеш объектов, но можно передать свой кеш (например, чтобы кешировать объекты между несколькими запросами). + +### Особенности работы + +Асинхронные методы изменяют переданные в метод экземпляры объектов, т.е. работают с объектами как с mutable object. Это требует особого внимания при работе с объектами до завершения операций загрузки/обновления (состояние объектов может измениться). Во избежание ошибок, следует использовать `await` или `Task.Wait` до того, как будет продолжена работа с объектом (либо клонировать исходный объект). + +### Примеры использования + +#### Загрузка объекта данных по ключу + +```csharp +using ICSSoft.STORMNET.Business; +var DS = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей + +// объект для загрузки +var userToLoad = new Пользователь(); +userToLoad.SetExistObjectPrimaryKey(user1.__PrimaryKey); //указываем ключ существующего объекта + +// поля для загрузки: +var view = new View { DefineClassType = typeof(Пользователь) }; +view.AddProperties( + Information.ExtractPropertyPath<Пользователь>(x => x.ФИО), + Information.ExtractPropertyPath<Пользователь>(x => x.ДатаРегистрации)); + +await DS.LoadObjectAsync(userToLoad, view); //обновляется объект userToLoad (догружаются указанные поля) +``` + +#### Загрузка нескольких объектов данных с помощью LCS + +```csharp +var lcsDateAfter2000 = LoadingCustomizationStruct.GetSimpleStruct(typeof(Пользователь), view); + +lcsDateAfter2000.LimitFunction = FunctionBuilder.BuildGreaterOrEqual<Пользователь>(x => x.ДатаРегистрации, new System.DateTime(2020, 01, 01)); // дата регистрации >= 01.01.2020 + +var loadedObjects = (await ds.LoadObjectsAsync(lcsDateAfter2000)).Cast<Пользователь>(); +``` + +Другие примеры можно посмотреть в тестах [DataServiceAsyncTests](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/blob/3ec3dc517469e6df519035d750a3da6c44a91bac/NewPlatform.Flexberry.ORM.IntegratedTests/ICSSoft.STORMNET.Business/DataServiceAsyncTests.cs) + +### Переход на асинхронный код + +1. В прикладных функциях заменить `IDataService` на `IAsyncDataService`, либо использовать реализацию (напр. `PostgresDataService` или `SQLDataService`). +2. Вызывать асинхронные методы датасервиса из асинхронного кода (с модификатором `async`): + +На текущий момент можно добавить модификатор `async`: +- для контроллеров WebApi в `ODataBackend`; +- для OData функций; +- для метода `Main` в консольных программах/сервисах (код сервиса рекомендуется также сделать асинхронным); +- для библиотек классов; + +Нельзя добавить модификатор `async`: +- для бизнес-серверов (OnUpdate/OnDelete/OnInsert); +- для методов класса `Startup.cs`; если вам все-же нужны асинхронные операции в `Startup.cs`, см. статью ["Асинхронный код в Startup ASP.NET Core: 4 способа обхода GetAwaiter().GetResult()"](https://habr.com/ru/company/dododev/blog/496300/) (решение №2 и №3). + +__Преимущества перехода__ + +1. Пропускная способность (throughput) асинхронного кода при нагрузке гораздо выше. Это особенно заметно, когда количество потоков, выполняемых одновременно, превышает thread pool (["Measuring performance for async vs sync code in ASP.NET Core"](https://stackoverflow.com/a/62919974)): + +```csharp +5000 sync calls 5546ms 35 threads +5000 async calls 29ms 35 threads +``` + +Прирост пропуской способности достигается за счёт освобождения потока при вызове `await`. Синхронный код (без async/await) под нагрузкой требует больше потоков (["Async vs Sync Benchmark (.NET)"](https://artemmikulich.medium.com/async-vs-sync-benchmark-net-f1e752a57755)), соответственно его пропускная способность под нагрузкой ниже. + +2. Код выполнится быстрее, если задействовать для задачи несколько потоков, работающих одновременно. В этом случае прирост к скорости будет приобретён ценой возросшей нагрузки на одну задачу. Прирост заметен только когда в thread pool есть свободные потоки (при невысокой нагрузке). +3. В UI приложениях (напр. [Windows Forms](fw_landing_page.html)) текущий поток может быть освобождён, и интерфейс не будет блокироваться ("замораживаться"). + +__Недостатки__ + +1. Сложность использования в синхронном коде. Асинхронный код можно вызывать через `Task.Run()`, но могут возникнуть проблемы (подробнее об этом в статье ["Avoid using Task.Run for long running work that blocks the thread"](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#avoid-using-taskrun-for-long-running-work-that-blocks-the-thread)). diff --git a/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.en.md b/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.en.md index e78dc9f3c..0d97d34b9 100644 --- a/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.en.md +++ b/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.en.md @@ -1,39 +1,39 @@ ---- -title: Sample user names for the structures in the database -sidebar: flexberry-orm_sidebar -keywords: Public, example, database, Flexberry Desinger, charts -summary: the Job names for the database -toc: true -permalink: en/fo_custom-naming-db-structures.html -lang: en -autotranslated: true -hash: e52ecaef7a417a423caa333e40333be80f2442c529ae53fc973d815896129c1b ---- +--- +title: Sample user names for the structures in the database +sidebar: flexberry-orm_sidebar +keywords: Public, example, database, Flexberry Desinger, charts +summary: the Job names for the database +toc: true +permalink: en/fo_custom-naming-db-structures.html +lang: en +autotranslated: true +hash: e52ecaef7a417a423caa333e40333be80f2442c529ae53fc973d815896129c1b +--- -There are 2 ways for [definition name](fo_storing-data-objects.html): +There are 2 ways for [definition name](fo_storing-data-objects.html): -* in Flexberry Desinger -* C# code using attributes. +* in Flexberry Desinger +* C# code using attributes. -If you choose the first path, then Flexberry Desinger will generate appropriate names automatically. +If you choose the first path, then Flexberry Desinger will generate appropriate names automatically. -You can relate data objects and attributes with any name, DB-structure](fo_storing-data-objects.html): +You can relate data objects and attributes with any name, DB-structure](fo_storing-data-objects.html): -* The table name for a class (attribute [ClassStorage](fd_data-classes.html) class); -* The column name for the attribute (attribute [PropertyStorage](fo_attributes-class-data.html) for the property); -* The name of the column [primary key (Primary key)](fo_primary-keys-objects.html) for the identifier of the object data (attribute [PrimaryKeyStorage](fd_data-classes.html) class); -* Column name foreign key (Foreign key) to dependencies of the master (attribute [PropertyStorage](fd_master-association.html) for the property); +* The table name for a class (attribute [ClassStorage](fd_data-classes.html) class); +* The column name for the attribute (attribute [PropertyStorage](fo_attributes-class-data.html) for the property); +* The name of the column [primary key (Primary key)](fo_primary-keys-objects.html) for the identifier of the object data (attribute [PrimaryKeyStorage](fd_data-classes.html) class); +* Column name foreign key (Foreign key) to dependencies of the master (attribute [PropertyStorage](fd_master-association.html) for the property); -For example, figure `DB structures custom naming`: +For example, figure `DB structures custom naming`: -* `CustomDBOwnClass` refers to table `CustomDBOwn`; -* `CustomDBOwnClass.CustomOwnAttribute` refers to the column in the table `CustomOwn` `CustomDBOwn`; -* `CustomDBMasterClass` refers to table `CustomDBMaster`; -* `CustomDBMasterClass.CustomMasterAttribute` refers to the column in the table CustomMaster `CustomDBOwnCustomDBMaster`; -* Attitude `CustomDBOwnClass` to `CustomDBMasterClass` determined `CustomDBMaster` column in the table `CustomDBOwnClass`; -* The IDs of both classes are `pkey` column in the relevant tables `tables` +* `CustomDBOwnClass` refers to table `CustomDBOwn`; +* `CustomDBOwnClass.CustomOwnAttribute` refers to the column in the table `CustomOwn` `CustomDBOwn`; +* `CustomDBMasterClass` refers to table `CustomDBMaster`; +* `CustomDBMasterClass.CustomMasterAttribute` refers to the column in the table CustomMaster `CustomDBOwnCustomDBMaster`; +* Attitude `CustomDBOwnClass` to `CustomDBMasterClass` determined `CustomDBMaster` column in the table `CustomDBOwnClass`; +* The IDs of both classes are `pkey` column in the relevant tables `tables` -Simply create objects and save them. +Simply create objects and save them. ```csharp CustomDBOwnClass cdbo = new CustomDBOwnClass(); @@ -42,14 +42,14 @@ cdbm.CustomMasterAttribute = new RandomStringGenerator().Generate(200); cdbo.CustomDBMasterClass = cdbm; cdbo.CustomOwnAttribute = new RandomStringGenerator().Generate(200); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead ICSSoft.STORMNET.DataObject[] objstoupd = new ICSSoft.STORMNET.DataObject[] { cdbo, cdbm }; dataService.UpdateObjects(ref objstoupd); Console.WriteLine("OK!"); -``` +``` -Full list of code examples Flexberry ORM is in ["code Examples"](fo_code-samples.html). +Full list of code examples Flexberry ORM is in ["code Examples"](fo_code-samples.html). diff --git a/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.ru.md b/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.ru.md index ecf5791fd..15c08e6b2 100644 --- a/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.ru.md +++ b/pages/products/flexberry-orm/additional-features/fo_custom-naming-db-structures.ru.md @@ -40,7 +40,7 @@ cdbm.CustomMasterAttribute = new RandomStringGenerator().Generate(200); cdbo.CustomDBMasterClass = cdbm; cdbo.CustomOwnAttribute = new RandomStringGenerator().Generate(200); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей ICSSoft.STORMNET.DataObject[] objstoupd = new ICSSoft.STORMNET.DataObject[] { cdbo, cdbm }; dataService.UpdateObjects(ref objstoupd); diff --git a/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.en.md b/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.en.md index 824c08414..2757f4093 100644 --- a/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.en.md +++ b/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.en.md @@ -1,37 +1,34 @@ ---- -title: Libraries Flexberry ORM -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, libraries, assemblies, nuget -summary: List of Flexberry ORM libraries, available via NuGet -toc: true -permalink: en/fo_flexberry-orm-libraries.html -lang: en -autotranslated: true -hash: adf0d68f5a3ca4fe75ae118057437766060632e374f0a276044ac6897bf63ee2 ---- +--- +title: Libraries Flexberry ORM +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, libraries, assemblies, nuget +summary: List of Flexberry ORM libraries, available via NuGet +toc: true +permalink: en/fo_flexberry-orm-libraries.html +lang: en +autotranslated: true +hash: adf0d68f5a3ca4fe75ae118057437766060632e374f0a276044ac6897bf63ee2 +--- -The list of libraries that contain the Runtime components [Flexberry ORM](fo_flexberry-orm.html): +The list of libraries that contain the Runtime components [Flexberry ORM](fo_flexberry-orm.html): -* **ChangesToSqlBTMonitor.dll** a library containing classes for working [service record SQL-scripts change data](fo_changes-sql-bt-monitor.html). -* **ExternalLangDef.dll** - the library that contains [language extension restrictions](fo_external-lang-def.html) for [constraint](fo_limit-function.html) on the dependent objects. -* **ICSSoft.STORMNET.BF.dll** -* **ICSSoft.STORMNET.Business.dll** a library containing base classes for organizations [see the structure of relational database tables to an object model](fo_data-service.html). -* **ICSSoft.STORMNET.Business.DRDataService.dll** a library containing classes for working [DRDataService](fo_dr-data-service.html). -* **ICSSoft.STORMNET.Business.LINQProvider.dll** - the library that contains the classes for LINQ support in [Flexberry ORM](fo_flexberry-orm.html). -* **ICSSoft.STORMNET.Business.LockService.dll** a library containing classes for working [service locks](fo_lock-service.html). -* **ICSSoft.STORMNET.Business.MSSQLDataService.dll** a library containing classes for [the display of the structure of relational tables in MS SQL Server (version 2005 and above) the object model](fo_data-service.html). -* **ICSSoft.STORMNET.Business.ODBCDataService.dll** a library containing classes for working [ODBCDataService](fo_odbc-data-service.html). -* **ICSSoft.STORMNET.Business.OracleDataService.dll** a library containing classes for working [OracleDataService](fo_oracle-data-service.html). -* **ICSSoft.STORMNET.Business.PostgresDataService.dll** a library containing classes for working [PostgresDataService](fo_postgres-data-service.html). -* **ICSSoft.STORMNET.Collections.dll** a library containing auxiliary base structure for organizing collections of objects. -* **ICSSoft.STORMNET.DataObject.dll** a library containing base classes for organizations [object model](fo_data-object.html), as well as basic utility methods for working with them. -* ICSSoft.STORMNET.Drawing.dll -* **ICSSoft.STORMNET.FunctionalLanguage.dll** - the library that contains the core classes for the operation of [the components of filters and limitations](fo_limitation.html). -* **ICSSoft.STORMNET.Tools.dll** - the library that contains common helper methods. -* **ICSSoft.STORMNET.UserDataTypes.dll** - the library, containing additionally certain types of data. -* **NewPlatform.Flexberry.Data.ODataService.dll** +* **ICSSoft.STORMNET.Business.ExternalLangDef.dll** - the library that contains [language extension restrictions](fo_external-lang-def.html) for [constraint](fo_limit-function.html) on the dependent objects. +* **ICSSoft.STORMNET.BF.dll** +* **ICSSoft.STORMNET.Business.dll** a library containing base classes for organizations [see the structure of relational database tables to an object model](fo_data-service.html), also classes for working [service record SQL-scripts change data](fo_changes-sql-bt-monitor.html). +* **ICSSoft.STORMNET.Business.LINQProvider.dll** - the library that contains the classes for LINQ support in [Flexberry ORM](fo_flexberry-orm.html). +* **ICSSoft.STORMNET.Business.LockService.dll** a library containing classes for working [service locks](fo_lock-service.html). +* **ICSSoft.STORMNET.Business.MSSQLDataService.dll** a library containing classes for [the display of the structure of relational tables in MS SQL Server (version 2005 and above) the object model](fo_data-service.html), and [DRDataService (Dirty Read)](fo_dr-data-service.html). +* **ICSSoft.STORMNET.Business.OracleDataService.dll** a library containing classes for working [OracleDataService](fo_oracle-data-service.html). +* **ICSSoft.STORMNET.Business.PostgresDataService.dll** a library containing classes for working [PostgresDataService](fo_postgres-data-service.html). +* **ICSSoft.STORMNET.Collections.dll** a library containing auxiliary base structure for organizing collections of objects. +* **ICSSoft.STORMNET.DataObject.dll** a library containing base classes for organizations [object model](fo_data-object.html), as well as basic utility methods for working with them. +* ICSSoft.STORMNET.Drawing.dll +* **ICSSoft.STORMNET.FunctionalLanguage.dll** - the library that contains the core classes for the operation of [the components of filters and limitations](fo_limitation.html). +* **ICSSoft.STORMNET.Tools.dll** - the library that contains common helper methods. +* **ICSSoft.STORMNET.UserDataTypes.dll** - the library, containing additionally certain types of data. +* **NewPlatform.Flexberry.Data.ODataService.dll** -{% include note.html content="Flexberry ORM is available for installation in the project via [NuGet package](https://www.nuget.org/packages/NewPlatform.Flexberry.The ORM)." %} +{% include note.html content="Flexberry ORM is available for installation in the project via [NuGet package](https://www.nuget.org/packages/NewPlatform.Flexberry.The ORM)." %} diff --git a/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.ru.md b/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.ru.md index b046730bf..6210e93b2 100644 --- a/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.ru.md +++ b/pages/products/flexberry-orm/additional-features/fo_flexberry-orm-libraries.ru.md @@ -10,17 +10,15 @@ lang: ru Список библиотек, содержащих Runtime-компоненты [Flexberry ORM](fo_flexberry-orm.html): -* **ChangesToSqlBTMonitor.dll** - библиотека, содержащая классы для работы [сервиса записи SQL-скриптов изменения данных](fo_changes-sql-bt-monitor.html). -* **ExternalLangDef.dll** - библиотека, содержащая [расширение языка ограничений](fo_external-lang-def.html) для [задания ограничений](fo_limit-function.html) на зависимые объекты. +* **ChangesToSqlBTMonitor.dll** - библиотека, содержащая +* **ICSSoft.STORMNET.Business.ExternalLangDef.dll** - библиотека, содержащая [расширение языка ограничений](fo_external-lang-def.html) для [задания ограничений](fo_limit-function.html) на зависимые объекты. * **ICSSoft.STORMNET.BF.dll** -* **ICSSoft.STORMNET.Business.dll** - библиотека, содержащая базовые классы для организации [отображения структуры реляционных таблиц БД на объектную модель](fo_data-service.html). -* **ICSSoft.STORMNET.Business.DRDataService.dll** - библиотека, содержащая классы для работы [DRDataService](fo_dr-data-service.html). +* **ICSSoft.STORMNET.Business.dll** - библиотека, содержащая базовые классы для организации [отображения структуры реляционных таблиц БД на объектную модель](fo_data-service.html), и классы для работы [сервиса записи SQL-скриптов изменения данных](fo_changes-sql-bt-monitor.html). * **ICSSoft.STORMNET.Business.LINQProvider.dll** - библиотека, содержащая классы для поддержки LINQ в [Flexberry ORM](fo_flexberry-orm.html). * **ICSSoft.STORMNET.Business.LockService.dll** - библиотека, содержащая классы для работы [сервиса блокировок](fo_lock-service.html). -* **ICSSoft.STORMNET.Business.MSSQLDataService.dll** - библиотека, содержащая классы для [организации отображения структуры реляционных таблиц MS SQL Server (версии 2005 и выше) на объектную модель](fo_data-service.html). -* **ICSSoft.STORMNET.Business.ODBCDataService.dll** - библиотека, содержащая классы для работы [ODBCDataService](fo_odbc-data-service.html). +* **ICSSoft.STORMNET.Business.MSSQLDataService.dll** - библиотека, содержащая классы для [организации отображения структуры реляционных таблиц MS SQL Server (версии 2005 и выше) на объектную модель](fo_data-service.html) и [DRDataService (Dirty Read - грязное чтение)](fo_dr-data-service.html). * **ICSSoft.STORMNET.Business.OracleDataService.dll** - библиотека, содержащая классы для работы [OracleDataService](fo_oracle-data-service.html). -* **ICSSoft.STORMNET.Business.PostgresDataService.dll** - библиотека, содержащая классы для работы [PostgresDataService](fo_postgres-data-service.html). +* **ICSSoft.STORMNET.Business.PostgresDataService.dll** - библиотека, содержащая классы для работы [PostgresDataService](fo_postgres-data-service.html). * **ICSSoft.STORMNET.Collections.dll** - библиотека, содержащая вспомогательные базовые структуры для организации коллекций объектов. * **ICSSoft.STORMNET.DataObject.dll** - библиотека, содержащая базовые классы для организации [объектной модели](fo_data-object.html), а также основные вспомогательные методы для работы с ними. * ICSSoft.STORMNET.Drawing.dll diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.en.md b/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.en.md index 4fd535918..7abc439d5 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.en.md @@ -11,6 +11,8 @@ hash: 4ca7c90ae5588bd49e22948ce037f8035f7cb8ccba998bb0cfed18a48194422b # AuditSetter +> AuditSetter is no more present in ORM v8.0. Use dependency injection to register IAuditService. + `AuditSetter` carries [initialization settings audit](efs_keep-and-use-audit-settings.html). The initialization is not necessarily performed by this class, it just contains the most successful initialization with default values. diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.ru.md b/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.ru.md index 724c6c898..94e512f4e 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditSetter.ru.md @@ -8,6 +8,7 @@ lang: ru --- # AuditSetter +> AuditSetter отсутствует в ORM v8.0. Необходимо самостоятельно регистрировать IAuditService через механизм внедрения зависимостей. `AuditSetter` осуществляет [инициализацию настроек аудита](efs_keep-and-use-audit-settings.html). diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.en.md b/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.en.md index 5d20de1de..dc554488f 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.en.md @@ -53,8 +53,8 @@ Since we don't know the result of the operation of forming the report, we expose You can now write data to the database audit: -``` - Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); +```csharp + Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); //AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService ``` Use the simplest overload `WriteCustomAuditOperation`, DataService are defined as standard for the application. @@ -84,7 +84,7 @@ finally AuditService.Current.RatifyAuditOperation( correct ? tExecutionVariant.Executed : tExecutionVariant.Failed, new List { auditOperationId.Value }, - false); + false); //AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService } ``` @@ -107,7 +107,7 @@ Now when I try to create the report in the audit database will be created corres }; // Writable surgery audit database and remember the ID of the created record - Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); + Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); //AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService var report = new Отчет(); bool correct = true; @@ -129,7 +129,7 @@ Now when I try to create the report in the audit database will be created corres AuditService.Current.RatifyAuditOperation( correct ? tExecutionVariant.Executed : tExecutionVariant.Failed, new List { auditOperationId.Value }, - false); + false); //AuditService.Current is removed in ORM v8.0. Use dependency injection instead to inject IAuditService } return report; diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.ru.md b/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.ru.md index 795324d8e..c722dcaaf 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditWebApiExample.ru.md @@ -51,8 +51,8 @@ var auditParams = new CustomAuditParameters Теперь можно записать данные в базу аудита: -``` - Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); +```csharp + Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. ``` Используем самую простую перегрузку метода `WriteCustomAuditOperation`, DataService определится как стандартный для приложения. @@ -82,7 +82,7 @@ finally AuditService.Current.RatifyAuditOperation( correct ? tExecutionVariant.Executed : tExecutionVariant.Failed, new List { auditOperationId.Value }, - false); + false); // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. } ``` @@ -105,7 +105,7 @@ finally }; // Записываем операцию аудита в базу и запоминаем ID созданной записи - Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); + Guid? auditOperationId = AuditService.Current.WriteCustomAuditOperation(auditParams, true); // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. var report = new Отчет(); bool correct = true; @@ -127,7 +127,7 @@ finally AuditService.Current.RatifyAuditOperation( correct ? tExecutionVariant.Executed : tExecutionVariant.Failed, new List { auditOperationId.Value }, - false); + false); // AuditService.Current удалён в ORM версии 8.0. Используйте внедрение зависимостей для инжекта IAuditService. } return report; diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.en.md b/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.en.md index 5a3ae86d2..d132d5f28 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.en.md @@ -41,12 +41,11 @@ And you need to add the initialization call using [Initial audit](efs_audit-setter.html). ``` -// *** Start programmer edit section *** (TestFS Main()) +// *** Start programmer edit section *** (TestFS Main()) ICSSoft.STORMNET.Windows.Forms.WinApplication.SetUICultureAsRussian(); - -// Initialize audit service -AuditSetter.InitAuditService(DataServiceProvider.DataService); -// *** End programmer edit section *** (TestFS Main()) +IUnityContainer container; // use dependency injection to get IUnityContainer; +var IAuditService = container.Resolve(); +// *** End programmer edit section *** (TestFS Main()) ``` # Connection assemblies diff --git a/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.ru.md b/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.ru.md index f28cfaf93..de82d2832 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_AuditWinExampleManual.ru.md @@ -1,5 +1,5 @@ --- -title: Пример подключения аудита к существующему Win-приложению без использования перегенерации проекта. +title: Пример подключения аудита к существующему Win-приложению без использования перегенерации проекта. sidebar: ember-flexberry-security_sidebar keywords: Flexberry Audit toc: true @@ -28,7 +28,7 @@ lang: ru ``` -А также +А также ```xml @@ -37,13 +37,11 @@ lang: ru # Подключение аудита в main необходимо добавить вызов инициализации с помощью [Инициализация аудита](efs_audit-setter.html). -``` - +```csharp // *** Start programmer edit section *** (TestFS Main()) ICSSoft.STORMNET.Windows.Forms.WinApplication.SetUICultureAsRussian(); - -// Инициализация сервиса аудита -AuditSetter.InitAuditService(DataServiceProvider.DataService); +IUnityContainer container; // контейнер необходимо получить через внедрение зависимостей; вместо IUnityContainer можно использовать IServiceProvider +var IAuditService = container.Resolve(); // *** End programmer edit section *** (TestFS Main()) ``` diff --git a/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.en.md b/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.en.md index 511010111..777dcd04c 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.en.md @@ -9,6 +9,8 @@ autotranslated: true hash: 1018e40e20836295016b5538417f8a1947e94bf8d0956a07990d8a919063f53d --- +> CheckAccessToAttribute is no more present in ORM v8.0. + # Rights attributes Flexberry Platform supports setting the properties of the data objects (attribute). Setting this right is made through specifying a custom expression in the attribute DataServiceExpression. The expression looks like the following: @@ -32,7 +34,7 @@ The value DeniedAccessValue should be recorded as it bolino to be recorded in th ```cs object deniedAccessValue; -if (!Information.CheckAccessToAttribute(this.GetType(), "Name", out deniedAccessValue)) +if (!Information.CheckAccessToAttribute(this.GetType(), "Name", out deniedAccessValue)) // CheckAccesToAttribute is no more present in ORM v8.0. return (string)deniedAccessValue; ``` diff --git a/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.ru.md b/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.ru.md index 2747fc349..dfcaa6bfe 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_CheckAccessToAttribute.ru.md @@ -7,6 +7,8 @@ permalink: ru/efs_check-access-to-attribute.html lang: ru --- +> CheckAccessToAttribute отсутствует в ORM начиная с версии 8.0. + # Права на атрибуты Flexberry Platform поддерживает настройку прав на свойства объектов данных (атрибут). Настройка этого вида прав производится через указание специального выражения в атрибуте DataServiceExpression. Выражение имеет вид следующий вид: @@ -21,7 +23,7 @@ Flexberry Platform поддерживает настройку прав на с # Порядок установки контроля прав на атрибуты 1. В консоли полномочий необходимо создать операции и настроить доступ пользователей к ним. -2. В Flexberry Tool добавить или отредактировать DataServiceExpression, добавив в него выражение настройки прав на атрибуты. +2. В Flexberry Tool добавить или отредактировать DataServiceExpression, добавив в него выражение настройки прав на атрибуты. Значение DeniedAccessValue должно быть записано так, как оно болжно быть записали в запросе SQL. В примере строковое – значит в одинарных кавычках. Если DeniedAccessValue уже есть, записываем рядом, для SQL server это комментарий. 3. При запуске приложения устанвить свойство RightManager.UseRightsOnAttribute = true. В web-приложении это можно сделать в Global.Application_Start. @@ -31,11 +33,11 @@ Flexberry Platform поддерживает настройку прав на с ```cs object deniedAccessValue; if (!Information.CheckAccessToAttribute(this.GetType(), "Название", out deniedAccessValue)) -return (string)deniedAccessValue; +return (string)deniedAccessValue; // CheckAccessToAttribute отсутствует в ORM начиная с версии 8.0. ``` # Права на мастеровые свойстваПри настройке прав на атрибуты, являющиеся ссылками на мастера, в качестве значения DeniedAccessValue необходимо указать ключ мастера, который будет присвоен свойству при отсутствии прав. Для таких целей рекомендуется завести специальный фиктивный мастер. ```cs [DataServiceExpression(typeof(ICSSoft.STORMNET.Business.MSSQLDataService), "/*Operation:ПросмотрАтрибутов;DeniedAccessValue:'00000000-0000-0000-0000-000000000000'*/")] -``` \ No newline at end of file +``` diff --git a/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.en.md b/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.en.md index adf29fea3..d741c140c 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.en.md @@ -1,56 +1,52 @@ ---- -title: Elements Flexberry Audit -sidebar: ember-flexberry-security_sidebar -keywords: Flexberry Audit -toc: true -permalink: en/efs_flexberry-audit-components.html -lang: en -autotranslated: true -hash: 3f5e5d666f018b38f0302a663a07d126c5e5f355837b71a3c61f8b04cace1829 ---- +--- +title: Elements Flexberry Audit +sidebar: ember-flexberry-security_sidebar +keywords: Flexberry Audit +toc: true +permalink: en/efs_flexberry-audit-components.html +lang: en +autotranslated: true +hash: 3f5e5d666f018b38f0302a663a07d126c5e5f355837b71a3c61f8b04cace1829 +--- -# AuditService -The application has a class `AuditService`. Through the class `AuditService` implemented API calls: -* the class that inherits from the interface [IAudit](i-audit.html), if the audit is not in a separate service. -* audit service `AuditWinService`. +# AuditService +The application has a class `AuditService`. Through the class `AuditService` implemented API calls: +* the class that inherits from the interface [IAudit](i-audit.html), if the audit is not in a separate service. +* audit service `AuditWinService`. -`AuditService` stores the application configuration audit, where they are loaded in the beginning of the application. +`AuditService` stores the application configuration audit, where they are loaded in the beginning of the application. -When performing potentially audited operations [service data](fo_sql-data-service.html) the application informs the class `AuditService` that: -* scans the existing configuration audit and decides on the need to implement audit records. -* if auditing is required, then an appropriate message is either `IAudit`, if there is no separate audit service or `AuditWinService` (waiting for a response will depend on the settings of the audit). +When performing potentially audited operations [service data](fo_sql-data-service.html) the application informs the class `AuditService` that: +* scans the existing configuration audit and decides on the need to implement audit records. +* if auditing is required, then an appropriate message is either `IAudit`, if there is no separate audit service or `AuditWinService` (waiting for a response will depend on the settings of the audit). -The class implements the interface `AuditService` `IAuditService`, and also has a static field of type `IAuditService` where will be recorded the instance of a class `AuditService` (this will allow to work both with a static class through the reference «AuditService.CurrentAuditService»). All calls are made via an interface (if there is a need, the class `Audit` easy to replace). +The class implements the interface `AuditService` `IAuditService`, and also has a static field of type `IAuditService` where will be recorded the instance of a class `AuditService` (this will allow to work both with a static class through the reference «AuditService.CurrentAuditService»). All calls are made via an interface (if there is a need, the class `Audit` easy to replace). -# IAudit +# IAudit -[IAudit](efs_i-audit.html) is an interface for you to organize the logic of the audit (that is, the class that implements this interface will be responsible for recording audit information and proofreading). +[IAudit](efs_i-audit.html) is an interface for you to organize the logic of the audit (that is, the class that implements this interface will be responsible for recording audit information and proofreading). -# AuditWinService +# AuditWinService -[AuditWinService](efs_audit-win-service.html) is a service through which it is possible to record audit data. +[AuditWinService](efs_audit-win-service.html) is a service through which it is possible to record audit data. -# AsyncAuditController +# AsyncAuditController -`AsyncAuditController` class, organizing asynchronous access `IAudit` that allows you to defer for some time the recording of data on audit ("'is not currently in use"'). +`AsyncAuditController` class, organizing asynchronous access `IAudit` that allows you to defer for some time the recording of data on audit ("'is not currently in use"'). -# RemoteAuditController (ServiceAuditController) +# interaction Scheme -`RemoteAuditController (ServiceAuditController)` class responsible for the interaction through wcf win service audit `AuditWinService` associated with the wcf service, which implements the interface `IAuditWcfServiceLibrary`. +## interaction pattern of the component audit without a single audit service -# interaction Scheme +![Image](/images/img/page/AuditWeb/AuditDiagramm1.PNG) -## interaction pattern of the component audit without a single audit service +## Scheme of interaction between a component of an audit when there is a distinct audit service -![Image](/images/img/page/AuditWeb/AuditDiagramm1.PNG) +![Image](/images/img/page/AuditWeb/AuditDiagramm2.PNG) -## Scheme of interaction between a component of an audit when there is a distinct audit service +## interaction pattern of the component audit -![Image](/images/img/page/AuditWeb/AuditDiagramm2.PNG) - -## interaction pattern of the component audit - -![Image](/images/img/page/AuditWeb/AuditDiagramm3.PNG) +![Image](/images/img/page/AuditWeb/AuditDiagramm3.PNG) diff --git a/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.ru.md b/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.ru.md index 6f5edde0c..abe69a814 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_FlexberryAuditComponents.ru.md @@ -8,7 +8,7 @@ lang: ru --- # AuditService -У приложения есть класс `AuditService`. Через класс `AuditService` реализуются API для обращения: +У приложения есть класс `AuditService`. Через класс `AuditService` реализуются API для обращения: * к классу, наследующему от интерфейса [IAudit](i-audit.html), если аудит не выделен в отдельный сервис. * к сервису аудита `AuditWinService`. @@ -32,10 +32,6 @@ lang: ru `AsyncAuditController` – класс, организующий асинхронный доступ к `IAudit`, что позволяет отложить на некоторое время запись данных об аудите ('''в настоящее время не используется'''). -# RemoteAuditController (ServiceAuditController) - -`RemoteAuditController (ServiceAuditController)` – класс, отвечающий за взаимодействие через wcf с win-сервисом аудита `AuditWinService`, связанному с wcf-сервисом, реализующим интерфейс `IAuditWcfServiceLibrary`. - # Схема взаимодействия ## Схема взаимодействия компонент подсистемы аудита без отдельного сервиса аудита diff --git a/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.en.md b/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.en.md index 9669e5bb4..8cb5d71ac 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.en.md +++ b/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.en.md @@ -121,7 +121,7 @@ private static IDataService SecurityDataService { if (_securityDataService == null) { - IUnityContainer container = UnityFactory.GetContainer(); + IUnityContainer container = UnityFactory.GetContainer(); //UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. _securityDataService = container.Resolve("SecurityManagerDataService"); } @@ -183,7 +183,7 @@ Now when you set some user specific rights you will be able to view only the rel To check whether the object satisfies specified filters powers, you can use the following functionality: ``` csharp -ISecurityManager securityManager = DataServiceProvider.DataService.SecurityManager; +ISecurityManager securityManager = DataServiceProvider.DataService.SecurityManager; // DataServiceProvider is deprecated; inject IDataService instead bool hasAccess = securityManager.AccessObjectCheck(objectTocheck, tTypeAccess.Insert, true); ``` diff --git a/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.ru.md b/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.ru.md index 7ba8ee404..45075aefa 100644 --- a/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.ru.md +++ b/pages/products/flexberry-orm/authority-audit/efs_security-rights-objects.ru.md @@ -19,7 +19,7 @@ lang: ru Как это реализовать: -1. Обновить пакет Flexberry ORM до версии не ниже 2.1.0-alpha01. +1. Обновить пакет Flexberry ORM до версии не ниже 2.1.0-alpha01. Обновить пакет Flexberry Security до версии не ниже 1.5.0-alpha01. @@ -33,12 +33,12 @@ lang: ru - + - + @@ -58,9 +58,9 @@ lang: ru - - - + @@ -82,7 +82,7 @@ lang: ru - + ... @@ -119,7 +119,7 @@ private static IDataService SecurityDataService { if (_securityDataService == null) { - IUnityContainer container = UnityFactory.GetContainer(); + IUnityContainer container = UnityFactory.GetContainer(); // UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). _securityDataService = container.Resolve("SecurityManagerDataService"); } @@ -188,7 +188,7 @@ bool hasAccess = securityManager.AccessObjectCheck(objectTocheck, tTypeAccess.In Сначала в примере происходит получение текущей инстанции `ISecurityManager`, установленной в текущий [DataService|сервис данных) (требуется, чтобы при этом менеджер полномочий был настроен на проверку полномочий на объекты (например, с помощью конфига, как показано выше); если это не так, то необходимую инстанцию менеджера полномочий можно создать с помощью программного кода). Далее в метод менеджера полномочий передаётс: -* объект, полномочия на который проверяются (может быть передан любой объект, в этом случае происходит проверка доступа на тип объекта, но если передан [DataObject|объект данных), то проверка происходит и на сам объект с учётом заданных ограничений), +* объект, полномочия на который проверяются (может быть передан любой объект, в этом случае происходит проверка доступа на тип объекта, но если передан [DataObject|объект данных), то проверка происходит и на сам объект с учётом заданных ограничений), * тип операции, полномочия на которую требуется проверять, * флаг, определяющий, требуется ли кидать исключение, если отсутствуют полномочия на объект. diff --git a/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.en.md b/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.en.md index 0e917e164..f3e2781cc 100644 --- a/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.en.md +++ b/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.en.md @@ -17,7 +17,7 @@ Services run-time subsystem powers Flexberry available through the interface `IC This interface allowed real authority [Flexberry UnityFactory](fo_unity-factory.html) as follows: ```csharp -IUnityContainer container = UnityFactory.CreateContainer(); +IUnityContainer container = UnityFactory.CreateContainer(); //UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. ISecurityManager securityManager = container.Resolve(); ``` diff --git a/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.ru.md b/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.ru.md index d53a54960..bb0edc08b 100644 --- a/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.ru.md +++ b/pages/products/flexberry-orm/authority-audit/fo_i-security-manager.ru.md @@ -8,6 +8,8 @@ permalink: ru/fo_i-security-manager.html lang: ru --- +> UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). + Сервисы времени выполнения подсистемы полномочий Flexberry доступны через интерфейс `ICSSoft.STORMNET.Security.ISecurityManager, ICSSoft.STORMNET.DataObject`. ## Получение доступа к инстанции ISecurityManager @@ -15,7 +17,7 @@ lang: ru Данный интерфес разрешается в реальную инстанцию через [Flexberry UnityFactory](fo_unity-factory.html) следующим образом: ```csharp -IUnityContainer container = UnityFactory.CreateContainer(); +IUnityContainer container = UnityFactory.CreateContainer(); // UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). ISecurityManager securityManager = container.Resolve(); ``` diff --git a/pages/products/flexberry-orm/business-servers/fo_cascade-delete.en.md b/pages/products/flexberry-orm/business-servers/fo_cascade-delete.en.md index 02e2021ba..99d423964 100644 --- a/pages/products/flexberry-orm/business-servers/fo_cascade-delete.en.md +++ b/pages/products/flexberry-orm/business-servers/fo_cascade-delete.en.md @@ -79,7 +79,7 @@ if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) UpdatedObject.Актуально = false; // Find all objects, referencing "delete" and remove them. - var ds = (SQLDataService)DataServiceProvider.DataService; + var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead var klients = ds.Query<Клиент>(Клиент.Views.КлиентE) .Where(k => k.Прописка.__PrimaryKey == UpdatedObject.__PrimaryKey); @@ -97,7 +97,7 @@ if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) Next to the user being shown the "deleted" data when viewing the list of objects required for the appropriate control limit types: ``` csharp -var ds = (MSSQLDataService)DataServiceProvider.DataService; +var ds = (MSSQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Клиент> limit1 = ds.Query<Адрес>(Адрес.Views.АдресL).Where(Address => Address.Актуально); Function onlyActual = LinqToLcs.GetLcs(limit1.Expression, Адрес.Views.АдресL).LimitFunction; ``` diff --git a/pages/products/flexberry-orm/business-servers/fo_cascade-delete.ru.md b/pages/products/flexberry-orm/business-servers/fo_cascade-delete.ru.md index 73e95ac30..11da4c245 100644 --- a/pages/products/flexberry-orm/business-servers/fo_cascade-delete.ru.md +++ b/pages/products/flexberry-orm/business-servers/fo_cascade-delete.ru.md @@ -77,7 +77,7 @@ if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) UpdatedObject.Актуально = false; // Найдем все объекты, ссылающиеся на "удаляемый" и удалим их. - var ds = (SQLDataService)DataServiceProvider.DataService; + var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var klients = ds.Query<Клиент>(Клиент.Views.КлиентE) .Where(k => k.Прописка.__PrimaryKey == UpdatedObject.__PrimaryKey); @@ -95,7 +95,7 @@ if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) Далее, чтобы пользователю не выводились "удаленные" данные при просмотре списка объектов, требуется на соответствующий контрол наложить ограничение вида: ``` csharp -var ds = (MSSQLDataService)DataServiceProvider.DataService; +var ds = (MSSQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. IQueryable<Клиент> limit1 = ds.Query<Адрес>(Адрес.Views.АдресL).Where(Address => Address.Актуально); Function onlyActual = LinqToLcs.GetLcs(limit1.Expression, Адрес.Views.АдресL).LimitFunction; -``` \ No newline at end of file +``` diff --git a/pages/products/flexberry-orm/business-servers/fo_delete-cancel.en.md b/pages/products/flexberry-orm/business-servers/fo_delete-cancel.en.md index dc6316fa7..7be2e85ca 100644 --- a/pages/products/flexberry-orm/business-servers/fo_delete-cancel.en.md +++ b/pages/products/flexberry-orm/business-servers/fo_delete-cancel.en.md @@ -44,7 +44,7 @@ For the above-described conditions: to add validation to a business class server if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) { // Find the number of clients that reference the deleted address. - var ds = (MSSQLDataService)DataServiceProvider.DataService; + var ds = (MSSQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead var clientsCount = ds.Query<Клиент>(Клиент.Views.КлиентE).Where(k => k.Прописка.__PrimaryKey == UpdatedObject.__PrimaryKey).Count(); // If the customer is not 0, throw an exception. diff --git a/pages/products/flexberry-orm/business-servers/fo_delete-cancel.ru.md b/pages/products/flexberry-orm/business-servers/fo_delete-cancel.ru.md index 4277a87a4..032c36431 100644 --- a/pages/products/flexberry-orm/business-servers/fo_delete-cancel.ru.md +++ b/pages/products/flexberry-orm/business-servers/fo_delete-cancel.ru.md @@ -42,7 +42,7 @@ lang: ru if (UpdatedObject.GetStatus() == ObjectStatus.Deleted) { // Найдем количество клиентов, ссылающихся на удаляемый адрес. - var ds = (MSSQLDataService)DataServiceProvider.DataService; + var ds = (MSSQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var clientsCount = ds.Query<Клиент>(Клиент.Views.КлиентE).Where(k => k.Прописка.__PrimaryKey == UpdatedObject.__PrimaryKey).Count(); // Если клиентов не 0, выкинем исключение. diff --git a/pages/products/flexberry-orm/business-servers/fo_unique-data-check.en.md b/pages/products/flexberry-orm/business-servers/fo_unique-data-check.en.md index b44839d24..b70bccf5a 100644 --- a/pages/products/flexberry-orm/business-servers/fo_unique-data-check.en.md +++ b/pages/products/flexberry-orm/business-servers/fo_unique-data-check.en.md @@ -26,7 +26,7 @@ You want to check the uniqueness of the entered credit card number. Code using [LinqProvider](fo_linq-provider.html): ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead var кредитныеКарты = ds.Query<КредитнаяКарта>(КредитнаяКарта.Views.КредитнаяКартаE) .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey && k.Номер == UpdatedObject.Номер); @@ -37,7 +37,7 @@ Thus, in the variable `кредитныеКарты` is the amount of the desire We should Refine the condition by adding a comparison with the current map, using `LinqProvider`: ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead var кредитныеКарты = ds.Query<КредитнаяКарта>(КредитнаяКарта.Views.КредитнаяКартаE) .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey && k.Номер == UpdatedObject.Номер diff --git a/pages/products/flexberry-orm/business-servers/fo_unique-data-check.ru.md b/pages/products/flexberry-orm/business-servers/fo_unique-data-check.ru.md index c6768822c..7c3ea6458 100644 --- a/pages/products/flexberry-orm/business-servers/fo_unique-data-check.ru.md +++ b/pages/products/flexberry-orm/business-servers/fo_unique-data-check.ru.md @@ -24,9 +24,9 @@ lang: ru Код с применением [LinqProvider](fo_linq-provider.html): ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var кредитныеКарты = ds.Query<КредитнаяКарта>(КредитнаяКарта.Views.КредитнаяКартаE) - .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey + .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey && k.Номер == UpdatedObject.Номер); ``` @@ -35,9 +35,9 @@ var кредитныеКарты = ds.Query<КредитнаяКарта>(Кре Следует доработать условие, добавив сравнение с текущей картой, используя `LinqProvider`: ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var кредитныеКарты = ds.Query<КредитнаяКарта>(КредитнаяКарта.Views.КредитнаяКартаE) - .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey + .Count(k => k.Клиент.__PrimaryKey == UpdatedObject.Клиент.__PrimaryKey && k.Номер == UpdatedObject.Номер && k.__primaryKey != UpdatedObject.__PrimaryKey); ``` diff --git a/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.en.md b/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.en.md index b47897e58..d07c14045 100644 --- a/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.en.md +++ b/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.en.md @@ -1,30 +1,30 @@ ---- -title: Service record SQL-scripts change the data -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, monitor tasks, changing data -summary: a Sample implementation of write SQL scripts using the task monitor -toc: true -permalink: en/fo_changes-sql-bt-monitor.html -lang: en -autotranslated: true -hash: a710c7d0df6a85458dfbe188f74fd7754cede2a831fa96019fc033c3a7b54e19 ---- +--- +title: Service record SQL-scripts change the data +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, monitor tasks, changing data +summary: a Sample implementation of write SQL scripts using the task monitor +toc: true +permalink: en/fo_changes-sql-bt-monitor.html +lang: en +autotranslated: true +hash: a710c7d0df6a85458dfbe188f74fd7754cede2a831fa96019fc033c3a7b54e19 +--- -## Description +## Description -`ICSSoft.Services.ChangesToSqlBTMonitor` is a kind [task monitor](fo_business-task-monitor.html), which allows you to record SQL-scripts change the data. +`ICSSoft.Services.ChangesToSqlBTMonitor` is a kind [task monitor](fo_business-task-monitor.html), which allows you to record SQL-scripts change the data. -## the service Connection +## the service Connection -To connect this service, you need in the configuration file to write: +To connect this service, you need in the configuration file to write: ```xml - -``` + +``` -## use of the service +## use of the service -Example handlers for menu items: +Example handlers for menu items: ```csharp private void RecorderClearClick(object sender, EventArgs e) @@ -40,19 +40,19 @@ private void RecorderSaveClick(object sender, EventArgs e) StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8); - // Have the writer write strings to the store. + // Have the writer write strings to the store. writer.Write(ICSSoft.Services.ChangesToSqlBTMonitor.Record); writer.Close(); } } -``` +``` -So in the output script to avoid unnecessary queries, you can configure a filter on the table names in the configuration file +So in the output script to avoid unnecessary queries, you can configure a filter on the table names in the configuration file ```xml -``` +``` diff --git a/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.ru.md b/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.ru.md index 4276a4f2f..646c637f7 100644 --- a/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.ru.md +++ b/pages/products/flexberry-orm/business-task-monitor/fo_changes-sql-bt-monitor.ru.md @@ -17,7 +17,7 @@ lang: ru Чтобы подключить данный сервис, нужно в конфигурационном файле написать: ```xml - + ``` ## Использование сервиса diff --git a/pages/products/flexberry-orm/current-user-service/fo_current-user-service.en.md b/pages/products/flexberry-orm/current-user-service/fo_current-user-service.en.md index 9b456d58b..637ce894d 100644 --- a/pages/products/flexberry-orm/current-user-service/fo_current-user-service.en.md +++ b/pages/products/flexberry-orm/current-user-service/fo_current-user-service.en.md @@ -1,48 +1,48 @@ ---- -title: Service current user -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, current user, example -summary: Methods of work with the current user -toc: true -permalink: en/fo_current-user-service.html -lang: en -autotranslated: true -hash: 308af940aa6ecf24e983f3712100317efb7363e1289da3c45116a8eab6af9195 ---- +--- +title: Service current user +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, current user, example +summary: Methods of work with the current user +toc: true +permalink: en/fo_current-user-service.html +lang: en +autotranslated: true +hash: 308af940aa6ecf24e983f3712100317efb7363e1289da3c45116a8eab6af9195 +--- -`Flexberry CurrentUserService` is [product platform Flexberry](fp_landing_page.html) and allows to obtain the current user, and change as individual properties, and the way to work with it. +`Flexberry CurrentUserService` is [product platform Flexberry](fp_landing_page.html) and allows to obtain the current user, and change as individual properties, and the way to work with it. -{% include note.html content="CurrentUserService Flexberry included in the NuGet package Flexberry ORM." %} +{% include note.html content="CurrentUserService Flexberry included in the NuGet package Flexberry ORM." %} -To get the current user using `ICSSoft.Services.CurrentUserService.CurrentUser`. An attribute has an interface `ICSSoft.Services.CurrentUserService IUser`: +To get the current user using `ICSSoft.Services.CurrentUserService.CurrentUser`. An attribute has an interface `ICSSoft.Services.CurrentUserService IUser`: ```csharp public interface IUser { - /// - /// The user name ("VASYA Pupkin"). - /// + /// + /// The user name ("VASYA Pupkin"). + /// string FriendlyName { get; set; } - /// - /// User domain. - /// + /// + /// User domain. + /// string Domain { get; set; } - /// - /// User login ("vpupkin"). - /// + /// + /// User login ("vpupkin"). + /// string Login { get; set; } } -``` +``` -By default, the username and domain of the user taken from environment variables (for win) and from the current HTTP context (for web applications). +By default, the username and domain of the user taken from environment variables (for win) and from the current HTTP context (for web applications). -The user name if not explicitly set, calculated via the login. +The user name if not explicitly set, calculated via the login. -## rewriting service the current user +## rewriting service the current user -If you want to change the way of working with the current user (e.g., store the user ID in the cache, and a web application), we need to implement the interface `ICSSoft.Services.CurrentUserService IUser` and assign it the handler. For mapping you can use the method `ICSSoft.Services.CurrentUserService.ResolveUser()` and settings in the configuration file (use [UnityFactory](fo_unity-factory.html)): +If you want to change the way of working with the current user (e.g., store the user ID in the cache, and a web application), we need to implement the interface `ICSSoft.Services.CurrentUserService IUser` and assign it the handler. For mapping you can use the method `ICSSoft.Services.CurrentUserService.ResolveUser()` and settings in the configuration file (use [UnityFactory](fo_unity-factory.html)): ```xml @@ -56,45 +56,45 @@ If you want to change the way of working with the current user (e.g., store the - + -``` +``` -In addition, for overriding the type necessary to fill in the ", ". +In addition, for overriding the type necessary to fill in the ", ". -### Example rewriting service the current user +### Example rewriting service the current user -Let the name of the current user stored in the static field `IIS.TryAccessSystem.Polzovatelyami.currentUserLogin`, then rewriting service the current user is the following: +Let the name of the current user stored in the static field `IIS.TryAccessSystem.Polzovatelyami.currentUserLogin`, then rewriting service the current user is the following: ``` csharp namespace IIS.TryAccessSystem { - /// - /// Override the current user service - /// + /// + /// Override the current user service + /// public class ClassOtherUser : ICSSoft.Services.CurrentUserService.IUser { - /// - /// The user name ("VASYA Pupkin") - /// + /// + /// The user name ("VASYA Pupkin") + /// public string FriendlyName { get { return IIS.TryAccessSystem.ПользовательПриложения.currentUserLogin; } set {} } - /// - /// Domain user - /// + /// + /// Domain user + /// public string Domain {get; set;} - /// - /// User login ("vpupkin") - /// + /// + /// User login ("vpupkin") + /// public string Login { get { return IIS.TryAccessSystem.ПользовательПриложения.currentUserLogin; } @@ -102,9 +102,9 @@ namespace IIS.TryAccessSystem } } } -``` +``` -If the class `IIS.TryAccessSystem.ClassOtherUser` contains an override of the service and located in the Assembly `TryAccessSystem(Forms)`, to override the service of the current user in the application configuration file, it is sufficient to add: +If the class `IIS.TryAccessSystem.ClassOtherUser` contains an override of the service and located in the Assembly `TryAccessSystem(Forms)`, to override the service of the current user in the application configuration file, it is sufficient to add: ```xml @@ -118,19 +118,19 @@ If the class `IIS.TryAccessSystem.ClassOtherUser` contains an override of the se - + -``` +``` -## Possible errors +## Possible errors -`CurrentUserService` may generate an error and report that it can not find the Assembly `Microsoft.Practices.Unity`. +`CurrentUserService` may generate an error and report that it can not find the Assembly `Microsoft.Practices.Unity`. -This is due to the fact that this build is really not in the folder with the binaries of the project, as it is not copied there when building the project. However, it is often that it is in the global folder with the assemblies of the operating system. +This is due to the fact that this build is really not in the folder with the binaries of the project, as it is not copied there when building the project. However, it is often that it is in the global folder with the assemblies of the operating system. To correct the situation you must have a reference to this Assembly (Reference) in the project to put the property `CopyLocal` = `true`. diff --git a/pages/products/flexberry-orm/current-user-service/fo_current-user-service.ru.md b/pages/products/flexberry-orm/current-user-service/fo_current-user-service.ru.md index 80c982810..16df65cb8 100644 --- a/pages/products/flexberry-orm/current-user-service/fo_current-user-service.ru.md +++ b/pages/products/flexberry-orm/current-user-service/fo_current-user-service.ru.md @@ -54,7 +54,7 @@ public interface IUser - + @@ -116,7 +116,7 @@ namespace IIS.TryAccessSystem - + @@ -130,4 +130,4 @@ namespace IIS.TryAccessSystem Это связано с тем, что этой сборки действительно нет в папке с бинарниками проекта, так как она не копируется туда при сборке проекта. Однако, зачастую бывает, что она есть в глобальной папке со сборками операционной системы. -Чтобы исправить ситуацию необходимо у ссылки на эту сборку (Reference) в проекте поставить свойство `CopyLocal` = `true`. \ No newline at end of file +Чтобы исправить ситуацию необходимо у ссылки на эту сборку (Reference) в проекте поставить свойство `CopyLocal` = `true`. diff --git a/pages/products/flexberry-orm/data-object/fo_actions-saving-object.en.md b/pages/products/flexberry-orm/data-object/fo_actions-saving-object.en.md index f260776bb..cc5984d88 100644 --- a/pages/products/flexberry-orm/data-object/fo_actions-saving-object.en.md +++ b/pages/products/flexberry-orm/data-object/fo_actions-saving-object.en.md @@ -16,7 +16,7 @@ In [Flexberry ORM](fo_flexberry-orm.html) this feature is implemented by using c ```csharp Console.WriteLine("4. How to do something persistence at the moment."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(CDDA)); diff --git a/pages/products/flexberry-orm/data-object/fo_actions-saving-object.ru.md b/pages/products/flexberry-orm/data-object/fo_actions-saving-object.ru.md index 9bb7f9f39..f30669dfd 100644 --- a/pages/products/flexberry-orm/data-object/fo_actions-saving-object.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_actions-saving-object.ru.md @@ -14,21 +14,21 @@ lang: ru ```csharp Console.WriteLine("4. How to do something at persistence moment."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(CDDA)); // Как сделать что-то в момент сохранения: // 1. Задать для сущности клас бизнес-сервера в Flexberry или с помощью .Net-атрибута BusinessServer (см. класс CDDA в проекте CDLIB(Objects)). -// 2. Сгенерируйте из Flexberry или создайте самостоятельно класс бизнес-сервера с методом, обрабатывающим сохранение объектов, и реализуйте его +// 2. Сгенерируйте из Flexberry или создайте самостоятельно класс бизнес-сервера с методом, обрабатывающим сохранение объектов, и реализуйте его // (см. класс CDLibBS в проекте CDLIB(BusinessServers)) // 3. Произведите какие-либо действия с объектом и сохраните его. CDDA cdda = new CDDA(); cdda.SetExistObjectPrimaryKey(primaryKey); - + Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); - + dataService.LoadObject(CDDA.Views.CDDA_E, cdda); cdda.Name = "Huh! " + DateTime.Now; dataService.UpdateObject(cdda); diff --git a/pages/products/flexberry-orm/data-object/fo_create-multiple-details.en.md b/pages/products/flexberry-orm/data-object/fo_create-multiple-details.en.md index e98eb5823..7ee1ad136 100644 --- a/pages/products/flexberry-orm/data-object/fo_create-multiple-details.en.md +++ b/pages/products/flexberry-orm/data-object/fo_create-multiple-details.en.md @@ -38,7 +38,7 @@ Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // The objects are stored in order corresponding to the relations between them (from the root to the tips). -DataServiceProvider.DataService.UpdateObject(aggregator); +DataServiceProvider.DataService.UpdateObject(aggregator); // DataServiceProvider is deprecated; inject IDataService instead stopwatch.Stop(); Console.WriteLine("Time taken for persistence: {0} ms.", stopwatch.ElapsedMilliseconds); diff --git a/pages/products/flexberry-orm/data-object/fo_create-multiple-details.ru.md b/pages/products/flexberry-orm/data-object/fo_create-multiple-details.ru.md index 77203e230..a8385da33 100644 --- a/pages/products/flexberry-orm/data-object/fo_create-multiple-details.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_create-multiple-details.ru.md @@ -23,7 +23,7 @@ lang: ru ```csharp Console.WriteLine("5. Create a dataobject with multiple details."); -// Создаем объект данных, у которого несколько детейловых свойств. +// Создаем объект данных, у которого несколько детейловых свойств. D0 aggregator = new D0(); // Вызываем метод генерации детейловых объектов. Код метода приведен ниже. @@ -36,7 +36,7 @@ Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // Объекты будут сохранены в порядке, соответствующем связям между ними (от корня до кончиков). -DataServiceProvider.DataService.UpdateObject(aggregator); +DataServiceProvider.DataService.UpdateObject(aggregator); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. stopwatch.Stop(); Console.WriteLine("Time taken for persistence: {0} ms.", stopwatch.ElapsedMilliseconds); diff --git a/pages/products/flexberry-orm/data-object/fo_features-dafault-value.en.md b/pages/products/flexberry-orm/data-object/fo_features-dafault-value.en.md index 144d314d4..2fd3aa73d 100644 --- a/pages/products/flexberry-orm/data-object/fo_features-dafault-value.en.md +++ b/pages/products/flexberry-orm/data-object/fo_features-dafault-value.en.md @@ -92,7 +92,7 @@ public class WinformC__ЗаписьНаПриёмE : ICSSoft.STORMNET.UI.BaseWin private void WinformC__ЗаписьНаПриёмE_DataObjectOnFormLoaded(object sender, EventArgs e) { //define which business servers defined for the object type "Zapolarie" - BusinessServer[] businessServers = BusinessServerProvider.GetBusinessServer(typeof(ЗаписьНаПриём), DataServiceObjectEvents.OnAllEvents, DataServiceProvider.DataService); + BusinessServer[] businessServers = BusinessServerProvider.GetBusinessServer(typeof(ЗаписьНаПриём), DataServiceObjectEvents.OnAllEvents, DataServiceProvider.DataService); // DataServiceProvider is deprecated; inject IDataService instead if (businessServers.Length>0) { TestBS curBS = (TestBS) businessServers[0]; //get first and only (in this case only) diff --git a/pages/products/flexberry-orm/data-object/fo_features-dafault-value.ru.md b/pages/products/flexberry-orm/data-object/fo_features-dafault-value.ru.md index fdabbd1ed..b94d9f511 100644 --- a/pages/products/flexberry-orm/data-object/fo_features-dafault-value.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_features-dafault-value.ru.md @@ -35,7 +35,7 @@ private System.Nullable fRelease = System.DateTime.Now; ### Синонимы типов -Для [синонимов типов](fd_typedef.html) задание значения по умолчанию на диаграмме классов происходит аналогично тому, как это происходит у типов, синонимами которых они являются. +Для [синонимов типов](fd_typedef.html) задание значения по умолчанию на диаграмме классов происходит аналогично тому, как это происходит у типов, синонимами которых они являются. ## Задание значения по умолчанию в программном коде @@ -65,13 +65,13 @@ public class WinformC__ПациентE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.BS public class Пациент : ICSSoft.STORMNET.DataObject { private fФИО = "ФИОПациента"; //установка значения по умолчанию - public string ФИО + public string ФИО { get { return fФИО; } - + set { fФИО = value; @@ -90,8 +90,8 @@ public class WinformC__ЗаписьНаПриёмE : ICSSoft.STORMNET.UI.BaseWin private void WinformC__ЗаписьНаПриёмE_DataObjectOnFormLoaded(object sender, EventArgs e) { //определяем, какие бизнес-сервера определены для объекта типа "ЗаписьНаПриём" - BusinessServer[] businessServers = BusinessServerProvider.GetBusinessServer(typeof(ЗаписьНаПриём), DataServiceObjectEvents.OnAllEvents, DataServiceProvider.DataService); - if (businessServers.Length>0) + BusinessServer[] businessServers = BusinessServerProvider.GetBusinessServer(typeof(ЗаписьНаПриём), DataServiceObjectEvents.OnAllEvents, DataServiceProvider.DataService); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. + if (businessServers.Length>0) { TestBS curBS = (TestBS) businessServers[0]; //берём первый и единственный (в данном случае единственный) curBS.InitializeRecord(this.DataObject as ЗаписьНаПриём); //задаём значения по умолчанию diff --git a/pages/products/flexberry-orm/data-object/fo_load-alter-objects.en.md b/pages/products/flexberry-orm/data-object/fo_load-alter-objects.en.md index 0262c5547..171b8f8ed 100644 --- a/pages/products/flexberry-orm/data-object/fo_load-alter-objects.en.md +++ b/pages/products/flexberry-orm/data-object/fo_load-alter-objects.en.md @@ -21,7 +21,7 @@ When loading is applied [view](fd_view-definition.html). ```csharp Console.WriteLine("2. How to load a dataobject in specific view, change it\'s property, then persist. Object loading status and state."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead // Initialize the helper object through which we get the primary key of an arbitrary object // of the specified type. diff --git a/pages/products/flexberry-orm/data-object/fo_load-alter-objects.ru.md b/pages/products/flexberry-orm/data-object/fo_load-alter-objects.ru.md index 855280534..26acdce8e 100644 --- a/pages/products/flexberry-orm/data-object/fo_load-alter-objects.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_load-alter-objects.ru.md @@ -19,7 +19,7 @@ lang: ru ```csharp Console.WriteLine("2. How to load dataobject in specific view, change it\'s property, then persist. Object status and loading state."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. // Инициализация вспомогательного объекта, с помощью которого мы получим первичный ключ произвольного объекта // заданного типа. @@ -45,7 +45,7 @@ stopwatch.Start(); // Сохранение объекта. Обновляются только загруженные свойства. dataService.UpdateObject(cdda); - + stopwatch.Stop(); Console.WriteLine("Time taken for persistence: {0} ms.", stopwatch.ElapsedMilliseconds); ``` diff --git a/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.en.md b/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.en.md index f45fae077..0fd66d0e0 100644 --- a/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.en.md +++ b/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.en.md @@ -15,7 +15,7 @@ Here is the download of all objects created in the [example](fo_actions-saving-o ```csharp Console.WriteLine("6. Loading a dataobject with multiple details."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(D0)); diff --git a/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.ru.md b/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.ru.md index 5af626f2b..8289433a3 100644 --- a/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_load-multiple-details-example.ru.md @@ -12,8 +12,8 @@ lang: ru ```csharp Console.WriteLine("6. Loading a dataobject with multiple details."); - -IDataService dataService = DataServiceProvider.DataService; + +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(D0)); @@ -43,7 +43,7 @@ internal void CheckDetailsQty(D dobj, int qtyInEach) for (int i = 0; i < detprops.Length; i++) { DetailArray detarr = (DetailArray)Information.GetPropValueByName(dobj, detprops[i]); - if (detarr.Count != qtyInEach) + if (detarr.Count != qtyInEach) throw new Exception(string.Format("Missing reading of {0}!", detprops[i])); for (int j = 0; j < detarr.Count; j++) diff --git a/pages/products/flexberry-orm/data-object/fo_methods-class-information.en.md b/pages/products/flexberry-orm/data-object/fo_methods-class-information.en.md index a01514aaa..b9422f2f9 100644 --- a/pages/products/flexberry-orm/data-object/fo_methods-class-information.en.md +++ b/pages/products/flexberry-orm/data-object/fo_methods-class-information.en.md @@ -495,6 +495,8 @@ A more detailed description of this method can be found in [Information.GetPrope ### CheckAccessToAttribute +> CheckAccessToAttribute is no more present in ORM v8.0. + __Assign__: Checking rights to object attributes. The method is a wrapper for the method CheckAccessToAttribute class `ICSSoft.STORMNET.RightManager` and used to verify the rights in Get'erach computable properties of the DataObject. Processing of the masters is not subject to. __Settings__: diff --git a/pages/products/flexberry-orm/data-object/fo_methods-class-information.ru.md b/pages/products/flexberry-orm/data-object/fo_methods-class-information.ru.md index 579a12605..3b8871acd 100644 --- a/pages/products/flexberry-orm/data-object/fo_methods-class-information.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_methods-class-information.ru.md @@ -492,6 +492,7 @@ static public string GetPropertyStorageName(System.Type type, string property, i ## Проверка прав на атрибуты объекта ### CheckAccessToAttribute +> CheckAccessToAttribute отсутствует в ORM начиная с версии 8.0. __Назначение__: Проверка прав на атрибуты объекта. Метод является оберткой для метода CheckAccessToAttribute класса `ICSSoft.STORMNET.RightManager` и используется для проверки прав в Get'ерах вычислимых свойств DataObject. Обработка мастеров не проиводится. diff --git a/pages/products/flexberry-orm/data-object/fo_prototyping-example.en.md b/pages/products/flexberry-orm/data-object/fo_prototyping-example.en.md index 7a4e53d70..e069594d5 100644 --- a/pages/products/flexberry-orm/data-object/fo_prototyping-example.en.md +++ b/pages/products/flexberry-orm/data-object/fo_prototyping-example.en.md @@ -16,7 +16,7 @@ Full list of code examples [Flexberry ORM](fo_flexberry-orm.html) is in ["code E ```csharp Console.WriteLine("7. Prototyping."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(D0)); diff --git a/pages/products/flexberry-orm/data-object/fo_prototyping-example.ru.md b/pages/products/flexberry-orm/data-object/fo_prototyping-example.ru.md index 3ea261048..a248ab4bf 100644 --- a/pages/products/flexberry-orm/data-object/fo_prototyping-example.ru.md +++ b/pages/products/flexberry-orm/data-object/fo_prototyping-example.ru.md @@ -14,7 +14,7 @@ lang: ru ```csharp Console.WriteLine("7. Prototyping."); -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(D0)); @@ -69,4 +69,4 @@ public virtual void Prototype(bool withDetails) } } } -``` \ No newline at end of file +``` diff --git a/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.en.md b/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.en.md index dbc6d8dc4..53e50bddc 100644 --- a/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.en.md +++ b/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.en.md @@ -19,7 +19,7 @@ static void Main() { //... // create a DataService - ICSSoft.STORMNET.Business.SQLDataService ds = (ICSSoft.STORMNET.Business.SQLDataService)ICSSoft.STORMNET.Business.DataServiceProvider.DataService; + ICSSoft.STORMNET.Business.SQLDataService ds = (ICSSoft.STORMNET.Business.SQLDataService)ICSSoft.STORMNET.Business.DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead // before generating ds.OnGenerateSQLSelect+=new ICSSoft.STORMNET.Business.OnGenerateSQLSelectEventHandler(ds_OnGenerateSQLSelect); // after the formation of the diff --git a/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.ru.md b/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.ru.md index eeaea4792..b2e47005f 100644 --- a/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_Intercept-formation-sql-query.ru.md @@ -8,7 +8,7 @@ permalink: ru/fo_intercept-formation-sql-query.html lang: ru --- -[SQLDataService](fo_sql-data-service.html) позволяет осуществлять перехват формирования SQL-запроса к БД за счёт применения [делегатов OnGenerateSQLSelect, AfterGenerateSQLSelectQuery, OnCreateCommand](fo_sql-data-service.html). +[SQLDataService](fo_sql-data-service.html) позволяет осуществлять перехват формирования SQL-запроса к БД за счёт применения [делегатов OnGenerateSQLSelect, AfterGenerateSQLSelectQuery, OnCreateCommand](fo_sql-data-service.html). `Примеры перехватов формирования SQL-запросов`: @@ -17,15 +17,15 @@ static void Main() { //... // создаем датасервис - ICSSoft.STORMNET.Business.SQLDataService ds = (ICSSoft.STORMNET.Business.SQLDataService)ICSSoft.STORMNET.Business.DataServiceProvider.DataService; - // перед формированием - ds.OnGenerateSQLSelect+=new ICSSoft.STORMNET.Business.OnGenerateSQLSelectEventHandler(ds_OnGenerateSQLSelect); + ICSSoft.STORMNET.Business.SQLDataService ds = (ICSSoft.STORMNET.Business.SQLDataService)ICSSoft.STORMNET.Business.DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. + // перед формированием + ds.OnGenerateSQLSelect+=new ICSSoft.STORMNET.Business.OnGenerateSQLSelectEventHandler(ds_OnGenerateSQLSelect); // после формирования - ds.AfterGenerateSQLSelectQuery+=new ICSSoft.STORMNET.Business.AfterGenerateSQLSelectQueryEventHandler(ds_AfterGenerateSQLSelectQuery); + ds.AfterGenerateSQLSelectQuery+=new ICSSoft.STORMNET.Business.AfterGenerateSQLSelectQueryEventHandler(ds_AfterGenerateSQLSelectQuery); // строка посылается на выполение ... ds.OnCreateCommand+=new ICSSoft.STORMNET.Business.OnCreateCommandEventHandler(ds_OnCreateCommand); //... -} +} public static void ds_OnGenerateSQLSelect(object sender, ICSSoft.STORMNET.Business.GenerateSQLSelectQueryEventArgs e) { //... @@ -45,7 +45,7 @@ public static void ds_AfterGenerateSQLSelectQuery(object sender, ICSSoft.STORMNE if (e.CustomizationStruct.View.Name == "ПеремИАрхив") { e.GeneratedQuery = System.Text.RegularExpressions.Regex.Replace(e.GeneratedQuery.ToUpper(), - "^SELECT","SELECT TOP 100"); + "^SELECT","SELECT TOP 100"); } //... } diff --git a/pages/products/flexberry-orm/data-service/fo_construction-ds.en.md b/pages/products/flexberry-orm/data-service/fo_construction-ds.en.md index 6ff6f721b..286672bd2 100644 --- a/pages/products/flexberry-orm/data-service/fo_construction-ds.en.md +++ b/pages/products/flexberry-orm/data-service/fo_construction-ds.en.md @@ -1,31 +1,31 @@ ---- -title: Designing data services -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services -summary: how to create a data service to the application -toc: true -permalink: en/fo_construction-ds.html -lang: en -autotranslated: true -hash: 2d735b09e206410d3fa88e9c70423dee694d50815da1db333fbb725472b0f764 ---- - -Create [service data](fo_data-service.html) in different ways: - -1.To construct [service data](fo_data-service.html) +--- +title: Designing data services +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, data services +summary: how to create a data service to the application +toc: true +permalink: en/fo_construction-ds.html +lang: en +autotranslated: true +hash: 2d735b09e206410d3fa88e9c70423dee694d50815da1db333fbb725472b0f764 +--- + +Create [service data](fo_data-service.html) in different ways: + +1.To construct [service data](fo_data-service.html) ```csharp -IDataService ds = new ODBCDataService(); -ds.CustomizationString="DSN=LibNetSample"; -``` +IDataService ds = new PostgresDataService(); +ds.CustomizationString="Host=localhost;Port=5432;User ID=postgres;Password=postgres;"; +``` -2.In WinForms applications you can throw» «[service data](fo_data-service.html) on the form as the control, and then configure it using standard window editing properties in the Visual Studio environment. +2.In WinForms applications you can throw» «[service data](fo_data-service.html) on the form as the control, and then configure it using standard window editing properties in the Visual Studio environment. -3.[Get it from service provider data](fo_ds-provider.html). +3.[Get it from service provider data](fo_ds-provider.html). ```csharp -IDataService ds = DataServiceProvider.DataService; -``` +IDataService ds = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead +``` diff --git a/pages/products/flexberry-orm/data-service/fo_construction-ds.ru.md b/pages/products/flexberry-orm/data-service/fo_construction-ds.ru.md index 27238ba1e..9ab75b88e 100644 --- a/pages/products/flexberry-orm/data-service/fo_construction-ds.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_construction-ds.ru.md @@ -13,8 +13,8 @@ lang: ru 1.Сконструировать [сервис данных](fo_data-service.html) ```csharp -IDataService ds = new ODBCDataService(); -ds.CustomizationString="DSN=LibNetSample"; +IDataService ds = new PostgresDataService(); +ds.CustomizationString="Host=localhost;Port=5432;User ID=postgres;Password=postgres;"; ``` 2.В WinForms-приложениях можно «бросить» [сервис данных](fo_data-service.html) на форму как контрол, затем настроить его через стандартное окно редактирования свойств в среде Visual Studio. @@ -22,5 +22,5 @@ ds.CustomizationString="DSN=LibNetSample"; 3.[Получить его у провайдера сервиса данных](fo_ds-provider.html). ```csharp -IDataService ds = DataServiceProvider.DataService; +IDataService ds = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` diff --git a/pages/products/flexberry-orm/data-service/fo_data-service.en.md b/pages/products/flexberry-orm/data-service/fo_data-service.en.md index 34f7a924f..a7cdc9048 100644 --- a/pages/products/flexberry-orm/data-service/fo_data-service.en.md +++ b/pages/products/flexberry-orm/data-service/fo_data-service.en.md @@ -1,357 +1,357 @@ ---- -title: Service data -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, uploading data objects, updating data objects -summary: features of data entities using the data service -toc: true -permalink: en/fo_data-service.html -lang: en -autotranslated: true -hash: 5731622ef220414b9641261e9e27bec759be6c0590c105219e0e0036c1c17b5e ---- +--- +title: Service data +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, uploading data objects, updating data objects +summary: features of data entities using the data service +toc: true +permalink: en/fo_data-service.html +lang: en +autotranslated: true +hash: 5731622ef220414b9641261e9e27bec759be6c0590c105219e0e0036c1c17b5e +--- -**Service data** - Flexberry ORM component that provides read and write data objects in the repository. In the object model Flexberry ORM data service is represented by a class implementing the interface `ICSSoft.STORMNET.Business.IDataService`. -Supported multiple [standard data](fo_standard-data-services.html), and, if necessary, users can be [developed](fo_implement-custom-ds.html) new to meet your specific requirements (for example, inheriting classes `ICSSoft.STORMNET.Business.ODBCDataService.ODBCDataService` or `ICSSoft.STORMNET.Business.`[`SQLDataService`](fo_sql-data-service.html)). +**Service data** - Flexberry ORM component that provides read and write data objects in the repository. In the object model Flexberry ORM data service is represented by a class implementing the interface `ICSSoft.STORMNET.Business.IDataService`. +Supported multiple [standard data](fo_standard-data-services.html), and, if necessary, users can be [developed](fo_implement-custom-ds.html) new to meet your specific requirements (for example, inheriting class `ICSSoft.STORMNET.Business.`[`SQLDataService`](fo_sql-data-service.html)). -{% include important.html content="When you access the service data in the code is recommended through the interface `ICSSoft.STORMNET.Business.IDataService`, because it guarantees the independence of the code from the type of data store." %} +{% include important.html content="When you access the service data in the code is recommended through the interface `ICSSoft.STORMNET.Business.IDataService`, because it guarantees the independence of the code from the type of data store." %} -Before using the service data in the program code it is necessary [to set one way or another](fo_construction-ds.html). +Before using the service data in the program code it is necessary [to set one way or another](fo_construction-ds.html). -Should __pay attention__ on the following points: +Should __pay attention__ on the following points: -* You can configure a data service so that on case-sensitive data source, the application behaved as you would with [case-insensitive source](fo_insensitivity-register-ds.html). -* Data service [in a particular way works with Boolean type](fo_interpretation-boolean-null.html). +* You can configure a data service so that on case-sensitive data source, the application behaved as you would with [case-insensitive source](fo_insensitivity-register-ds.html). +* Data service [in a particular way works with Boolean type](fo_interpretation-boolean-null.html). -## Main features of the service data +## Main features of the service data -Before going to code the service data it is necessary to [link](fo_ds-provider.html). When using multiple vaults it is necessary to consider some of the [features](fo_multibase.html). +Before going to code the service data it is necessary to [link](fo_ds-provider.html). When using multiple vaults it is necessary to consider some of the [features](fo_multibase.html). -Interface `ICSSoft.STORMNET.Business.IDataService` contains the following basic groups of methods: +Interface `ICSSoft.STORMNET.Business.IDataService` contains the following basic groups of methods: -* __Methods with names like__ `UpdateXXXXXXXX` designed to bring the data store (update, delete, create record](fo_object-status.html)) in accordance with the transmitted one or more data objects: -* `UpdateObject` - updating a single object. -* `UpdateObjects` - update multiple objects. -* __Methods with names like__ `LoadXXXXXXXX` designed for reading one or more data objects. -* `LoadObject` - loading of the object (depending on settings using this method it is possible to carry out [dochitcu object](fo_additional-loading.html)). -* `LoadObjects` - loading facilities (including method overloads allow you to implement [a portion Stena](fo_reading-portion.html), [read belonging to different object classes in a single view](fo_reading-several-types-objects.html)). -* __Upload without creating objects__ `LoadStringedObjectView`. -* __Method of obtaining numbers of objects__, satisfying the condition `GetObjectsCount`. +* __Methods with names like__ `UpdateXXXXXXXX` designed to bring the data store (update, delete, create record](fo_object-status.html)) in accordance with the transmitted one or more data objects: +* `UpdateObject` - updating a single object. +* `UpdateObjects` - update multiple objects. +* __Methods with names like__ `LoadXXXXXXXX` designed for reading one or more data objects. +* `LoadObject` - loading of the object (depending on settings using this method it is possible to carry out [dochitcu object](fo_additional-loading.html)). +* `LoadObjects` - loading facilities (including method overloads allow you to implement [a portion Stena](fo_reading-portion.html), [read belonging to different object classes in a single view](fo_reading-several-types-objects.html)). +* __Upload without creating objects__ `LoadStringedObjectView`. +* __Method of obtaining numbers of objects__, satisfying the condition `GetObjectsCount`. -Most of the methods read/write have overloads that accept an extra parameter [DataObjectCache](fo_context-sensitive-cache.html), allowing to maintain a single instance for multiple instances of objects. Pass `DataObjectCache` methods zachetki in that case, if some object already exists in memory and after zachistki all references to it should point exactly at the object. In methods of updating the parameter is passed to the correct placement of references to instances of data from the cache due to the fact that after saving it to the vault updates the properties of a data object and initialize its copy of the data. +Most of the methods read/write have overloads that accept an extra parameter [DataObjectCache](fo_context-sensitive-cache.html), allowing to maintain a single instance for multiple instances of objects. Pass `DataObjectCache` methods zachetki in that case, if some object already exists in memory and after zachistki all references to it should point exactly at the object. In methods of updating the parameter is passed to the correct placement of references to instances of data from the cache due to the fact that after saving it to the vault updates the properties of a data object and initialize its copy of the data. -Read more about the features of using cache, see [Context-sensitive cache data objects](fo_context-sensitive-cache.html). +Read more about the features of using cache, see [Context-sensitive cache data objects](fo_context-sensitive-cache.html). -Below, when considering methods, the overload parameter `DataObjectCache` not separately described. +Below, when considering methods, the overload parameter `DataObjectCache` not separately described. -## Loading of data objects +## Loading of data objects -To load multiple data objects are overloads of the `LoadObjects`. +To load multiple data objects are overloads of the `LoadObjects`. -### Download data objects for view or array of views +### Download data objects for view or array of views -* Loads all the data objects available in the repository. Thus loading only those properties that are specified in [view](fd_view-definition.html). +* Loads all the data objects available in the repository. Thus loading only those properties that are specified in [view](fd_view-definition.html). ```csharp ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View dataObjectView); -``` +``` -* There is a consistent method call with parameter representation for each element of the array. The practical applicability of this overload is not obvious. +* There is a consistent method call with parameter representation for each element of the array. The practical applicability of this overload is not obvious. ```csharp ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View[] dataObjectViews); -``` +``` -#### Settings +#### Settings -`dataObjectView(s)` - view or array of views +`dataObjectView(s)` - view or array of views -### Loading data objects using the configuration structure for the sample LoadingCustomizationStruct (array of structures) +### Loading data objects using the configuration structure for the sample LoadingCustomizationStruct (array of structures) -* This method overload allows you to fine-tune the selection of downloadable objects through the use of structure [LoadingCustomizationStruct](fo_loading-customization-struct.html): +* This method overload allows you to fine-tune the selection of downloadable objects through the use of structure [LoadingCustomizationStruct](fo_loading-customization-struct.html): -* specify the view (a vertical list: download only of certain properties), -* the number of rows returned (for relational repositories limitation `TOP` in `SELECT`), -* collation of results to return (`ORDER BY`), -* restrictions on deducted data objects (`WHERE`) -* etc. see description [LoadingCustomizationStruct](fo_loading-customization-struct.html). +* specify the view (a vertical list: download only of certain properties), +* the number of rows returned (for relational repositories limitation `TOP` in `SELECT`), +* collation of results to return (`ORDER BY`), +* restrictions on deducted data objects (`WHERE`) +* etc. see description [LoadingCustomizationStruct](fo_loading-customization-struct.html). -[Example usage](fo_load-limitation-example.html). +[Example usage](fo_load-limitation-example.html). Zamechanie: This overloading allows you to implement a [read belonging to different object classes in a single view](fo_reading-several-types-objects.html). ```csharp -// 1. +// 1. ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct); -// 2. +// 2. ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, DataObjectCache DataObjectCache); -``` +``` -* There is a consistent method call with the parameter - `LoadingCustomizationStruct` for each element of the array. The practical applicability of this overload is not obvious. +* There is a consistent method call with the parameter - `LoadingCustomizationStruct` for each element of the array. The practical applicability of this overload is not obvious. ```csharp ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct[] customizationStructs); -``` +``` -#### Settings +#### Settings -`customizationStruct(s)` - [adjusting structure for a sample](fo_loading-customization-struct.html) (array of structures) +`customizationStruct(s)` - [adjusting structure for a sample](fo_loading-customization-struct.html) (array of structures) -### Download objects using state of the editing (to implement batch reading) +### Download objects using state of the editing (to implement batch reading) -* Getting the first batch [batch reading](fo_reading-portion.html). In addition to portions of data objects, data services returns a read state. This condition is transmitted to the data service to retrieve the next portion in subsequent calls (see Loading a single data object). +* Getting the first batch [batch reading](fo_reading-portion.html). In addition to portions of data objects, data services returns a read state. This condition is transmitted to the data service to retrieve the next portion in subsequent calls (see Loading a single data object). ```csharp -// 1. +// 1. ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct,ref object State); -// 2. +// 2. ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, ref object State, DataObjectCache DataObjectCache); -``` +``` -* Getting another batch [batch reading](fo_reading-portion.html). Should precede the call to that overload. +* Getting another batch [batch reading](fo_reading-portion.html). Should precede the call to that overload. ```csharp -// 1. +// 1. ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State); -// 2. +// 2. ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State, DataObjectCache DataObjectCache); -``` +``` -#### Settings +#### Settings -* `State` - a State of proof-reading(for the subsequent decide) -* `customizationStruct` - [adjusting structure for a sample](fo_loading-customization-struct.html) +* `State` - a State of proof-reading(for the subsequent decide) +* `customizationStruct` - [adjusting structure for a sample](fo_loading-customization-struct.html) -Primechanie: the serving Size may be specified with the parameter `LoadingBufferSize` structure [LoadingCustomizationStruct](fo_loading-customization-struct.html). +Primechanie: the serving Size may be specified with the parameter `LoadingBufferSize` structure [LoadingCustomizationStruct](fo_loading-customization-struct.html). -## Download one data object +## Download one data object -To load a single data object are method overloads `LoadObject`. -Reading properties from the repository is given in the data object [primary key](fo_primary-keys-objects.html). +To load a single data object are method overloads `LoadObject`. +Reading properties from the repository is given in the data object [primary key](fo_primary-keys-objects.html). -Examples of usage: +Examples of usage: -* [Processing one object](fo_processing-one-object.html), -* [Example of load changes of the object](fo_load-alter-objects.html). +* [Processing one object](fo_processing-one-object.html), +* [Example of load changes of the object](fo_load-alter-objects.html). -### download of the data object primary key +### download of the data object primary key -Fetch only the own properties of the object. In the absence of a data store object with the specified primary key, an exception will be thrown `CantFindDataObjectException`. Do not use this method overload to decide data object, applicable to overloading methods with optional parameters. +Fetch only the own properties of the object. In the absence of a data store object with the specified primary key, an exception will be thrown `CantFindDataObjectException`. Do not use this method overload to decide data object, applicable to overloading methods with optional parameters. ```csharp -// 1. +// 1. void LoadObject(ICSSoft.STORMNET.DataObject dobject) -// 2. +// 2. void LoadObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -``` +``` -#### Settings +#### Settings -`dobject` - the data Object that you want to download +`dobject` - the data Object that you want to download -### download of the object data representation +### download of the object data representation -Load only those properties that are specified in [view](fd_view-definition.html). +Load only those properties that are specified in [view](fd_view-definition.html). ```csharp -// 1. +// 1. void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject) -// 2. +// 2. void LoadObject(void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject) -// 3. +// 3. void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -// 4. +// 4. void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -``` +``` -#### Settings +#### Settings -`dataObjectView(dataObjectViewName)` - [view](fd_view-definition.html) (view name) +`dataObjectView(dataObjectViewName)` - [view](fd_view-definition.html) (view name) -### download of the data object specifying additional parameters +### download of the data object specifying additional parameters This method overload can be used, in particular, to perform [reload object properties](fo_additional-loading.html). ```csharp -// 1. +// 1. void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) -// 2. +// 2. void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) -// 3. +// 3. void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) -// 4. -void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) +// 4. +void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) -// 5. +// 5. void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) -// 6. +// 6. void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) -``` +``` -#### Settings +#### Settings -* `ClearDataObject` - clear whether the object -* `CheckExistingObject` is to check whether the object exists in the repository (if you specify `true`, in the absence of the object in the database an exception will be thrown of type `CantFindDataObjectException`) +* `ClearDataObject` - clear whether the object +* `CheckExistingObject` is to check whether the object exists in the repository (if you specify `true`, in the absence of the object in the database an exception will be thrown of type `CantFindDataObjectException`) -## updating a single data object +## updating a single data object -To update one data object are method overloads `UpdateObject`. +To update one data object are method overloads `UpdateObject`. -Examples of usage: +Examples of usage: -* [Processing one object](fo_processing-one-object.html), -* [Example of load changes of the object](fo_load-alter-objects.html). +* [Processing one object](fo_processing-one-object.html), +* [Example of load changes of the object](fo_load-alter-objects.html). -If before saving requires the implementation of certain actions, they can be implemented in the business server [this way](fo_actions-saving-object.html). +If before saving requires the implementation of certain actions, they can be implemented in the business server [this way](fo_actions-saving-object.html). -It should be borne in mind that the preservation of the object may cause [saving related objects](fo_update-related-objects.html). +It should be borne in mind that the preservation of the object may cause [saving related objects](fo_update-related-objects.html). -The update of the data object. +The update of the data object. ```csharp -// 1. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject) +// 1. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject) -// 2. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject) +// 2. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject) -// 3. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) +// 3. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -// 4. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) +// 4. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -// 5. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) +// 5. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) -// 6. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) +// 6. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) -// 7. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache, bool AlwaysThrowException) -``` +// 7. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache, bool AlwaysThrowException) +``` -#### Settings +#### Settings -* `dobject` - the data object to be updated -* `DataObjectCache` - object cache -* `AlwaysThrowException` - If an error occurred in the database, not attempt any other queries, just to cock a mistake and roll back the transaction +* `dobject` - the data object to be updated +* `DataObjectCache` - object cache +* `AlwaysThrowException` - If an error occurred in the database, not attempt any other queries, just to cock a mistake and roll back the transaction -## Update multiple data objects +## Update multiple data objects -To update multiple data objects are overloads of the `UpdateObjects`. -Requests for all updated objects are executed in the same transaction. +To update multiple data objects are overloads of the `UpdateObjects`. +Requests for all updated objects are executed in the same transaction. -Updated data objects can be homogeneous and heterogeneous. In the method they are passed a parameter a one-dimensional array of type [DataObject](fo_data-object.html)[]. -In General, the service data is able to build himself the order of the queries to update the data objects. But possible situation when the related objects are important, the order of the objects in the array, detailed information about the order of saving objects is presented in [Processing multiple objects](fo_processing-multiple-objects.html). +Updated data objects can be homogeneous and heterogeneous. In the method they are passed a parameter a one-dimensional array of type [DataObject](fo_data-object.html)[]. +In General, the service data is able to build himself the order of the queries to update the data objects. But possible situation when the related objects are important, the order of the objects in the array, detailed information about the order of saving objects is presented in [Processing multiple objects](fo_processing-multiple-objects.html). -It should be borne in mind that for each element of the array, maintaining it may cause [saving related objects](fo_update-related-objects.html). +It should be borne in mind that for each element of the array, maintaining it may cause [saving related objects](fo_update-related-objects.html). -[Example usage](fo_instantiate-persist-objects.html). +[Example usage](fo_instantiate-persist-objects.html). -Update multiple data objects in the repository. +Update multiple data objects in the repository. ```csharp -// 1. +// 1. void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects) -// 2. +// 2. void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, bool AlwaysThrowException) -// 3. +// 3. void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache) -// 4. +// 4. void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache, bool AlwaysThrowException) -``` +``` -#### Settings +#### Settings -* `objects` - object to update -* `DataObjectCache` - object cache -* `AlwaysThrowException` - if an error occurred in the database, not attempt any other queries, just to cock a mistake and roll back the transaction +* `objects` - object to update +* `DataObjectCache` - object cache +* `AlwaysThrowException` - if an error occurred in the database, not attempt any other queries, just to cock a mistake and roll back the transaction -## Loading without object creation +## Loading without object creation -You can download from the store without instantiating every object in this case is represented as a string of property values delimited. Used when you should not edit the objects. This method is much faster than creating objects when you load the method `LoadObjects`. To download in the form of the string representation is designed method overload `LoadStringedObjectView`. +You can download from the store without instantiating every object in this case is represented as a string of property values delimited. Used when you should not edit the objects. This method is much faster than creating objects when you load the method `LoadObjects`. To download in the form of the string representation is designed method overload `LoadStringedObjectView`. -[Example usage](fo_load-limitation-example.html). +[Example usage](fo_load-limitation-example.html). -### Loading without object creation +### Loading without object creation -__The result is__: an array of structures `ObjectStringDataView` +__The result is__: an array of structures `ObjectStringDataView` ```csharp ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct) -``` +``` -#### Settings +#### Settings -* `separator` separator in strings -* `customizationStruct` - nastroika structure of the sample [LoadingCustomizationStruct](fo_loading-customization-struct.html) +* `separator` separator in strings +* `customizationStruct` - nastroika structure of the sample [LoadingCustomizationStruct](fo_loading-customization-struct.html) -__Note__: the order of object properties data in the result string with the delimiters specified by parameter `ColumnsOrder` structure `customizationStruct`. +__Note__: the order of object properties data in the result string with the delimiters specified by parameter `ColumnsOrder` structure `customizationStruct`. -### Download without creating objects using state of the proofreading (to implement batch reading) +### Download without creating objects using state of the proofreading (to implement batch reading) -1.`LoadStringedObjectView` +1.`LoadStringedObjectView` -* Getting the first batch [batch reading](fo_reading-portion.html). In addition to serving data, the data service returns a read state. This condition is transmitted to the data service to retrieve the next portion in subsequent calls. +* Getting the first batch [batch reading](fo_reading-portion.html). In addition to serving data, the data service returns a read state. This condition is transmitted to the data service to retrieve the next portion in subsequent calls. ```csharp ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct, ref object State) -``` +``` -* Getting another batch [batch reading](fo_reading-portion.html). Must be preceded by a call to the previous overload. +* Getting another batch [batch reading](fo_reading-portion.html). Must be preceded by a call to the previous overload. ```csharp ObjectStringDataView[] LoadStringedObjectView(ref object state) -``` +``` -2.`CompleteLoadStringedObjectView` +2.`CompleteLoadStringedObjectView` -The correct operation to complete a portion of reading at `LoadStringedObjectView`. +The correct operation to complete a portion of reading at `LoadStringedObjectView`. ```csharp void CompleteLoadStringedObjectView(ref object state) -``` +``` -#### Settings +#### Settings -* `State` - a State of proof-reading(for the subsequent decide) -* `customizationStruct` - [adjusting structure for a sample](fo_loading-customization-struct.html) +* `State` - a State of proof-reading(for the subsequent decide) +* `customizationStruct` - [adjusting structure for a sample](fo_loading-customization-struct.html) -__Note__: the batch Size can be specified with the parameter `LoadingBufferSize` structure [LoadingCustomizationStruct](fo_loading-customization-struct.html). +__Note__: the batch Size can be specified with the parameter `LoadingBufferSize` structure [LoadingCustomizationStruct](fo_loading-customization-struct.html). -## a number of objects that satisfy the query +## a number of objects that satisfy the query -[Example usage](fo_load-limitation-example.html). +[Example usage](fo_load-limitation-example.html). -Returns the number of objects satisfying conditions of the sample,without performing a data load. +Returns the number of objects satisfying conditions of the sample,without performing a data load. -`GetObjectsCount` +`GetObjectsCount` ```csharp int GetObjectsCount(LoadingCustomizationStruct customizationStruct) -``` +``` -#### Settings +#### Settings -`customizationStruct` - adjusting structure for a sample of [LoadingCustomizationStruct](fo_loading-customization-struct.html) +`customizationStruct` - adjusting structure for a sample of [LoadingCustomizationStruct](fo_loading-customization-struct.html) -## Use SQL when working with data service +## Use SQL when working with data service -In some situations, the service data is not enough to solve specific problems, in such cases, there is a possibility [of a direct SQL query](fo_sql-query.html) and [the change is automatically built query](fo_intercept-formation-sql-query.html). +In some situations, the service data is not enough to solve specific problems, in such cases, there is a possibility [of a direct SQL query](fo_sql-query.html) and [the change is automatically built query](fo_intercept-formation-sql-query.html). diff --git a/pages/products/flexberry-orm/data-service/fo_data-service.ru.md b/pages/products/flexberry-orm/data-service/fo_data-service.ru.md index 49566d950..aa9725fd5 100644 --- a/pages/products/flexberry-orm/data-service/fo_data-service.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_data-service.ru.md @@ -1,356 +1,356 @@ ---- -title: Сервис данных -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, загрузка объектов данных, обновление объектов данных -summary: Особенности работы с объектами данных с использованием сервиса данных -toc: true -permalink: ru/fo_data-service.html -lang: ru ---- - -**Сервис данных** - компонент Flexberry ORM, обеспечивающий запись и чтение объектов данных в хранилище. В объектной модели Flexberry ORM сервис данных представлен классом, реализующим интерфейс `ICSSoft.STORMNET.Business.IDataService`. -Поддерживается несколько [стандартных сервисов данных](fo_standard-data-services.html), и при необходимости пользователями могут быть [разработаны](fo_implement-custom-ds.html) новые, удовлетворяющие специфическим требованиям (например, наследуя классы `ICSSoft.STORMNET.Business.ODBCDataService.ODBCDataService` или `ICSSoft.STORMNET.Business.`[`SQLDataService`](fo_sql-data-service.html)). - -{% include important.html content="При обращении к сервису данных в программном коде рекомендуется производить через интерфейс `ICSSoft.STORMNET.Business.IDataService`, т.к. это гарантирует независимость кода от типа хранилища данных." %} - -Перед использованием сервиса данных в программном коде его необходимо [настроить тем или иным способом](fo_construction-ds.html). - -Следует __обратить внимание__ на следующие моменты: - -* Существует возможность настроить сервис данных таким образом, чтобы на регистрозависимом источнике данных приложение вело себя как при работе с [регистронезависимым источником](fo_insensitivity-register-ds.html). -* Сервис данных [особым образом работает с логическим типом](fo_interpretation-boolean-null.html). - -## Основные возможности сервиса данных - -Перед обращением в программном коде к сервису данных на него необходимо получить [ссылку](fo_ds-provider.html). При одновременном использовании нескольких хранилищ необходимо учесть некоторые [особенности](fo_multibase.html). - -Интерфейс `ICSSoft.STORMNET.Business.IDataService` содержит следующие основные группы методов: - -* __Методы с именами типа__ `UpdateXXXXXXXX`, предназначенные для приведения хранилища данных ([обновление, удаление, создание записей](fo_object-status.html)) в соответствие с переданными одним или несколькими объектами данных: - * `UpdateObject` - обновление одного объекта. - * `UpdateObjects` - обновление нескольких объектов. -* __Методы с именами типа__ `LoadXXXXXXXX`, предназначенные для чтения одного, либо нескольких объектов данных. - * `LoadObject` - загрузка объекта (в зависимости от параметров с помощью данного метода можно осуществлять [дочитку объекта](fo_additional-loading.html)). - * `LoadObjects` - загрузка объектов (в т.ч. перегрузки метода позволяют реализовать [порционное стение](fo_reading-portion.html), [чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html)). -* __Загрузка без создания объектов__ `LoadStringedObjectView`. -* __Метод получения количества объектов__, удовлетворяющих условию `GetObjectsCount`. - -Большинство методов чтения/записи имеют перегрузки, принимающие дополнительный параметр [DataObjectCache](fo_context-sensitive-cache.html), позволяющий поддерживать одну инстанцию для нескольких экземпляров объектов. Передавать `DataObjectCache` в методы зачитки нужно в том случае, если какой-то объект уже существует в памяти и после зачитки все ссылки на него должны указывать именно на этот объект. В методы обновления данный параметр передается для верной расстановки ссылок на экземпляры данных из кэша в связи с тем, что после сохранения в хранилище происходит обновление свойств объекта данных и инициализация его копии данных. - -Подробнее об особенностях использовании кэша см. в статье [Контекстно-зависимый кэш объектов данных](fo_context-sensitive-cache.html). - -Ниже, при рассмотрении методов, перегрузки с параметром `DataObjectCache` отдельно не описываются. - -## Загрузка объектов данных - -Для загрузки нескольких объектов данных служат перегрузки метода `LoadObjects`. - -### Загрузка объектов данных по представлению или массиву представлений - -* Загружаются все объекты данных, доступные в хранилище. При этом выполняется загрузка только тех свойств, которые указаны в [представлении](fd_view-definition.html). - -```csharp -ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View dataObjectView); -``` - -* Происходит последовательный вызов метода с параметром - представление для каждого элемента массива. Практическая применимость данной перегрузки неочевидна. - -```csharp -ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View[] dataObjectViews); -``` - -*Параметры* - -`dataObjectView(s)` - представление или массив представлений - -### Загрузка объектов данных по настроечной структуре для выборки LoadingCustomizationStruct (массиву структур) - -* Данная перегрузка метода позволяет тонко настроить выборку загружаемых объектов за счёт использования структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html): - - * указать представление (вертикальное ограничение выборки: загрузка только определенных свойств), - * количество возвращаемых строк (для реляционных хранилищ ограничение `TOP` в `SELECT`), - * параметры сортировки возвращаемых результатов (`ORDER BY`), - * ограничения на вычитываемые объекты данных (`WHERE`) - * и т.д.. Подробнее см. описание [LoadingCustomizationStruct](fo_loading-customization-struct.html). - - [Пример использования](fo_load-limitation-example.html). - -_Замечание_: Данная перегрузка позволяет реализовать [чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html). - -```csharp -// 1. -ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct); - -// 2. -ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, DataObjectCache DataObjectCache); -``` - -* Происходит последовательный вызов метода с параметром - `LoadingCustomizationStruct` для каждого элемента массива. Практическая применимость данной перегрузки неочевидна. - -```csharp -ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct[] customizationStructs); -``` - -*Параметры* - -`customizationStruct(s)` - [настроечная структура для выборки](fo_loading-customization-struct.html) (массив структур) - -### Загрузка объектов с использованием состояния вычитки (для реализации порционного чтения) - -* Получение первой порции при [порционном чтении](fo_reading-portion.html). Кроме порции объектов данных, сервис данных возвращает некоторое состояние чтения. Это состояние передается сервису данных для получения очередных порций при последующих вызовах (см. Загрузка одного объекта данных). - -```csharp -// 1. -ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct,ref object State); - -// 2. -ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, ref object State, DataObjectCache DataObjectCache); -``` - -* Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов в указанной выше перегрузке. - -```csharp -// 1. -ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State); - -// 2. -ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State, DataObjectCache DataObjectCache); -``` - -*Параметры* - -* `State` - Состояние вычитки(для последующей дочитки) -* `customizationStruct` - [настроечная структура для выборки](fo_loading-customization-struct.html) - -_Примечание_: Размер порции может быть задан с помощью параметра `LoadingBufferSize` структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html). - -## Загрузка одного объекта данных - -Для загрузки одного объекта данных служат перегрузки метода `LoadObject`. -Вычитка свойств из хранилища осуществляется по заданному в объекте данных [первичному ключу](fo_primary-keys-objects.html). - -*Примеры использования:* - -* [Обработка одного объекта](fo_processing-one-object.html), -* [Пример загрузки и изменения объекта](fo_load-alter-objects.html). - -### Загрузка объекта данных по первичному ключу - -Будут загружены только собственные свойства объекта. При отсутствии в хранилище данных объекта с заданным первичным ключом будет выдано исключение `CantFindDataObjectException`. Не следует использовать данную перегрузку метода для дочитки объекта данных, для этого применимы перегрузки методы с дополнительными параметрами. - -```csharp -// 1. -void LoadObject(ICSSoft.STORMNET.DataObject dobject) - -// 2. -void LoadObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -``` - -*Параметры* - -`dobject` - Объект данных, который требуется загрузить - -### Загрузка объекта данных по представлению - -Выполняется загрузка только тех свойств, которые указаны в [представлении](fd_view-definition.html). - -```csharp -// 1. -void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject) - -// 2. -void LoadObject(void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject) - -// 3. -void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) - -// 4. -void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) -``` - -*Параметры* - -`dataObjectView(dataObjectViewName)` - [представление](fd_view-definition.html) (имя представления) - -### Загрузка объекта данных с указанием дополнительных параметров - -Данная перегрузка метода может быть использована, в частности, для выполнения [догрузки свойств объекта](fo_additional-loading.html). - -```csharp -// 1. -void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) - -// 2. -void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) - -// 3. -void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) - -// 4. -void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) - -// 5. -void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) - -// 6. -void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) -``` - -*Параметры* - -* `ClearDataObject` - очищать ли объект -* `CheckExistingObject` - проверять ли существование объекта в хранилище (если указать `true`, при отсутствии объекта в базе будет выдано исключение типа `CantFindDataObjectException`) - -## Обновление одного объекта данных - -Для обновления одного объекта данных служат перегрузки метода `UpdateObject`. - -Примеры использования: - -* [Обработка одного объекта](fo_processing-one-object.html), -* [Пример загрузки и изменения объекта](fo_load-alter-objects.html). - -Если перед выполнением сохранения требуется выполнение определенных действий, они могут быть реализованы в бизнес-сервере [указанным способом](fo_actions-saving-object.html). - -Следует иметь в виду, что сохранение объекта может вызвать [сохранение связанных с ним объектов](fo_update-related-objects.html). - -Обновление объекта данных. - -```csharp -// 1. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject) - -// 2. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject) - -// 3. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) - -// 4. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) - -// 5. -void UpdateObject(ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) - -// 6. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) - -// 7. -void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache, bool AlwaysThrowException) -``` - -*Параметры* - -* `dobject` - объект данных, который требуется обновить -* `DataObjectCache` - кеш объектов -* `AlwaysThrowException` - Если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию - -## Обновление нескольких объектов данных - -Для обновления нескольких объектов данных служат перегрузки метода `UpdateObjects`. -Запросы для всех обновляемых объектов выполняются в единой транзакции. - -Обновляемые объекты данных могут быть как однотипными, так и разнотипными. В метод они передаются параметром — одномерным массивом типа [DataObject](fo_data-object.html)[]. -В общем случае сервис данных умеет сам выстраивать порядок запросов на обновление объектов данных. Но возможны ситуации, когда для связанных объектов важен порядок следования объектов в массиве, подробная информация о порядке сохранения объектов приведена в статье [Обработка множества объектов](fo_processing-multiple-objects.html). - -Следует иметь в виду, что для каждого элемента массива его сохранение может вызвать [сохранение связанных с ним объектов](fo_update-related-objects.html). - -[Пример использования](fo_instantiate-persist-objects.html). - -Обновление нескольких объектов данных в хранилище. - -```csharp -// 1. -void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects) - -// 2. -void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, bool AlwaysThrowException) - -// 3. -void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache) - -// 4. -void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache, bool AlwaysThrowException) -``` - -*Параметры* - -* `objects` - объекты для обновления -* `DataObjectCache` - кеш объектов -* `AlwaysThrowException` - если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию - -## Загрузка без создания объектов - -Можно выполнить загрузку из хранилища без создания экземпляров: каждый объект в этом случае представлен в виде строки из значений свойств с разделителями. Используется, когда не требуется редактирование объектов. Данный метод намного быстрее, чем создание объектов при загрузке в методе `LoadObjects`. Для загрузки в виде строкового представления предназначены перегрузки метода `LoadStringedObjectView`. - -[Пример использования](fo_load-limitation-example.html). - -__Возвращаемый результат__: массив структур `ObjectStringDataView` - -```csharp -ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct) -``` - -*Параметры* - -* `separator` - разделитель в строках -* `customizationStruct` - настроичная структура для выборки [LoadingCustomizationStruct](fo_loading-customization-struct.html) - -__Примечание__: порядок следования свойств объекта данных в результирующей строке с разделителями задаётся парметром `ColumnsOrder` структуры `customizationStruct`. - -### Загрузка без создания объектов с использованием состояния вычитки (для реализации порционного чтения) - -1.`LoadStringedObjectView` - -* Получение первой порции при [порционном чтении](fo_reading-portion.html). Кроме порции данных, сервис данных возвращает некоторое состояние чтения. Это состояние передается сервису данных для получения очередных порций при последующих вызовах. - -```csharp -ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct, ref object State) -``` - -* Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов в предыдущей перегрузке. - -```csharp -ObjectStringDataView[] LoadStringedObjectView(ref object state) -``` - -2.`CompleteLoadStringedObjectView` - -Корректное завершения операции порционного чтения при `LoadStringedObjectView`. - -```csharp -void CompleteLoadStringedObjectView(ref object state) -``` - -*Параметры* - -* `State` - Состояние вычитки(для последующей дочитки) -* `customizationStruct` - [настроечная структура для выборки](fo_loading-customization-struct.html) - -__Примечание__: Размер порции может быть задан с помощью параметра `LoadingBufferSize` структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html). - -## Получение количества объектов, удовлетворяющих запросу - -[Пример использования](fo_load-limitation-example.html). - -Возвращает количество объектов удовлетворяющих условиям выборки,не выполняя загрузку данных. - -`GetObjectsCount` - -```csharp -int GetObjectsCount(LoadingCustomizationStruct customizationStruct) -``` - -*Параметры* - -`customizationStruct` - настроечная структура для выборки [LoadingCustomizationStruct](fo_loading-customization-struct.html) - -## Использование SQL при работе с сервисом данных - -В некоторых ситуациях возможностей сервиса данных недостаточно для решения специфических задач, в таких случаях есть возможность [непосредственного выполнения SQL-запроса](fo_sql-query.html) и [изменение автоматически построенного запроса](fo_intercept-formation-sql-query.html). - -## Асинхронные запросы в ORM - -В [ORM](fo_flexberry-orm.html) существует возможность загружать данные в асинхронном режиме (async/await). `SQLDataService` реализует интерфейс `IAsyncDataService`, который описывает асинхронные методы загрузки. - -Подробнее в статье [Асинхронные запросы в ORM](fo_asynchronous_requests_in_orm.html). \ No newline at end of file +--- +title: Сервис данных +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, загрузка объектов данных, обновление объектов данных +summary: Особенности работы с объектами данных с использованием сервиса данных +toc: true +permalink: ru/fo_data-service.html +lang: ru +--- + +**Сервис данных** - компонент Flexberry ORM, обеспечивающий запись и чтение объектов данных в хранилище. В объектной модели Flexberry ORM сервис данных представлен классом, реализующим интерфейс `ICSSoft.STORMNET.Business.IDataService`. +Поддерживается несколько [стандартных сервисов данных](fo_standard-data-services.html), и при необходимости пользователями могут быть [разработаны](fo_implement-custom-ds.html) новые, удовлетворяющие специфическим требованиям (например, наследуя класс `ICSSoft.STORMNET.Business.`[`SQLDataService`](fo_sql-data-service.html)). + +{% include important.html content="При обращении к сервису данных в программном коде рекомендуется производить через интерфейс `ICSSoft.STORMNET.Business.IDataService`, т.к. это гарантирует независимость кода от типа хранилища данных." %} + +Перед использованием сервиса данных в программном коде его необходимо [настроить тем или иным способом](fo_construction-ds.html). + +Следует __обратить внимание__ на следующие моменты: + +* Существует возможность настроить сервис данных таким образом, чтобы на регистрозависимом источнике данных приложение вело себя как при работе с [регистронезависимым источником](fo_insensitivity-register-ds.html). +* Сервис данных [особым образом работает с логическим типом](fo_interpretation-boolean-null.html). + +## Основные возможности сервиса данных + +Перед обращением в программном коде к сервису данных на него необходимо получить [ссылку](fo_ds-provider.html). При одновременном использовании нескольких хранилищ необходимо учесть некоторые [особенности](fo_multibase.html). + +Интерфейс `ICSSoft.STORMNET.Business.IDataService` содержит следующие основные группы методов: + +* __Методы с именами типа__ `UpdateXXXXXXXX`, предназначенные для приведения хранилища данных ([обновление, удаление, создание записей](fo_object-status.html)) в соответствие с переданными одним или несколькими объектами данных: + * `UpdateObject` - обновление одного объекта. + * `UpdateObjects` - обновление нескольких объектов. +* __Методы с именами типа__ `LoadXXXXXXXX`, предназначенные для чтения одного, либо нескольких объектов данных. + * `LoadObject` - загрузка объекта (в зависимости от параметров с помощью данного метода можно осуществлять [дочитку объекта](fo_additional-loading.html)). + * `LoadObjects` - загрузка объектов (в т.ч. перегрузки метода позволяют реализовать [порционное стение](fo_reading-portion.html), [чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html)). +* __Загрузка без создания объектов__ `LoadStringedObjectView`. +* __Метод получения количества объектов__, удовлетворяющих условию `GetObjectsCount`. + +Большинство методов чтения/записи имеют перегрузки, принимающие дополнительный параметр [DataObjectCache](fo_context-sensitive-cache.html), позволяющий поддерживать одну инстанцию для нескольких экземпляров объектов. Передавать `DataObjectCache` в методы зачитки нужно в том случае, если какой-то объект уже существует в памяти и после зачитки все ссылки на него должны указывать именно на этот объект. В методы обновления данный параметр передается для верной расстановки ссылок на экземпляры данных из кэша в связи с тем, что после сохранения в хранилище происходит обновление свойств объекта данных и инициализация его копии данных. + +Подробнее об особенностях использовании кэша см. в статье [Контекстно-зависимый кэш объектов данных](fo_context-sensitive-cache.html). + +Ниже, при рассмотрении методов, перегрузки с параметром `DataObjectCache` отдельно не описываются. + +## Загрузка объектов данных + +Для загрузки нескольких объектов данных служат перегрузки метода `LoadObjects`. + +### Загрузка объектов данных по представлению или массиву представлений + +* Загружаются все объекты данных, доступные в хранилище. При этом выполняется загрузка только тех свойств, которые указаны в [представлении](fd_view-definition.html). + +```csharp +ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View dataObjectView); +``` + +* Происходит последовательный вызов метода с параметром - представление для каждого элемента массива. Практическая применимость данной перегрузки неочевидна. + +```csharp +ICSSoft.STORMNET.DataObject[] LoadObjects(ICSSoft.STORMNET.View[] dataObjectViews); +``` + +*Параметры* + +`dataObjectView(s)` - представление или массив представлений + +### Загрузка объектов данных по настроечной структуре для выборки LoadingCustomizationStruct (массиву структур) + +* Данная перегрузка метода позволяет тонко настроить выборку загружаемых объектов за счёт использования структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html): + + * указать представление (вертикальное ограничение выборки: загрузка только определенных свойств), + * количество возвращаемых строк (для реляционных хранилищ ограничение `TOP` в `SELECT`), + * параметры сортировки возвращаемых результатов (`ORDER BY`), + * ограничения на вычитываемые объекты данных (`WHERE`) + * и т.д.. Подробнее см. описание [LoadingCustomizationStruct](fo_loading-customization-struct.html). + + [Пример использования](fo_load-limitation-example.html). + +_Замечание_: Данная перегрузка позволяет реализовать [чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html). + +```csharp +// 1. +ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct); + +// 2. +ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, DataObjectCache DataObjectCache); +``` + +* Происходит последовательный вызов метода с параметром - `LoadingCustomizationStruct` для каждого элемента массива. Практическая применимость данной перегрузки неочевидна. + +```csharp +ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct[] customizationStructs); +``` + +*Параметры* + +`customizationStruct(s)` - [настроечная структура для выборки](fo_loading-customization-struct.html) (массив структур) + +### Загрузка объектов с использованием состояния вычитки (для реализации порционного чтения) + +* Получение первой порции при [порционном чтении](fo_reading-portion.html). Кроме порции объектов данных, сервис данных возвращает некоторое состояние чтения. Это состояние передается сервису данных для получения очередных порций при последующих вызовах (см. Загрузка одного объекта данных). + +```csharp +// 1. +ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct,ref object State); + +// 2. +ICSSoft.STORMNET.DataObject[] LoadObjects(LoadingCustomizationStruct customizationStruct, ref object State, DataObjectCache DataObjectCache); +``` + +* Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов в указанной выше перегрузке. + +```csharp +// 1. +ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State); + +// 2. +ICSSoft.STORMNET.DataObject[] LoadObjects(ref object State, DataObjectCache DataObjectCache); +``` + +*Параметры* + +* `State` - Состояние вычитки(для последующей дочитки) +* `customizationStruct` - [настроечная структура для выборки](fo_loading-customization-struct.html) + +_Примечание_: Размер порции может быть задан с помощью параметра `LoadingBufferSize` структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html). + +## Загрузка одного объекта данных + +Для загрузки одного объекта данных служат перегрузки метода `LoadObject`. +Вычитка свойств из хранилища осуществляется по заданному в объекте данных [первичному ключу](fo_primary-keys-objects.html). + +*Примеры использования:* + +* [Обработка одного объекта](fo_processing-one-object.html), +* [Пример загрузки и изменения объекта](fo_load-alter-objects.html). + +### Загрузка объекта данных по первичному ключу + +Будут загружены только собственные свойства объекта. При отсутствии в хранилище данных объекта с заданным первичным ключом будет выдано исключение `CantFindDataObjectException`. Не следует использовать данную перегрузку метода для дочитки объекта данных, для этого применимы перегрузки методы с дополнительными параметрами. + +```csharp +// 1. +void LoadObject(ICSSoft.STORMNET.DataObject dobject) + +// 2. +void LoadObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) +``` + +*Параметры* + +`dobject` - Объект данных, который требуется загрузить + +### Загрузка объекта данных по представлению + +Выполняется загрузка только тех свойств, которые указаны в [представлении](fd_view-definition.html). + +```csharp +// 1. +void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject) + +// 2. +void LoadObject(void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject) + +// 3. +void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) + +// 4. +void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) +``` + +*Параметры* + +`dataObjectView(dataObjectViewName)` - [представление](fd_view-definition.html) (имя представления) + +### Загрузка объекта данных с указанием дополнительных параметров + +Данная перегрузка метода может быть использована, в частности, для выполнения [догрузки свойств объекта](fo_additional-loading.html). + +```csharp +// 1. +void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) + +// 2. +void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) + +// 3. +void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject) + +// 4. +void LoadObject(ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) + +// 5. +void LoadObject(string dataObjectViewName, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) + +// 6. +void LoadObject(ICSSoft.STORMNET.View dataObjectView, ICSSoft.STORMNET.DataObject dobject, bool ClearDataObject, bool CheckExistingObject, DataObjectCache DataObjectCache) +``` + +*Параметры* + +* `ClearDataObject` - очищать ли объект +* `CheckExistingObject` - проверять ли существование объекта в хранилище (если указать `true`, при отсутствии объекта в базе будет выдано исключение типа `CantFindDataObjectException`) + +## Обновление одного объекта данных + +Для обновления одного объекта данных служат перегрузки метода `UpdateObject`. + +Примеры использования: + +* [Обработка одного объекта](fo_processing-one-object.html), +* [Пример загрузки и изменения объекта](fo_load-alter-objects.html). + +Если перед выполнением сохранения требуется выполнение определенных действий, они могут быть реализованы в бизнес-сервере [указанным способом](fo_actions-saving-object.html). + +Следует иметь в виду, что сохранение объекта может вызвать [сохранение связанных с ним объектов](fo_update-related-objects.html). + +Обновление объекта данных. + +```csharp +// 1. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject) + +// 2. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject) + +// 3. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) + +// 4. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache) + +// 5. +void UpdateObject(ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) + +// 6. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, bool AlwaysThrowException) + +// 7. +void UpdateObject(ref ICSSoft.STORMNET.DataObject dobject, DataObjectCache DataObjectCache, bool AlwaysThrowException) +``` + +*Параметры* + +* `dobject` - объект данных, который требуется обновить +* `DataObjectCache` - кеш объектов +* `AlwaysThrowException` - Если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию + +## Обновление нескольких объектов данных + +Для обновления нескольких объектов данных служат перегрузки метода `UpdateObjects`. +Запросы для всех обновляемых объектов выполняются в единой транзакции. + +Обновляемые объекты данных могут быть как однотипными, так и разнотипными. В метод они передаются параметром — одномерным массивом типа [DataObject](fo_data-object.html)[]. +В общем случае сервис данных умеет сам выстраивать порядок запросов на обновление объектов данных. Но возможны ситуации, когда для связанных объектов важен порядок следования объектов в массиве, подробная информация о порядке сохранения объектов приведена в статье [Обработка множества объектов](fo_processing-multiple-objects.html). + +Следует иметь в виду, что для каждого элемента массива его сохранение может вызвать [сохранение связанных с ним объектов](fo_update-related-objects.html). + +[Пример использования](fo_instantiate-persist-objects.html). + +Обновление нескольких объектов данных в хранилище. + +```csharp +// 1. +void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects) + +// 2. +void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, bool AlwaysThrowException) + +// 3. +void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache) + +// 4. +void UpdateObjects(ref ICSSoft.STORMNET.DataObject[] objects, DataObjectCache DataObjectCache, bool AlwaysThrowException) +``` + +*Параметры* + +* `objects` - объекты для обновления +* `DataObjectCache` - кеш объектов +* `AlwaysThrowException` - если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию + +## Загрузка без создания объектов + +Можно выполнить загрузку из хранилища без создания экземпляров: каждый объект в этом случае представлен в виде строки из значений свойств с разделителями. Используется, когда не требуется редактирование объектов. Данный метод намного быстрее, чем создание объектов при загрузке в методе `LoadObjects`. Для загрузки в виде строкового представления предназначены перегрузки метода `LoadStringedObjectView`. + +[Пример использования](fo_load-limitation-example.html). + +__Возвращаемый результат__: массив структур `ObjectStringDataView` + +```csharp +ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct) +``` + +*Параметры* + +* `separator` - разделитель в строках +* `customizationStruct` - настроичная структура для выборки [LoadingCustomizationStruct](fo_loading-customization-struct.html) + +__Примечание__: порядок следования свойств объекта данных в результирующей строке с разделителями задаётся парметром `ColumnsOrder` структуры `customizationStruct`. + +### Загрузка без создания объектов с использованием состояния вычитки (для реализации порционного чтения) + +1.`LoadStringedObjectView` + +* Получение первой порции при [порционном чтении](fo_reading-portion.html). Кроме порции данных, сервис данных возвращает некоторое состояние чтения. Это состояние передается сервису данных для получения очередных порций при последующих вызовах. + +```csharp +ObjectStringDataView[] LoadStringedObjectView(char separator, LoadingCustomizationStruct customizationStruct, ref object State) +``` + +* Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов в предыдущей перегрузке. + +```csharp +ObjectStringDataView[] LoadStringedObjectView(ref object state) +``` + +2.`CompleteLoadStringedObjectView` + +Корректное завершения операции порционного чтения при `LoadStringedObjectView`. + +```csharp +void CompleteLoadStringedObjectView(ref object state) +``` + +*Параметры* + +* `State` - Состояние вычитки(для последующей дочитки) +* `customizationStruct` - [настроечная структура для выборки](fo_loading-customization-struct.html) + +__Примечание__: Размер порции может быть задан с помощью параметра `LoadingBufferSize` структуры [LoadingCustomizationStruct](fo_loading-customization-struct.html). + +## Получение количества объектов, удовлетворяющих запросу + +[Пример использования](fo_load-limitation-example.html). + +Возвращает количество объектов удовлетворяющих условиям выборки,не выполняя загрузку данных. + +`GetObjectsCount` + +```csharp +int GetObjectsCount(LoadingCustomizationStruct customizationStruct) +``` + +*Параметры* + +`customizationStruct` - настроечная структура для выборки [LoadingCustomizationStruct](fo_loading-customization-struct.html) + +## Использование SQL при работе с сервисом данных + +В некоторых ситуациях возможностей сервиса данных недостаточно для решения специфических задач, в таких случаях есть возможность [непосредственного выполнения SQL-запроса](fo_sql-query.html) и [изменение автоматически построенного запроса](fo_intercept-formation-sql-query.html). + +## Асинхронные запросы в ORM + +В [ORM](fo_flexberry-orm.html) существует возможность загружать данные в асинхронном режиме (async/await). `SQLDataService` реализует интерфейс `IAsyncDataService`, который описывает асинхронные методы загрузки. + +Подробнее в статье [Асинхронные запросы в ORM](fo_asynchronous_requests_in_orm.html). diff --git a/pages/products/flexberry-orm/data-service/fo_dr-data-service.en.md b/pages/products/flexberry-orm/data-service/fo_dr-data-service.en.md index c981dc83f..76805fb2c 100644 --- a/pages/products/flexberry-orm/data-service/fo_dr-data-service.en.md +++ b/pages/products/flexberry-orm/data-service/fo_dr-data-service.en.md @@ -1,30 +1,30 @@ ---- -title: DRDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, service data, reading data -summary: Using dirty read -toc: true -permalink: en/fo_dr-data-service.html -lang: en -autotranslated: true -hash: 648bed382e981fa818916b5925393b835f05996a3f34a6c7d94cb6dd1010ad95 ---- +--- +title: DRDataService +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, service data, reading data +summary: Using dirty read +toc: true +permalink: en/fo_dr-data-service.html +lang: en +autotranslated: true +hash: 648bed382e981fa818916b5925393b835f05996a3f34a6c7d94cb6dd1010ad95 +--- -`DRDataService` - [service data](fo_data-service.html), the heir [SQLDataService](fo_sql-data-service.html), has the same functionality as conventional [MSSQLDataService](fo_mssql-data-service.html), but when reading data ["dirty read (dirty read)"](http://msdn.microsoft.com/ru-ru/library/ms173763.aspx). +`DRDataService` - [service data](fo_data-service.html), the heir [SQLDataService](fo_sql-data-service.html), has the same functionality as conventional [MSSQLDataService](fo_mssql-data-service.html), but when reading data ["dirty read (dirty read)"](http://msdn.microsoft.com/ru-ru/library/ms173763.aspx). -## receiving a copy DRDataService +## receiving a copy DRDataService -Instance DRDataService can be obtained through [UnityFactory](fo_unity-factory.html) using the following code: +Instance DRDataService can be obtained through [UnityFactory](fo_unity-factory.html) using the following code: ```csharp - IUnityContainer container = UnityFactory.CreateContainer(); + IUnityContainer container = UnityFactory.CreateContainer(); //UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. IDataService dataService = container.Resolve("DRDataService"); - dataService.CustomizationString = DataServiceProvider.DataService.CustomizationString; -``` + dataService.CustomizationString = DataServiceProvider.DataService.CustomizationString; // DataServiceProvider is deprecated; inject IDataService instead +``` -## Configure DataService +## Configure DataService -Setting `DRDataService` via the configuration file : +Setting `DRDataService` via the configuration file : ```xml @@ -35,15 +35,15 @@ Setting `DRDataService` via the configuration file : - + -``` +``` -The connection string in this example is configured as described in the article about [`DataServiceProvider`](fo_ds-provider.html) +The connection string in this example is configured as described in the article about [`DataServiceProvider`](fo_ds-provider.html) diff --git a/pages/products/flexberry-orm/data-service/fo_dr-data-service.ru.md b/pages/products/flexberry-orm/data-service/fo_dr-data-service.ru.md index 1cff91d06..d32a84610 100644 --- a/pages/products/flexberry-orm/data-service/fo_dr-data-service.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_dr-data-service.ru.md @@ -15,9 +15,9 @@ lang: ru Экземпляр DRDataService можно получить через [UnityFactory](fo_unity-factory.html), выполнив следующий код: ```csharp - IUnityContainer container = UnityFactory.CreateContainer(); + IUnityContainer container = UnityFactory.CreateContainer(); // UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). IDataService dataService = container.Resolve("DRDataService"); - dataService.CustomizationString = DataServiceProvider.DataService.CustomizationString; + dataService.CustomizationString = DataServiceProvider.DataService.CustomizationString; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` ## Настройка DataService @@ -33,7 +33,7 @@ lang: ru - + diff --git a/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.en.md b/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.en.md index 64c4cbd7d..8a56b16b2 100644 --- a/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.en.md +++ b/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.en.md @@ -1,33 +1,33 @@ ---- -title: the Implementation of a random data service -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services -summary: features of the implementation of the service data -toc: true -permalink: en/fo_implement-custom-ds.html -lang: en -autotranslated: true -hash: ad17367b146fb50c53cee21694e4da72732a2448b0586d20b8f0aa3235fa849b ---- +--- +title: the Implementation of a random data service +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, data services +summary: features of the implementation of the service data +toc: true +permalink: en/fo_implement-custom-ds.html +lang: en +autotranslated: true +hash: ad17367b146fb50c53cee21694e4da72732a2448b0586d20b8f0aa3235fa849b +--- -In the General case [service data](fo_data-service.html) must implement interface ICSSoft.STORMNET.Business.IDataService. +In the General case [service data](fo_data-service.html) must implement interface ICSSoft.STORMNET.Business.IDataService. -## implementation of a random data service +## implementation of a random data service -If you must implement your own [service data](fo_data-service.html), should consider the following: +If you must implement your own [service data](fo_data-service.html), should consider the following: -1. You must consider the attributes of storage. The installation of these attributes can be checked by the methods of [Information](fo_methods-class-information.html): GetAssemblyStorageName, GetClassStorageName, GetPropertyStorageName. -2. Classes, [attributes, master detaili can be nejanilini](fo_not-stored-attributes.html), which indicated NotStoredAttribute. The [Information](fo_methods-class-information.html).GetStorablePropertyNames returns the list of stored attributes. -3. First of all be deducted in accordance with the procedure specified by the attribute [LoadingOrderAttribute](fo_order-loading-property.html), then all the rest. The [Information](fo_methods-class-information.html).GetLoadingOrder returns order. -4. In attributes, the wizards could not be allowed empty values, which is specified by the attribute NotNullAttribute. +1. You must consider the attributes of storage. The installation of these attributes can be checked by the methods of [Information](fo_methods-class-information.html): GetAssemblyStorageName, GetClassStorageName, GetPropertyStorageName. +2. Classes, [attributes, master detaili can be nejanilini](fo_not-stored-attributes.html), which indicated NotStoredAttribute. The [Information](fo_methods-class-information.html).GetStorablePropertyNames returns the list of stored attributes. +3. First of all be deducted in accordance with the procedure specified by the attribute [LoadingOrderAttribute](fo_order-loading-property.html), then all the rest. The [Information](fo_methods-class-information.html).GetLoadingOrder returns order. +4. In attributes, the wizards could not be allowed empty values, which is specified by the attribute NotNullAttribute. -To optimize, you need to update only the changed attributes [Information](fo_methods-class-information.html).GetAlteredProperyNames. +To optimize, you need to update only the changed attributes [Information](fo_methods-class-information.html).GetAlteredProperyNames. -## the implementation of the service data for relational storage +## the implementation of the service data for relational storage -If you want to implement the [service data](fo_data-service.html) for relational storage, it is recommended to unasledovala [ready data services Platform Flexberry](fo_standard-data-services.html), in particular, from a common ancestor relational data service [SQLDataService](fo_sql-data-service.html), or [ODBCDataService](fo_odbc-data-service.html). Then, according to features of the repository that you want to use the appropriate overload methods. +If you want to implement the [service data](fo_data-service.html) for relational storage, it is recommended to unasledovala [ready data services Platform Flexberry](fo_standard-data-services.html), in particular, from a common ancestor relational data service [SQLDataService](fo_sql-data-service.html). Then, according to features of the repository that you want to use the appropriate overload methods. -Below is an example of [data service](fo_data-service.html) working with Microsoft SQL Server directly, using the SQLClient: +Below is an example of [data service](fo_data-service.html) working with Microsoft SQL Server directly, using the SQLClient: ``` csharp public class MSSQLDataService:ICSSoft.STORMNET.Business.SQLDataService @@ -43,11 +43,11 @@ public class MSSQLDataService:ICSSoft.STORMNET.Business.SQLDataService for (int i= identifiers.Length-2;i>=0;i--) result = string.Concat("ISNULL(",identifiers[i],", ",result,")"); return result; - } + } } -``` +``` -In this example, the only overridden two methods, one now performs the connection to the source directly, the other takes into account the specific instructions in the query ISNULL. +In this example, the only overridden two methods, one now performs the connection to the source directly, the other takes into account the specific instructions in the query ISNULL. diff --git a/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.ru.md b/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.ru.md index bf9ad963a..9d81d48b9 100644 --- a/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_implement-custom-ds.ru.md @@ -23,7 +23,7 @@ lang: ru ## Реализация сервиса данных для реляционного хранилища -Если требуется реализовать [сервис данных](fo_data-service.html) для реляционного хранилища, рекомендуется унаследоваться от [готовых сервисов данных Flexberry Platform](fo_standard-data-services.html), в частности, от общего предка реляционных сервис данных [SQLDataService](fo_sql-data-service.html), либо [ODBCDataService](fo_odbc-data-service.html). Затем, согласно особенностей хранилища, которое планируется использовать, необходимо соответствующим образом перегрузить методы. +Если требуется реализовать [сервис данных](fo_data-service.html) для реляционного хранилища, рекомендуется унаследоваться от [готовых сервисов данных Flexberry Platform](fo_standard-data-services.html), в частности, от общего предка реляционных сервисов данных [SQLDataService](fo_sql-data-service.html). Затем, согласно особенностей хранилища, которое планируется использовать, необходимо соответствующим образом перегрузить методы. Ниже приводится пример [сервиса данных](fo_data-service.html), выполняющего работу с Microsoft SQL Server напрямую, через SQLClient: @@ -41,7 +41,7 @@ public class MSSQLDataService:ICSSoft.STORMNET.Business.SQLDataService for (int i= identifiers.Length-2;i>=0;i--) result = string.Concat("ISNULL(",identifiers[i],", ",result,")"); return result; - } + } } ``` diff --git a/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.en.md b/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.en.md index d5ab01413..5304e2f22 100644 --- a/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.en.md +++ b/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.en.md @@ -91,7 +91,7 @@ try // Flexberry ORM saves the data objects according to their condition. Dependencies between objects are handled automatically. All queries executed in one transaction. // Thus, a single call UpdateObjects corresponds to a single transaction database. // Besides, there is a method UpdateObject to update a single object (and the object graph data to which it refers). - DataServiceProvider.DataService.UpdateObjects(ref objectsToUpdateArray); + DataServiceProvider.DataService.UpdateObjects(ref objectsToUpdateArray); // DataServiceProvider is deprecated; inject IDataService instead stopwatch.Stop(); Console.WriteLine("Time taken for persistence: {0} ms.", stopwatch.ElapsedMilliseconds); diff --git a/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.ru.md b/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.ru.md index 4e3ecb27f..0110fdad6 100644 --- a/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_instantiate-persist-objects.ru.md @@ -86,10 +86,10 @@ try stopwatch.Start(); // DataServiceProvider.DataService создает сервис данных, тип которого задан в конфигурационном файле (ключи DataServiceType, CustomizationStrings в секции appSettings). - // Flexberry ORM сохраняет объекты данных в соответствии с их состоянием. Зависимости между объектами обрабатываются автоматически. Все запросы выполняются в одной транзакции. + // Flexberry ORM сохраняет объекты данных в соответствии с их состоянием. Зависимости между объектами обрабатываются автоматически. Все запросы выполняются в одной транзакции. // Таким образом, один вызов UpdateObjects соответствует одной транзакции БД. // Кроме этого, существует метод UpdateObject для обновления одиночного объекта (и графа объектов данных, на которые он ссылается). - DataServiceProvider.DataService.UpdateObjects(ref objectsToUpdateArray); + DataServiceProvider.DataService.UpdateObjects(ref objectsToUpdateArray); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. stopwatch.Stop(); Console.WriteLine("Time taken for persistence: {0} ms.", stopwatch.ElapsedMilliseconds); diff --git a/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.en.md b/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.en.md index 08403f890..105227a27 100644 --- a/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.en.md +++ b/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.en.md @@ -67,7 +67,7 @@ lcs.LimitFunction = <Объект типа ICSSoft.STORMNET.FunctionalLanguage.F 6. To make a request to the server, using the method of [`LoadObjects` data service](fo_data-service.html) ``` csharp -var credits = DataServiceProvider.DataService.LoadObjects(lcs).Cast<Кредит>(); +var credits = DataServiceProvider.DataService.LoadObjects(lcs).Cast<Кредит>(); // DataServiceProvider is deprecated; inject IDataService instead ``` ## Example diff --git a/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.ru.md b/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.ru.md index 71f8635d8..65db681f2 100644 --- a/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_loading-customization-struct.ru.md @@ -65,7 +65,7 @@ lcs.LimitFunction = <Объект типа ICSSoft.STORMNET.FunctionalLanguage.F 6. Сделать запрос к серверу, используя метод [`LoadObjects` сервиса данных](fo_data-service.html) ``` csharp -var credits = DataServiceProvider.DataService.LoadObjects(lcs).Cast<Кредит>(); +var credits = DataServiceProvider.DataService.LoadObjects(lcs).Cast<Кредит>(); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` ## Пример diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.en.md b/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.en.md deleted file mode 100644 index b35b9e709..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.en.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: data Services to access the Access database engine -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services, Access -summary: Features use ODBCAccessDataService -toc: true -permalink: en/fo_odbc-access-ds.html -lang: en -autotranslated: true -hash: f0c411372d0810ae62df95de9cf20731c71f9cf7062da926c58b3e2b89180f89 ---- - -`ODBCAccessDataService ` is [service data](fo_data-service.html), represents the implementation of [ODBCDataService](fo_odbc-data-service.html), optimized for data access DBMS Access. - -When specifying ODBCAccessDataService as a service data string is used - -`ICSSoft.STORMNET.Business.ODBCAccessDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## features of use - -* The connection string used ODBCAccessDataService lines - -`Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\Temp\Flexberry.mdb;` - -(in this example, the connection will be made to the database "Flexberry.mdb" located on my way "D:\Temp\"). -* Due to the version of the driver, work with ODBCAccessDataService is only possible in applications that are compiled for x86. - - - diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.ru.md b/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.ru.md deleted file mode 100644 index 58216e06c..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-access-ds.ru.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Cервис данных для доступа к СУБД Access -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, сервис данных, Access -summary: Особенности использования ODBCAccessDataService -toc: true -permalink: ru/fo_odbc-access-ds.html -lang: ru ---- - -`ODBCAccessDataService `- это [сервис данных](fo_data-service.html), представляющий реализацию [ODBCDataService](fo_odbc-data-service.html), оптимизированный для доступа к данным СУБД Access. - -При указании ODBCAccessDataService в качестве сервиса данных используется строка - -`ICSSoft.STORMNET.Business.ODBCAccessDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## Особенности использования - -* В качестве строки подключения ODBCAccessDataService используются строки вида - -`Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\Temp\Flexberry.mdb;` - -(в данном примере подключение будет производиться к БД "Flexberry.mdb", расположенной по пути "D:\Temp\"). -* Из-за версии используемого драйвера, работа с ODBCAccessDataService возможно только в приложениях, скомпилированных под x86. diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-data-service.en.md b/pages/products/flexberry-orm/data-service/fo_odbc-data-service.en.md deleted file mode 100644 index e963f5381..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-data-service.en.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: ODBCDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services, odbc, -summary: Service for access to relational data sources -toc: true -permalink: en/fo_odbc-data-service.html -lang: en -autotranslated: true -hash: 29d5017ffd1fd0252f2dd575193856c0a45f74329382986f709cf5b5e5e9d8bf ---- - -`ODBCDataService` is [service data](fo_data-service.html) to access relational data sources, independent from the relational DBMS is an implementation of the [abstract class SQLDataService](fo_sql-data-service.html). - -When specifying ODBCDataService as a service data string is used `ICSSoft.STORMNET.Business.ODBCDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## Heirs ODBCDataService - -There are subclasses of ODBCDataService: - -* [ODBCAccessDataService](fo_odbc-access-ds.html) -* [ODBCMySqlDataService](fo_odbc-mysql-data-service.html) - - - diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-data-service.ru.md b/pages/products/flexberry-orm/data-service/fo_odbc-data-service.ru.md deleted file mode 100644 index ac02bcbab..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-data-service.ru.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ODBCDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, сервис данных, odbc -summary: Сервис для доступа к реляционным источникам данных -toc: true -permalink: ru/fo_odbc-data-service.html -lang: ru ---- - -`ODBCDataService` - это [сервис данных](fo_data-service.html) для доступа к реляционным источникам данных, независим от реляционной СУБД, является реализацией [абстрактного класса SQLDataService](fo_sql-data-service.html). - -При указании ODBCDataService в качестве сервиса данных используется строка `ICSSoft.STORMNET.Business.ODBCDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## Наследники ODBCDataService - -Существуют классы-наследники ODBCDataService: - -* [ODBCAccessDataService](fo_odbc-access-ds.html) -* [ODBCMySqlDataService](fo_odbc-mysql-data-service.html) diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.en.md b/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.en.md deleted file mode 100644 index 3f223c2f4..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.en.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: ODBCMySqlDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services, odbc, -summary: the data Service to access data in MySQL -toc: true -permalink: en/fo_odbc-mysql-data-service.html -lang: en -autotranslated: true -hash: 4507c588358096e5749fac7c6848a24aa54e2e191d204272696fe3160dc94c8f ---- - -`ODBCMySqlDataService` is [service data](fo_data-service.html), represents the implementation of [ODBCDataService](fo_odbc-data-service.html), optimized for data access, MySQL database. - -When specifying ODBCMySqlDataService as a service data string is used `ICSSoft.STORMNET.Business.ODBCMySqlDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## features of use - -* ODBCMySqlDataService implemented for MySQL versions 4.1 and later, with some restrictions on object structure. - - - diff --git a/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.ru.md b/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.ru.md deleted file mode 100644 index 363c6436d..000000000 --- a/pages/products/flexberry-orm/data-service/fo_odbc-mysql-data-service.ru.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: ODBCMySqlDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, сервис данных, odbc -summary: Cервис данных для доступа к данным СУБД MySQL -toc: true -permalink: ru/fo_odbc-mysql-data-service.html -lang: ru ---- - -`ODBCMySqlDataService` - это [сервис данных](fo_data-service.html), представляющий реализацию [ODBCDataService](fo_odbc-data-service.html), оптимизированный для доступа к данным СУБД MySQL. - -При указании ODBCMySqlDataService в качестве сервиса данных используется строка `ICSSoft.STORMNET.Business.ODBCMySqlDataService, ICSSoft.STORMNET.Business.ODBCDataService`. - -## Особенности использования - -* ODBCMySqlDataService реализован для СУБД MySQL версий 4.1 и более поздние, с некоторыми ограничениями на объектную структуру. diff --git a/pages/products/flexberry-orm/data-service/fo_processing-one-object.en.md b/pages/products/flexberry-orm/data-service/fo_processing-one-object.en.md index 8f392aee5..1c269280b 100644 --- a/pages/products/flexberry-orm/data-service/fo_processing-one-object.en.md +++ b/pages/products/flexberry-orm/data-service/fo_processing-one-object.en.md @@ -33,12 +33,12 @@ static void Main(string[) args) } private static void UpdateObject(DataObject dparam) { - IDataService ds = DataServiceProvider.DataService; + IDataService ds = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead ds.UpdateObject(ref dparam); } private static void LoadObject(DataObject dparam) { - IDataService ds = DataServiceProvider.DataService; + IDataService ds = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead ds.LoadObject(dparam); } ``` diff --git a/pages/products/flexberry-orm/data-service/fo_processing-one-object.ru.md b/pages/products/flexberry-orm/data-service/fo_processing-one-object.ru.md index 18f1d32ad..14739e56f 100644 --- a/pages/products/flexberry-orm/data-service/fo_processing-one-object.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_processing-one-object.ru.md @@ -21,22 +21,22 @@ static void Main(string[) args) Страна странакоторуюпишем = new Страна(); странакоторуюпишем.Наименование="Россия"; UpdateObject(странакоторуюпишем); - Console.WriteLine("Конец сохранения"); + Console.WriteLine("Конец сохранения"); //чтение одного объекта Страна странакоторуючитаем = new Страна(); странакоторуючитаем.SetExistObjectPrimaryKey(странакоторуюпишем.__PrimaryKey); LoadObject(странакоторуючитаем); - Console.WriteLine("Конец чтения, страна {0}", странакоторуючитаем.Наименование); + Console.WriteLine("Конец чтения, страна {0}", странакоторуючитаем.Наименование); Console.Read(); } private static void UpdateObject(DataObject dparam) { - IDataService ds = DataServiceProvider.DataService; + IDataService ds = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ds.UpdateObject(ref dparam); } private static void LoadObject(DataObject dparam) { - IDataService ds = DataServiceProvider.DataService; + IDataService ds = DataServiceProvider.DataService; ds.LoadObject(dparam); } ``` diff --git a/pages/products/flexberry-orm/data-service/fo_reading-portion.en.md b/pages/products/flexberry-orm/data-service/fo_reading-portion.en.md index d421d423e..33d582c25 100644 --- a/pages/products/flexberry-orm/data-service/fo_reading-portion.en.md +++ b/pages/products/flexberry-orm/data-service/fo_reading-portion.en.md @@ -19,7 +19,7 @@ To perform batch reading should: * Perform follow-up pochityvaya as. ``` csharp -IDataService ds = DataServiceProvider.DataService; +IDataService ds = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Автор), Автор.Views.Главное); lcs.LoadingBufferSize = 1; // The batch size. object state = null; // Return state of data service. diff --git a/pages/products/flexberry-orm/data-service/fo_reading-portion.ru.md b/pages/products/flexberry-orm/data-service/fo_reading-portion.ru.md index d6ef52db5..13faeac59 100644 --- a/pages/products/flexberry-orm/data-service/fo_reading-portion.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_reading-portion.ru.md @@ -8,7 +8,7 @@ permalink: ru/fo_reading-portion.html lang: ru --- -Весьма удобной возможностью является чтение объектов данных порциями, по частям. Существует возможность вызвать операцию чтения таким образом, чтобы кроме порции объектов данных, [сервис данных](fo_data-service.html) возвратил некоторое состояние чтения. Передавая последующим операциям чтения это состояние, можно получать очередные порции. +Весьма удобной возможностью является чтение объектов данных порциями, по частям. Существует возможность вызвать операцию чтения таким образом, чтобы кроме порции объектов данных, [сервис данных](fo_data-service.html) возвратил некоторое состояние чтения. Передавая последующим операциям чтения это состояние, можно получать очередные порции. Для выполнения порционного чтения необходимо: @@ -17,8 +17,8 @@ lang: ru * Выполнять последующее дочитывание по состоянию. ``` csharp -IDataService ds = DataServiceProvider.DataService; -LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Автор), Автор.Views.Главное); +IDataService ds = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. +LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Автор), Автор.Views.Главное); lcs.LoadingBufferSize = 1; // Размер порции. object state = null; // Сюда вернётся состояние сервиса данных. DataObject[) dataobjects = ds.LoadObjects(lcs, ref state); // Вызываем сервис данных, состояние запоминается. @@ -29,7 +29,7 @@ while (dataobjects.Length > 0) // Пока ещё что-то возвращ Console.ReadLine(); dataobjects = ds.LoadObjects(ref state); // Прочитываем очередную порцию. Lcs уже не передаём. prvPrintPortion(dataobjects); // Печатаем очередную порцию. -} +} Console.WriteLine("Больше авторов нет. Конец."); Console.Read(); diff --git a/pages/products/flexberry-orm/data-service/fo_sql-data-service.en.md b/pages/products/flexberry-orm/data-service/fo_sql-data-service.en.md index 6ae2aa90c..21b56f7d3 100644 --- a/pages/products/flexberry-orm/data-service/fo_sql-data-service.en.md +++ b/pages/products/flexberry-orm/data-service/fo_sql-data-service.en.md @@ -1,242 +1,241 @@ ---- -title: SQLDataService -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services -summary: Opportunities, methods, demands, activities, and events -toc: true -permalink: en/fo_sql-data-service.html -lang: en -autotranslated: true -hash: 8bbea0f68de7b0ad390d3c7beba961b4f2944a0cc01b81640707977539ce235e ---- +--- +title: SQLDataService +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, data services +summary: Opportunities, methods, demands, activities, and events +toc: true +permalink: en/fo_sql-data-service.html +lang: en +autotranslated: true +hash: 8bbea0f68de7b0ad390d3c7beba961b4f2944a0cc01b81640707977539ce235e +--- -[Service data](fo_data-service.html) working with relational storage. +[Service data](fo_data-service.html) working with relational storage. -Is an abstract class, inherited from it +Is an abstract class, inherited from it -* [`MSSQLDataService`](fo_mssql-data-service.html), -* [`ODBCDataService`](fo_odbc-data-service.html), -* [`OracleDataService`](fo_oracle-data-service.html), -* [`PostgresDataService`](fo_postgres-data-service.html). +* [`MSSQLDataService`](fo_mssql-data-service.html), +* [`OracleDataService`](fo_oracle-data-service.html), +* [`PostgresDataService`](fo_postgres-data-service.html). -## Main features SQLDataService +## Main features SQLDataService -Because `SQLDataService` implements the interface `ICSSoft.STORMNET.Business.IDataService`, it supports all the methods defined in this interface](fo_data-service.html). -It should be noted that some of the methods only declared in the class `SQLDataService`, and their implementation must be implemented in descendant classes. +Because `SQLDataService` implements the interface `ICSSoft.STORMNET.Business.IDataService`, it supports all the methods defined in this interface](fo_data-service.html). +It should be noted that some of the methods only declared in the class `SQLDataService`, and their implementation must be implemented in descendant classes. -### Additional ways to load data +### Additional ways to load data -#### LoadRawValues +#### LoadRawValues -__Assign__: Download without create objects when you need to get DISTINCT data. -Standard methods zachetki get [PrimaryKey] in(fo_primary-keys-objects.html) to allow the correct creation of data objects. Accordingly, DISTINCT [PrimaryKey] in(fo_primary-keys-objects.html) in the query has no effect (keys are unique, so no grouping the results will not happen - they are all different). This method returns a regular two-dimensional array (as it does `ADO.NET`). +__Assign__: Download without create objects when you need to get DISTINCT data. +Standard methods zachetki get [PrimaryKey] in(fo_primary-keys-objects.html) to allow the correct creation of data objects. Accordingly, DISTINCT [PrimaryKey] in(fo_primary-keys-objects.html) in the query has no effect (keys are unique, so no grouping the results will not happen - they are all different). This method returns a regular two-dimensional array (as it does `ADO.NET`). -__Settings__: +__Settings__: -`customizationStruct` - Structure [LoadingCustomizationStruct](fo_loading-customization-struct.html) defining what and how to ship. Must be specified `Distinct`. +`customizationStruct` - Structure [LoadingCustomizationStruct](fo_loading-customization-struct.html) defining what and how to ship. Must be specified `Distinct`. -__Signature__: +__Signature__: ```csharp - virtual public object[][] LoadRawValues(LoadingCustomizationStruct customizationStruct) -``` + virtual public object[][] LoadRawValues(LoadingCustomizationStruct customizationStruct) +``` -__Example__: +__Example__: ```csharp -SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; +SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead View v = new View(); v.DefineClassType = typeof (Door); v.AddProperty("Street.Name"); LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Door), v); -lcs.Distinct = false; //Get a two-dimensional array of properties without DISTINCT in the upper SELECT-e +lcs.Distinct = false; //Get a two-dimensional array of properties without DISTINCT in the upper SELECT-e object[][] loadDistinctValues = ds.LoadRawValues(lcs); string s = loadDistinctValues.Length.ToString(); -lcs.Distinct = true; //Get a two-dimensional array with DISTINCT properties at the top SELECT-e +lcs.Distinct = true; //Get a two-dimensional array with DISTINCT properties at the top SELECT-e object[][] loadDistinctValues1 = ds.LoadRawValues(lcs); string s1 = loadDistinctValues1.Length.ToString(); -``` +``` -#### SecondLoadObject +#### SecondLoadObject -__Assign__: Method for decide data object. -Previously loaded properties are not overwritten, the modified properties are not overwritten. Replaced the piece the properties of the clone data. It is recommended to read the description in the article [Dochitcu data object](fo_additional-loading.html). +__Assign__: Method for decide data object. +Previously loaded properties are not overwritten, the modified properties are not overwritten. Replaced the piece the properties of the clone data. It is recommended to read the description in the article [Dochitcu data object](fo_additional-loading.html). -__Settings__: +__Settings__: -* `dataObjectView` - view -* `dataObject` - bject data that you want to download -* `checkExistingObject` is to check whether the object exists in the repository -* `dataObjectCache` - cache +* `dataObjectView` - view +* `dataObject` - bject data that you want to download +* `checkExistingObject` is to check whether the object exists in the repository +* `dataObjectCache` - cache -__Signature__: +__Signature__: ```csharp -protected virtual void SecondLoadObject(View dataObjectView, DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache) -``` +protected virtual void SecondLoadObject(View dataObjectView, DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache) +``` -## Additional ways to update data +## Additional ways to update data -### UpdateObjectsOrdered +### UpdateObjectsOrdered -__Assign__: to Update the data objects in the specified order. +__Assign__: to Update the data objects in the specified order. -`SQLDataService` knows himself to build the order query to update the data objects. This is especially true when there are a large number of diverse objects in a single transaction. Unfortunately, it is not always possible to automatically compute the correct order of requests. First and foremost, this applies to situations when the graph types, there are cycles. To solve this problem, we propose to use the method that performs updating of objects sequentially in the order in which they come in this method. +`SQLDataService` knows himself to build the order query to update the data objects. This is especially true when there are a large number of diverse objects in a single transaction. Unfortunately, it is not always possible to automatically compute the correct order of requests. First and foremost, this applies to situations when the graph types, there are cycles. To solve this problem, we propose to use the method that performs updating of objects sequentially in the order in which they come in this method. -__Settings__: +__Settings__: -* `objects` - refreshable -* `alwaysThrowException` - If an error occurred in the database, don't try to fulfill other requests, just cocked an error and roll back the transaction. +* `objects` - refreshable +* `alwaysThrowException` - If an error occurred in the database, don't try to fulfill other requests, just cocked an error and roll back the transaction. -__Signature__: +__Signature__: ```csharp virtual public void UpdateObjectsOrdered(ref DataObject[] objects, bool alwaysThrowException = true) -``` +``` -__Example__: +__Example__: ```csharp protected void UpdateButtonClick(object sender, EventArgs e) { - SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; + SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead var ko = ds.Query<КритерийОценки>(КритерийОценки.Views.КритерийОценкиE).First(o => o.Описание.StartsWith("kirlim")); ko.Описание = "kirlim-birlim"; DataObject[] dObjs = new DataObject[] { ko }; ds.UpdateObjectsOrdered(ref dObjs); } -``` +``` -### operations within the specified connection and transaction +### operations within the specified connection and transaction -#### LoadObjectByExtConn +#### LoadObjectByExtConn -__Assign__: Loading the object with the specified connectie within the specified transaction +__Assign__: Loading the object with the specified connectie within the specified transaction -__Settings__: +__Settings__: -* `dataObjectView` - Representation that will be counted towards the object. -* `dobject` - the Object that will be zachityvalis/counted. -* `сlearDataObject` - whether zachitka to clear the fields of an existing data object. -* `сheckExistingObject` - to Verify the existence encountered sacide objects. -* `dataObjectCache` - the object Cache. -* `connection` - Connecte through which will occur zachitka. -* `transaction` Transaction, which will be held zachitka. +* `dataObjectView` - Representation that will be counted towards the object. +* `dobject` - the Object that will be zachityvalis/counted. +* `сlearDataObject` - whether zachitka to clear the fields of an existing data object. +* `сheckExistingObject` - to Verify the existence encountered sacide objects. +* `dataObjectCache` - the object Cache. +* `connection` - Connecte through which will occur zachitka. +* `transaction` Transaction, which will be held zachitka. -__Signature__: +__Signature__: ```csharp public virtual void LoadObjectByExtConn( View dataObjectView, - DataObject dobject, - bool сlearDataObject, - bool сheckExistingObject, - DataObjectCache dataObjectCache, - IDbConnection connection, - IDbTransaction transaction) -``` + DataObject dobject, + bool сlearDataObject, + bool сheckExistingObject, + DataObjectCache dataObjectCache, + IDbConnection connection, + IDbTransaction transaction) +``` -#### LoadObjectsByExtConn +#### LoadObjectsByExtConn -__Assign__: Loading objects using the specified connection and transaction +__Assign__: Loading objects using the specified connection and transaction -__Settings__: +__Settings__: -* `customizationStruct` - Structure that defines what and how to ship. -* `state` - a State of proof-reading(for the subsequent decide if you use [batch reading](fo_reading-portion.html), the serving size specified in `customizationStruct.LoadingBufferSize`) -* `dataObjectCache` - object Cache for zazitky. -* `connection` - Connecte through which will be fulfilled zachitka. -* `transaction` Transaction, which will be performed zachitka. +* `customizationStruct` - Structure that defines what and how to ship. +* `state` - a State of proof-reading(for the subsequent decide if you use [batch reading](fo_reading-portion.html), the serving size specified in `customizationStruct.LoadingBufferSize`) +* `dataObjectCache` - object Cache for zazitky. +* `connection` - Connecte through which will be fulfilled zachitka. +* `transaction` Transaction, which will be performed zachitka. -__Signature__: +__Signature__: ```csharp public virtual DataObject[] LoadObjectsByExtConn( LoadingCustomizationStruct customizationStruct, - ref object state, + ref object state, DataObjectCache dataObjectCache, IDbConnection connection, IDbTransaction transaction) -``` +``` -#### ReadFirstByExtConn +#### ReadFirstByExtConn -__Appointment___: Receive the first portion when [batch reading](fo_reading-portion.html) using the specified connection and transaction. In addition to portions of data objects, the data service returns a status read `state`. This condition is transmitted to the data service to retrieve the next portion (see next method). +__Appointment___: Receive the first portion when [batch reading](fo_reading-portion.html) using the specified connection and transaction. In addition to portions of data objects, the data service returns a status read `state`. This condition is transmitted to the data service to retrieve the next portion (see next method). Analogue to the previous method, but instead of adjusting the structure of the sample is determined by the text of the query. -__Settings__: +__Settings__: -* `Query` - Text query to fetch data -* `state` - a State of proof-reading(for the subsequent decide) -* `LoadingBufferSize` - size portions -* `Connection` - Connecte through which will be fulfilled zachitka -* `Transaction` Transaction, which will be performed zachitka +* `Query` - Text query to fetch data +* `state` - a State of proof-reading(for the subsequent decide) +* `LoadingBufferSize` - size portions +* `Connection` - Connecte through which will be fulfilled zachitka +* `Transaction` Transaction, which will be performed zachitka -__Signature__: +__Signature__: ```csharp public virtual object[][] ReadFirstByExtConn(string Query, ref object State, int LoadingBufferSize, System.Data.IDbConnection Connection, System.Data.IDbTransaction Transaction) -``` +``` -#### ReadNextByExtConn +#### ReadNextByExtConn -__Appointment___: Receiving another batch [batch reading](fo_reading-portion.html). Must be preceded by a call to one of the above two methods of obtaining status `state`. +__Appointment___: Receiving another batch [batch reading](fo_reading-portion.html). Must be preceded by a call to one of the above two methods of obtaining status `state`. -__Settings__: +__Settings__: -* `state` - a State of proof-reading(for the subsequent decide) -* `LoadingBufferSize` - size portions +* `state` - a State of proof-reading(for the subsequent decide) +* `LoadingBufferSize` - size portions -__Signature__: +__Signature__: ```csharp public virtual object[][] ReadNextByExtConn(ref object State, int LoadingBufferSize) -``` +``` -#### UpdateObjectsByExtConn +#### UpdateObjectsByExtConn -__Assign__: to Update the store objects using the specified connection and transaction. +__Assign__: to Update the store objects using the specified connection and transaction. -{% include note.html content="If the option `alwaysThrowException`=`true`, always cocked an error. Otherwise, execution continues. However, while there is a risk of premature end of the transaction, with the transition to the other mode queries in autocommit transaction. A manifestation of the problem are errors like: The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION." %} +{% include note.html content="If the option `alwaysThrowException`=`true`, always cocked an error. Otherwise, execution continues. However, while there is a risk of premature end of the transaction, with the transition to the other mode queries in autocommit transaction. A manifestation of the problem are errors like: The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION." %} -__Settings__: +__Settings__: -* `objects` Objects to update. -* `dataObjectCache` - the object Cache. -* `alwaysThrowException` - If an error occurred in the database, don't try to fulfill other requests, just cocked an error and roll back the transaction. -* `connection` - Konekcija (remember to close). -* `transaction` Transaction (don't forget to complete). +* `objects` Objects to update. +* `dataObjectCache` - the object Cache. +* `alwaysThrowException` - If an error occurred in the database, don't try to fulfill other requests, just cocked an error and roll back the transaction. +* `connection` - Konekcija (remember to close). +* `transaction` Transaction (don't forget to complete). -__Signature__: +__Signature__: ```csharp public virtual void UpdateObjectsByExtConn(ref DataObject[] objects, DataObjectCache dataObjectCache, bool alwaysThrowException, IDbConnection connection, IDbTransaction transaction) -``` +``` -## Generation of the texts of SQL queries +## Generation of the texts of SQL queries -### GenerateQueriesForUpdateObjects +### GenerateQueriesForUpdateObjects -__Assign__: Generating requests to modify objects +__Assign__: Generating requests to modify objects -__Settings__: +__Settings__: -* `deleteQueries` Queries for delete (output parameter) -* `deleteTables` - Table that will be conducted the deletion of data (output parameter) -* `updateQueries` - Generated requests for change (output parameter). -* `updateTables` - Tables, which will be held modifying the database (output parameter). -* `insertQueries` - Generated requests to add (output parameter). -* `insertTables` - Table that will be inserting data (output parameter). -* `tableOperations` Operation that will be performed on the tables (output parameter). -* `queryOrder` - the Order of execution of the generated queries specified by a table name (output parameter). -* `checkLoadedProps` is to Check whether the workload properties. -* `processingObjects` - Current processed objects (i.e., objects that the service plans to confirm data in the database in the current transaction). An output parameter. +* `deleteQueries` Queries for delete (output parameter) +* `deleteTables` - Table that will be conducted the deletion of data (output parameter) +* `updateQueries` - Generated requests for change (output parameter). +* `updateTables` - Tables, which will be held modifying the database (output parameter). +* `insertQueries` - Generated requests to add (output parameter). +* `insertTables` - Table that will be inserting data (output parameter). +* `tableOperations` Operation that will be performed on the tables (output parameter). +* `queryOrder` - the Order of execution of the generated queries specified by a table name (output parameter). +* `checkLoadedProps` is to Check whether the workload properties. +* `processingObjects` - Current processed objects (i.e., objects that the service plans to confirm data in the database in the current transaction). An output parameter. * `dataObjectCache` - Cache data objects. -* `auditObjects` is a List of objects that you want to record in the audit (the output parameter). Is filled in case when passed is not null and current audit service is enabled. -* `dobjects` - the objects for which the generated queries. +* `auditObjects` is a List of objects that you want to record in the audit (the output parameter). Is filled in case when passed is not null and current audit service is enabled. +* `dobjects` - the objects for which the generated queries. -__Signature__: +__Signature__: ```csharp public virtual void GenerateQueriesForUpdateObjects( @@ -252,9 +251,9 @@ public virtual void GenerateQueriesForUpdateObjects( System.Collections.ArrayList processingObjects, DataObjectCache dataObjectCache, params ICSSoft.STORMNET.DataObject[] dobjects) -``` +``` -In this overload returns a list of additional objects that require the creation of audit records: +In this overload returns a list of additional objects that require the creation of audit records: ```csharp public virtual void GenerateQueriesForUpdateObjects( @@ -267,78 +266,78 @@ public virtual void GenerateQueriesForUpdateObjects( SortedList tableOperations, StringCollection queryOrder, bool checkLoadedProps, - ArrayList processingObjects, + ArrayList processingObjects, DataObjectCache dataObjectCache, List auditObjects, params ICSSoft.STORMNET.DataObject[] dobjects) -``` +``` -### GenerateSQLSelect +### GenerateSQLSelect -__Assign__: Receive a request to read data +__Assign__: Receive a request to read data -__Settings__: +__Settings__: -* `customizationStruct` - customize sample -* `StorageStruct` - returns the corresponding structure of the sample +* `customizationStruct` - customize sample +* `StorageStruct` - returns the corresponding structure of the sample -__The result is___: request +__The result is___: request -__Signature__: +__Signature__: ```csharp -// 1. +// 1. public virtual string GenerateSQLSelect(LoadingCustomizationStruct customizationStruct, bool ForReadValues, out STORMDO.Business.StorageStructForView[] StorageStruct, bool Optimized) -// 2. +// 2. public virtual string GenerateSQLSelect(LoadingCustomizationStruct customizationStruct, bool Optimized) -``` +``` -### GetLeftJoinExpression +### GetLeftJoinExpression -__Assign__: to LeftJoin expression +__Assign__: to LeftJoin expression -__Settings__: +__Settings__: -* `subTable` the name of the table -* `subTableAlias` - the table alias -* `parentAliasWithKey` -* `subTableKey` -* `subJoins` -* `baseOutline` +* `subTable` the name of the table +* `subTableAlias` - the table alias +* `parentAliasWithKey` +* `subTableKey` +* `subJoins` +* `baseOutline` -__Signature__: +__Signature__: ```csharp public virtual void GetLeftJoinExpression(string subTable, string subTableAlias, string parentAliasWithKey, string subTableKey, string subJoins, string baseOutline, out string FromPart, out string WherePart) -``` +``` -### GetInnerJoinExpression +### GetInnerJoinExpression -__Assign__: to InnerJoin expression +__Assign__: to InnerJoin expression -__Settings__: +__Settings__: -* `subTable` the name of the table -* `subTableAlias` - the table alias -* `parentAliasWithKey` -* `subTableKey` -* `subJoins` -* `baseOutline` -* `FromPart` -* `WherePart` +* `subTable` the name of the table +* `subTableAlias` - the table alias +* `parentAliasWithKey` +* `subTableKey` +* `subJoins` +* `baseOutline` +* `FromPart` +* `WherePart` -__Signature__: +__Signature__: ```csharp public virtual void GetInnerJoinExpression(string subTable, string subTableAlias, string parentAliasWithKey, string subTableKey, string subJoins, string baseOutline, out string FromPart, out string WherePart) -``` +``` -### GetJoinTableModifierExpression +### GetJoinTableModifierExpression -__Assign__: Return a modifier to access a table (e.g. WITH (NOLOCK)) +__Assign__: Return a modifier to access a table (e.g. WITH (NOLOCK)) -You can overload this method in the data service-the successor to return its corresponding modifier. +You can overload this method in the data service-the successor to return its corresponding modifier. Basic `SQLDataService` returns an empty string. diff --git a/pages/products/flexberry-orm/data-service/fo_sql-data-service.ru.md b/pages/products/flexberry-orm/data-service/fo_sql-data-service.ru.md index 84f58359d..2fe2d6561 100644 --- a/pages/products/flexberry-orm/data-service/fo_sql-data-service.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_sql-data-service.ru.md @@ -10,10 +10,9 @@ lang: ru [Сервис данных](fo_data-service.html), работающий с реляционными хранилищами. -Является абстрактным классом, от него наследуется +Является абстрактным классом, от него наследуется * [`MSSQLDataService`](fo_mssql-data-service.html), -* [`ODBCDataService`](fo_odbc-data-service.html), * [`OracleDataService`](fo_oracle-data-service.html), * [`PostgresDataService`](fo_postgres-data-service.html). @@ -31,18 +30,18 @@ __Назначение__: Загрузка без создания объект __Параметры__: -`customizationStruct` - Структура [LoadingCustomizationStruct](fo_loading-customization-struct.html), определяющая, что и как грузить. Должен быть указан параметр `Distinct`. +`customizationStruct` - Структура [LoadingCustomizationStruct](fo_loading-customization-struct.html), определяющая, что и как грузить. Должен быть указан параметр `Distinct`. __Сигнатура__: ```csharp - virtual public object[][] LoadRawValues(LoadingCustomizationStruct customizationStruct) -``` + virtual public object[][] LoadRawValues(LoadingCustomizationStruct customizationStruct) +``` __Пример__: ```csharp -SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; +SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. View v = new View(); v.DefineClassType = typeof (Door); v.AddProperty("Street.Name"); @@ -71,40 +70,40 @@ __Параметры__: __Сигнатура__: ```csharp -protected virtual void SecondLoadObject(View dataObjectView, DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache) +protected virtual void SecondLoadObject(View dataObjectView, DataObject dataObject, bool checkExistingObject, DataObjectCache dataObjectCache) ``` ## Дополнительные способы обновления данных ### UpdateObjectsOrdered -__Назначение__: Обновить объекты данных в указанном порядке. +__Назначение__: Обновить объекты данных в указанном порядке. `SQLDataService` умеет сам выстраивать порядок запросов на обновление объектов данных. Особенно это актуально, когда есть большое количество разнотипных объектов в одной транзакции. К сожалению, не всегда есть возможность автоматизированно вычислить правильный порядок запросов. В первую очередь, это относится к ситуациям, когда в графе типов есть циклы. Для решения этой проблемы предлагается использовать данный метод, который выполняет обновление объектов последовательно в том порядке, в котором они приходят в этот метод. __Параметры__: -* `objects` - обновляемые объекты +* `objects` - обновляемые объекты * `alwaysThrowException` - Если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию. __Сигнатура__: ```csharp virtual public void UpdateObjectsOrdered(ref DataObject[] objects, bool alwaysThrowException = true) -``` +``` __Пример__: ```csharp protected void UpdateButtonClick(object sender, EventArgs e) { - SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; + SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var ko = ds.Query<КритерийОценки>(КритерийОценки.Views.КритерийОценкиE).First(o => o.Описание.StartsWith("kirlim")); ko.Описание = "kirlim-birlim"; DataObject[] dObjs = new DataObject[] { ko }; ds.UpdateObjectsOrdered(ref dObjs); } -``` +``` ### Выполнение операций в рамках указанных коннекции и транзакции @@ -127,13 +126,13 @@ __Сигнатура__: ```csharp public virtual void LoadObjectByExtConn( View dataObjectView, - DataObject dobject, - bool сlearDataObject, - bool сheckExistingObject, - DataObjectCache dataObjectCache, - IDbConnection connection, - IDbTransaction transaction) -``` + DataObject dobject, + bool сlearDataObject, + bool сheckExistingObject, + DataObjectCache dataObjectCache, + IDbConnection connection, + IDbTransaction transaction) +``` #### LoadObjectsByExtConn @@ -152,7 +151,7 @@ __Сигнатура__: ```csharp public virtual DataObject[] LoadObjectsByExtConn( LoadingCustomizationStruct customizationStruct, - ref object state, + ref object state, DataObjectCache dataObjectCache, IDbConnection connection, IDbTransaction transaction) @@ -161,11 +160,11 @@ public virtual DataObject[] LoadObjectsByExtConn( #### ReadFirstByExtConn __Назначение__: Получение первой порции при [порционном чтении](fo_reading-portion.html) с использованием указанной коннекции и транзакции. Кроме порции объектов данных, сервис данных возвращает состояние чтения `state`. Это состояние передается сервису данных для получения очередных порций (см. следующий метод). -Аналог предыдущего метода, но вместо настроечной структуры выборка определяется текстом запроса. +Аналог предыдущего метода, но вместо настроечной структуры выборка определяется текстом запроса. __Параметры__: -* `Query` - Текст запроса для выборки данных +* `Query` - Текст запроса для выборки данных * `state` - Состояние вычитки(для последующей дочитки) * `LoadingBufferSize` - размер порции * `Connection` - Коннекция, через которую будут выполнена зачитка @@ -179,7 +178,7 @@ public virtual object[][] ReadFirstByExtConn(string Query, ref object State, int #### ReadNextByExtConn -__Назначение__: Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов одного из двух вышеуказанных методов с получением состояния `state`. +__Назначение__: Получение очередных порций при [порционном чтении](fo_reading-portion.html). Должен предшествовать вызов одного из двух вышеуказанных методов с получением состояния `state`. __Параметры__: @@ -194,7 +193,7 @@ public virtual object[][] ReadNextByExtConn(ref object State, int LoadingBufferS #### UpdateObjectsByExtConn -__Назначение__: Обновить хранилище по объектам с использованием указанной коннекции и транзакции. +__Назначение__: Обновить хранилище по объектам с использованием указанной коннекции и транзакции. {% include note.html content="Если параметр `alwaysThrowException`=`true`, всегда взводится ошибка. Иначе, выполнение продолжается. Однако, при этом есть опасность преждевременного окончания транзакции, с переходом для остальных запросов режима транзакционности в autocommit. Проявлением проблемы являются ошибки вроде: The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION." %} @@ -216,7 +215,7 @@ public virtual void UpdateObjectsByExtConn(ref DataObject[] objects, DataObjectC ### GenerateQueriesForUpdateObjects -__Назначение__: Генерация запросов для изменения объектов +__Назначение__: Генерация запросов для изменения объектов __Параметры__: @@ -250,8 +249,8 @@ public virtual void GenerateQueriesForUpdateObjects( System.Collections.ArrayList processingObjects, DataObjectCache dataObjectCache, params ICSSoft.STORMNET.DataObject[] dobjects) -``` - +``` + В данной перегрузке дополнительно возвращается список объектов, для которых необходимо создание записей аудита: ```csharp @@ -265,16 +264,16 @@ public virtual void GenerateQueriesForUpdateObjects( SortedList tableOperations, StringCollection queryOrder, bool checkLoadedProps, - ArrayList processingObjects, + ArrayList processingObjects, DataObjectCache dataObjectCache, List auditObjects, params ICSSoft.STORMNET.DataObject[] dobjects) -``` +``` ### GenerateSQLSelect __Назначение__: Получить запрос на вычитку данных - + __Параметры__: * `customizationStruct` - настройка выборки @@ -295,16 +294,16 @@ public virtual string GenerateSQLSelect(LoadingCustomizationStruct customization ### GetLeftJoinExpression __Назначение__: Получить LeftJoin выражение - + __Параметры__: * `subTable` - имя таблицы * `subTableAlias` - псевдоним таблицы -* `parentAliasWithKey` -* `subTableKey` -* `subJoins` -* `baseOutline` - +* `parentAliasWithKey` +* `subTableKey` +* `subJoins` +* `baseOutline` + __Сигнатура__: ```csharp @@ -313,31 +312,31 @@ public virtual void GetLeftJoinExpression(string subTable, string subTableAlias, ### GetInnerJoinExpression -__Назначение__: Получить InnerJoin выражение +__Назначение__: Получить InnerJoin выражение __Параметры__: -* `subTable` - имя таблицы -* `subTableAlias` - псевдоним таблицы -* `parentAliasWithKey` -* `subTableKey` -* `subJoins` -* `baseOutline` -* `FromPart` -* `WherePart` +* `subTable` - имя таблицы +* `subTableAlias` - псевдоним таблицы +* `parentAliasWithKey` +* `subTableKey` +* `subJoins` +* `baseOutline` +* `FromPart` +* `WherePart` __Сигнатура__: ```csharp public virtual void GetInnerJoinExpression(string subTable, string subTableAlias, string parentAliasWithKey, string subTableKey, string subJoins, string baseOutline, out string FromPart, out string WherePart) -``` +``` ### GetJoinTableModifierExpression __Назначение__: Вернуть модификатор для обращения к таблице (напр WITH (NOLOCK)) Можно перегрузить этот метод в сервисе данных-наследнике для возврата соответствующего своего модификатора. -Базовый `SQLDataService` возвращает пустую строку. +Базовый `SQLDataService` возвращает пустую строку. __Сигнатура__: @@ -347,12 +346,12 @@ public virtual string GetJoinTableModifierExpression() ### GetINExpression -__Назначение__: Вернуть in выражение для where +__Назначение__: Вернуть in выражение для where __Параметры__: `identifiers` - идентификаторы - + __Сигнатура__: ```csharp @@ -362,7 +361,7 @@ public virtual string GetINExpression(params string[] identifiers) ### GetIfNullExpression __Назначение__: Вернуть ifnull выражение - + __Параметры__: `identifiers` - идентификаторы @@ -375,14 +374,14 @@ public virtual string GetIfNullExpression(params string[] identifiers) ### PutIdentifierIntoBrackets -__Назначение__: Оформить идентификатор +__Назначение__: Оформить идентификатор __Параметры__: `identifier` - идентификатор __Возвращаемый результат__: оформленный идентификатор(например в кавычках) - + __Сигнатура__: ```csharp @@ -392,7 +391,7 @@ public virtual string PutIdentifierIntoBrackets(string identifier) ### CreateJoins __Назначение__: Создать join соединения - + __Параметры__: * `source` - источник с которого формируется соединение @@ -414,7 +413,7 @@ public virtual void CreateJoins(STORMDO.Business.StorageStructForView.PropSource ### `CreateJoins` -__Назначение__: Создать join соединения +__Назначение__: Создать join соединения __Параметры__: @@ -424,7 +423,7 @@ __Параметры__: * `keysandtypes` - ключи и типы * `baseOutline` - смещение в запросе * `joinscount` - количество соединений - + __Сигнатура__: ```csharp @@ -445,16 +444,16 @@ SELECT Key1,Key2,... key3 FROM fromjoins -``` +``` __Параметры__: -* `storageStruct` - структура хранилища -* `AddingAdvansedField` - довленные дополнительные свойства +* `storageStruct` - структура хранилища +* `AddingAdvansedField` - довленные дополнительные свойства * `AddingKeysCount` - добавленниые ключи -* `addMasterFieldsCustomizer` -* `addNotMainKeys` -* `SelectTypesIds` +* `addMasterFieldsCustomizer` +* `addNotMainKeys` +* `SelectTypesIds` __Сигнатура__: @@ -464,11 +463,11 @@ virtual public string GenerateSQLSelectByStorageStruct(STORMDO.Business.StorageS // 2. virtual public string GenerateSQLSelectByStorageStruct(STORMDO.Business.StorageStructForView storageStruct, bool addNotMainKeys, bool addMasterFieldsCustomizer, string AddingAdvansedField, int AddingKeysCount, bool SelectTypesIds, bool MustNewGenerate, bool MustDopSelect) -``` +``` ### ConvertSimpleValueToQueryValueString -__Назначение__: Конвертация константных значений в строки запроса +__Назначение__: Конвертация константных значений в строки запроса __Параметры__: @@ -482,7 +481,7 @@ public virtual string ConvertSimpleValueToQueryValueString(object value) ### ConvertValueToQueryValueString -__Назначение__: Конвертация значений в строки запроса +__Назначение__: Конвертация значений в строки запроса __Параметры__: @@ -496,13 +495,13 @@ public virtual string ConvertValueToQueryValueString(object value) ### ConvertValueToQueryValueString -__Назначение__: Преобразование значение свойства в строку для запроса +__Назначение__: Преобразование значение свойства в строку для запроса __Параметры__: -* `dataobject` - объект данных +* `dataobject` - объект данных * `propname` - имя свойства - + __Сигнатура__: ```csharp @@ -511,7 +510,7 @@ public virtual string ConvertValueToQueryValueString(DataObject dataobject, stri ### LimitFunction2SQLWhere -__Назначение__: Преобразование функции +__Назначение__: Преобразование функции __Параметры__:`LimitFunction` - настроечная структура выборки @@ -523,7 +522,7 @@ public virtual string LimitFunction2SQLWhere(STORMFunction LimitFunction, STORMD ### LimitFunction2SQLWhere -__Назначение__: Преобразование функции +__Назначение__: Преобразование функции __Параметры__: @@ -543,10 +542,10 @@ __Назначение__: Вычитка первой партии данных __Параметры__: -* `Query` - Текст запроса для выборки данных +* `Query` - Текст запроса для выборки данных * `state` - Состояние вычитки(для последующей дочитки) * `LoadingBufferSize` - размер порции - + __Сигнатура__: ```csharp @@ -561,23 +560,23 @@ __Параметры__: * `state` - Состояние вычитки(для последующей дочитки) * `LoadingBufferSize` - размер порции - + __Сигнатура__: ```csharp public virtual object[][] ReadNext(ref object State, int LoadingBufferSize) ``` -### ExecuteNonQuery +### ExecuteNonQuery __Назначение__: Выполнить запрос __Параметры__: -`Query` - текст SQL-запроса +`Query` - текст SQL-запроса + +__Возвращаемый результат__: количество задетых строк -__Возвращаемый результат__: количество задетых строк - __Сигнатура__: ```csharp @@ -624,7 +623,7 @@ public delegate void AfterUpdateObjectsEventHandler(object sender, DataObjectsEv либо присвоить значение явно: ```csharp -SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; +SQLDataService ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ds.UseCommandTimeout = true; ds.CommandTimeout = 60; ``` diff --git a/pages/products/flexberry-orm/data-service/fo_sql-query.en.md b/pages/products/flexberry-orm/data-service/fo_sql-query.en.md index c80bd2497..7ae2eb362 100644 --- a/pages/products/flexberry-orm/data-service/fo_sql-query.en.md +++ b/pages/products/flexberry-orm/data-service/fo_sql-query.en.md @@ -46,7 +46,7 @@ public virtual decimal СуммаОплаченныхПокупок { get { - var connection = (SqlConnection)((SQLDataService)DataServiceProvider.DataService).GetConnection(); //get connection + var connection = (SqlConnection)((SQLDataService)DataServiceProvider.DataService).GetConnection(); // DataServiceProvider is deprecated; inject IDataService instead var command = new SqlCommand("SELECT SUM(purchase.\"Amount\") "+ "FROM \"Customer\" customer join \"Purchase\" purchase on customer.\"primaryKey\" = purchase.\"Buyer\" "+ "WHERE purchase.\"Buyer\"=@Customer AND purchase.\"Status\" = \'Paid\' ", connection); //make a request diff --git a/pages/products/flexberry-orm/data-service/fo_sql-query.ru.md b/pages/products/flexberry-orm/data-service/fo_sql-query.ru.md index 6e25edaea..5180b3c2d 100644 --- a/pages/products/flexberry-orm/data-service/fo_sql-query.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_sql-query.ru.md @@ -1,7 +1,7 @@ --- title: SQL-запросы в Flexberry sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, сервис данных, база данных, запросы, ограничения, ADO.NET +keywords: Flexberry ORM, сервис данных, база данных, запросы, ограничения, ADO.NET summary: Описание способов работы с БД и рекомендуемые способы доступа к БД toc: true permalink: ru/fo_sql-query.html @@ -40,7 +40,7 @@ lang: ru Ниже представлен пример исполнения SQL-запросов через технологию ADO.Net: ``` csharp -var connection = (SqlConnection)((SQLDataService)DataServiceProvider.DataService).GetConnection(); // Получение подключения. +var connection = (SqlConnection)((SQLDataService)DataServiceProvider.DataService).GetConnection(); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var command = new SqlCommand("SELECT SUM(purchase.\"Сумма\") "+ " FROM \"Покупатель\" customer join \"Покупка\" purchase on customer.\"primaryKey\" = purchase.\"Покупатель\" "+ " WHERE purchase.\"Покупатель\"=@Customer AND purchase.\"Статус\" = \'Оплачено\' ", connection); //формирование запроса diff --git a/pages/products/flexberry-orm/data-service/fo_standard-data-services.en.md b/pages/products/flexberry-orm/data-service/fo_standard-data-services.en.md index 3c3f95646..f4847fd9c 100644 --- a/pages/products/flexberry-orm/data-service/fo_standard-data-services.en.md +++ b/pages/products/flexberry-orm/data-service/fo_standard-data-services.en.md @@ -1,32 +1,29 @@ ---- -title: Standard data services Flexberry ORM -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, data services -summary: inheritance Hierarchy and description of data services -toc: true -permalink: en/fo_standard-data-services.html -lang: en -autotranslated: true -hash: 58d0e6ab4451c9ae16de8583a4774a4b1763a794aa9d064f9e760ba226f32920 ---- - -## the inheritance hierarchy for the data services - -![](/images/pages/products/flexberry-orm/data-service/i-data-service-inheritance.png) - -## Description of standard data services - -Following [data services](fo_data-service.html): - -* [ICSSoft.STORMNET.Business.XMLFileDataService](fo_xml-file-ds.html) to access the data in the format `XML` files. -* [ICSSoft.STORMNET.Business.SQLDataService](fo_sql-data-service.html) — basic ancestor of all data services working with relational sources. -* [ICSSoft.STORMNET.Business.MSSQLDataService](fo_mssql-data-service.html) is a data service to access the SQL `MS Server` directly, bypassing `ODBC`. Requires `SQL Client`, but the rate of work increases by approximately 25%. -* [ICSSoft.STORMNET.Business.DRDataService](fo_dr-data-service.html) is a data service for `MS SQL Server` that implements a "dirty read" of the data (`WITH (NOLOCK)`). -* [ICSSoft.STORMNET.Business.OracleDataService](fo_oracle-data-service.html) is a data service to access the `Oracle` directly, bypassing `ODBC`. Requires [client Oracle](fo_tools-oracle-ds.html). -* [ICSSoft.STORMNET.Business.PostgresDataService](fo_postgres-data-service.html) -* [ICSSoft.STORMNET.Business.ODBCDataService.ODBCDataService](fo_odbc-data-service.html) to access relational data sources. Independent of RDBMS, it is important the use of standards `ANSI` and `ODBC`. -[ICSSoft.STORMNET.Business.ODBCDataService.ODBCAccessDataService](fo_odbc-access-ds.html) — [ODBCDataService](fo_odbc-data-service.html), optimized for data access `СУБД Access`. *Use DB Access is possible only in the x86 version!** -* [ICSSoft.STORMNET.Business.ODBCDataService.ODBCMySqlDataService](fo_odbc-mysql-data-service.html) — [ODBCDataService](fo_odbc-data-service.html), optimized for data access `СУБД MySQL` (version 4.1 and later, with some restrictions on object structure). +--- +title: Standard data services Flexberry ORM +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, data services +summary: inheritance Hierarchy and description of data services +toc: true +permalink: en/fo_standard-data-services.html +lang: en +autotranslated: true +hash: 58d0e6ab4451c9ae16de8583a4774a4b1763a794aa9d064f9e760ba226f32920 +--- + +## the inheritance hierarchy for the data services + +![](/images/pages/products/flexberry-orm/data-service/i-data-service-inheritance.png) + +## Description of standard data services + +Following [data services](fo_data-service.html): + +* [ICSSoft.STORMNET.Business.XMLFileDataService](fo_xml-file-ds.html) to access the data in the format `XML` files. +* [ICSSoft.STORMNET.Business.SQLDataService](fo_sql-data-service.html) — basic ancestor of all data services working with relational sources. +* [ICSSoft.STORMNET.Business.MSSQLDataService](fo_mssql-data-service.html) is a data service to access the SQL `MS Server` directly, bypassing `ODBC`. Requires `SQL Client`, but the rate of work increases by approximately 25%. +* [ICSSoft.STORMNET.Business.DRDataService](fo_dr-data-service.html) is a data service for `MS SQL Server` that implements a "dirty read" of the data (`WITH (NOLOCK)`). +* [ICSSoft.STORMNET.Business.OracleDataService](fo_oracle-data-service.html) is a data service to access the `Oracle` directly, bypassing `ODBC`. Requires [client Oracle](fo_tools-oracle-ds.html). +* [ICSSoft.STORMNET.Business.PostgresDataService](fo_postgres-data-service.html) diff --git a/pages/products/flexberry-orm/data-service/fo_standard-data-services.ru.md b/pages/products/flexberry-orm/data-service/fo_standard-data-services.ru.md index 45eded04f..d061dc294 100644 --- a/pages/products/flexberry-orm/data-service/fo_standard-data-services.ru.md +++ b/pages/products/flexberry-orm/data-service/fo_standard-data-services.ru.md @@ -22,6 +22,3 @@ lang: ru * [ICSSoft.STORMNET.Business.DRDataService](fo_dr-data-service.html) — сервис данных для `MS SQL Server`, реализующий "грязное чтение" данных (`WITH (NOLOCK)`). * [ICSSoft.STORMNET.Business.OracleDataService](fo_oracle-data-service.html) — сервис данных для доступа к `Oracle` напрямую, минуя `ODBC`. Требует наличия [клиентского ПО Oracle](fo_tools-oracle-ds.html). * [ICSSoft.STORMNET.Business.PostgresDataService](fo_postgres-data-service.html) -* [ICSSoft.STORMNET.Business.ODBCDataService.ODBCDataService](fo_odbc-data-service.html) для доступа к реляционным источникам данных. Независим от реляционной СУБД, важно использование стандартов `ANSI` и `ODBC`. - [ICSSoft.STORMNET.Business.ODBCDataService.ODBCAccessDataService](fo_odbc-access-ds.html) — [ODBCDataService](fo_odbc-data-service.html), оптимизированный для доступа к данным `СУБД Access`. **Использование БД Access возможно только в х86-версии!** -* [ICSSoft.STORMNET.Business.ODBCDataService.ODBCMySqlDataService](fo_odbc-mysql-data-service.html) — [ODBCDataService](fo_odbc-data-service.html), оптимизированный для доступа к данным `СУБД MySQL` (версия 4.1 и более поздние, с некоторыми ограничениями на объектную структуру). diff --git a/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.en.md b/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.en.md index 6b2071839..b6790ff1c 100644 --- a/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.en.md +++ b/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.en.md @@ -34,7 +34,7 @@ In the attribute `DataServiceExpression` defined the expression that will be use Is equivalent to this expression on the C# code is written in the getter of the properties. ```csharp -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Person), Person.Views.Person_E); // Load all the data objects. Nechranice property will be computed using the expressions in the getter. diff --git a/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.ru.md b/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.ru.md index a48a317c8..06d586c06 100644 --- a/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.ru.md +++ b/pages/products/flexberry-orm/data-types/fo_nonstored-calculated-properties.ru.md @@ -32,7 +32,7 @@ public virtual string FullName Эквивалентный этому выражению код на C# написан в геттере свойства. ```csharp -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Person), Person.Views.Person_E); // Загрузить все объекты данных. Нехранимое свойство будет вычислено с помощью выражения в геттере. diff --git a/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.en.md b/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.en.md index 91589d4db..05c5a4864 100644 --- a/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.en.md +++ b/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.en.md @@ -112,7 +112,7 @@ Read more about how to work check for changes in the data objects written in [th ### Example of loading and saving object with its own types ```csharp -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(CDDA)); diff --git a/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.ru.md b/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.ru.md index bbcdbb7b0..dd0d969e0 100644 --- a/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.ru.md +++ b/pages/products/flexberry-orm/data-types/fo_using-custom-types-example.ru.md @@ -24,7 +24,7 @@ public class Dollar { private int fDollars; private int fCents; - + public Dollar(int Dollars, int Cents) { fDollars = 0; @@ -33,13 +33,13 @@ public class Dollar this.Cents = Cents; } - public int Dollars + public int Dollars { get{return fDollars;} - set + set { - if (value >= 0) - fDollars = value; + if (value >= 0) + fDollars = value; } } @@ -110,7 +110,7 @@ public virtual IIS.CDLIB.Dollar Price ### Пример загрузки и сохранения объекта с собственными типами ```csharp -IDataService dataService = DataServiceProvider.DataService; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. OrmSample ormSample = new OrmSample(dataService); object primaryKey = ormSample.GetSomeObjectPrimaryKey(typeof(CDDA)); diff --git a/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.en.md b/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.en.md index 6ea8b3e2b..bd1abb603 100644 --- a/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.en.md +++ b/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.en.md @@ -10,6 +10,8 @@ autotranslated: true hash: 44521544d5e3234f0d31b8a66b6803ed7b139f8e127dbe772d433632ea2ae457 --- +> Starting from ORM v8.0 DataServiceProvider is deprecated, use `IDataService` instead. + `DataServiceProvider.DataService` is [service data](fo_data-service.html), which is initialized based on the settings specified in the configuration file (`App.cobfig` or `Web.config`). Thus, `DataServiceProvider.DataService` is [service data](fo_data-service.html) by default. ### Algorithm initialization DataServiceProvider.DataService diff --git a/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.ru.md b/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.ru.md index a44f7b7a1..f1f46f13f 100644 --- a/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.ru.md +++ b/pages/products/flexberry-orm/dependency-injection/fo_ds-provider.ru.md @@ -8,6 +8,8 @@ permalink: ru/fo_ds-provider.html lang: ru --- +> С версии ORM 8.0 DataServiceProvider устарел, вместо него используйте внедрение зависимостей для получения `IDataService`. + `DataServiceProvider.DataService` - это [сервис данных](fo_data-service.html), который инициализируется на основании параметров, заданных в файле конфигурации (`App.cobfig` или `Web.config`). Таким образом, `DataServiceProvider.DataService` является [сервисом данных](fo_data-service.html) по умолчанию. ### Алгоритм инициализации DataServiceProvider.DataService diff --git a/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.en.md b/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.en.md index 2c0365779..2e0f2d686 100644 --- a/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.en.md +++ b/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.en.md @@ -10,6 +10,8 @@ autotranslated: true hash: 0d858097730c3894e0cabc212b9c2f0ca2f4fdfaeffbac720f1898b4a6d5ff3f --- +> UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. + `Flexberry UnityFactory` is [product platform Flexberry](fp_landing_page.html) and allows a standard way to work with a resolution of containers [Unity Container](https://msdn.microsoft.com/en-us/library/ff647202.aspx). Use the version of [Unity 2.1](https://msdn.microsoft.com/en-us/library/hh237493.aspx). {% include note.html content="Flexberry UnityFactory is available for installation in the project via the NuGet package Flexberry ORM." %} @@ -17,7 +19,7 @@ hash: 0d858097730c3894e0cabc212b9c2f0ca2f4fdfaeffbac720f1898b4a6d5ff3f Method `CreateContainer()` creates a default container to resolve the interface in real authority: ```csharp -IUnityContainer container = ICSSoft.Services.UnityFactory.CreateContainer(); +IUnityContainer container = ICSSoft.Services.UnityFactory.CreateContainer(); //UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. IService serviceInstance = container.Resolve(); ``` @@ -28,7 +30,7 @@ IService serviceInstance = container.Resolve(); Method `GetContainer()`, returns a single (application domain) of the container instance that allows to work correctly with objects of type `ContainerControlledLifetimemanager`. ``` csharp -IUnityContainer container = ICSSoft.Services.UnityFactory.GetContainer(); +IUnityContainer container = ICSSoft.Services.UnityFactory.GetContainer(); //UnityFactory is deprecated. Inject IUnityContainer (or IServiceProvider) instead. IService serviceInstance = container.Resolve(); ``` diff --git a/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.ru.md b/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.ru.md index dfab488c9..bebd642aa 100644 --- a/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.ru.md +++ b/pages/products/flexberry-orm/dependency-injection/fo_unity-factory.ru.md @@ -15,7 +15,7 @@ lang: ru Метод `CreateContainer()` создает контейнер по умолчанию, через который можно выполнить разрешение интерфейса в реальную инстанцию: ```csharp -IUnityContainer container = ICSSoft.Services.UnityFactory.CreateContainer(); +IUnityContainer container = ICSSoft.Services.UnityFactory.CreateContainer(); // UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). IService serviceInstance = container.Resolve(); ``` @@ -26,7 +26,7 @@ IService serviceInstance = container.Resolve(); Метод `GetContainer()`, возвращает единственный (на уровне домена приложения) экземпляр контейнера, что позволяет корректно работать с объектами типа `ContainerControlledLifetimeManager`. ``` csharp -IUnityContainer container = ICSSoft.Services.UnityFactory.GetContainer(); +IUnityContainer container = ICSSoft.Services.UnityFactory.GetContainer(); // UnityFactory устарел. Вместо него используйте внедрение зависимостей (инжектите IUnityContainer/IServiceProvider или напрямую нужные зависимости). IService serviceInstance = container.Resolve(); ``` diff --git a/pages/products/flexberry-orm/lock-service/fo_lock-service.en.md b/pages/products/flexberry-orm/lock-service/fo_lock-service.en.md index 137ec2332..3d14c2e73 100644 --- a/pages/products/flexberry-orm/lock-service/fo_lock-service.en.md +++ b/pages/products/flexberry-orm/lock-service/fo_lock-service.en.md @@ -20,18 +20,18 @@ To open blockages, you must use the method `ClearLock`. ```csharp Автор автор = new Автор(); -LockService ls = new LockService(); -ls.SetLock(автор); //Blocking -string sLockID = ls.SetLock(автор); //Attempt to lock the same object +LockService lockService = container.Resolve(); +lockService.SetLock(автор); //Blocking +string sLockID = lockService.SetLock(автор); //Attempt to lock the same object if (sLockID!=string.Empty) { Console.WriteLine(string.Format("Locked by: {0}", sLockID)); } -ls.ClearLock(автор);//Cleanup the lock +lockService.ClearLock(автор);//Cleanup the lock Console.ReadLine(); ``` -Service lock accesses the data store via [service data](fo_data-service.html) specified in the [service provider data](fo_ds-provider.html) (`ICSSoft.STORMNET.Business.DataServiceProvider.DataService`). +Service lock accesses the data store via [service data](fo_data-service.html) dependency, registered through Unity. Vault locks must be a corresponding source. diff --git a/pages/products/flexberry-orm/lock-service/fo_lock-service.ru.md b/pages/products/flexberry-orm/lock-service/fo_lock-service.ru.md index d271ed4bd..e006ec218 100644 --- a/pages/products/flexberry-orm/lock-service/fo_lock-service.ru.md +++ b/pages/products/flexberry-orm/lock-service/fo_lock-service.ru.md @@ -18,18 +18,18 @@ lang: ru ```csharp Автор автор = new Автор(); -LockService ls = new LockService(); -ls.SetLock(автор); //Блокирование -string sLockID = ls.SetLock(автор); //Попытка повторного блокирования того же объекта +LockService lockService = container.Resolve(); +lockService.SetLock(автор); //Blocking +string sLockID = lockService.SetLock(автор); //Attempt to lock the same object if (sLockID!=string.Empty) { - Console.WriteLine(string.Format("Заблокировано пользователем: {0}", sLockID)); + Console.WriteLine(string.Format("Locked by: {0}", sLockID)); } -ls.ClearLock(автор);//Очистка блокировки +lockService.ClearLock(автор);//Cleanup the lock Console.ReadLine(); ``` -Сервис блокировок обращается к хранилищу данных через [сервис данных](fo_data-service.html), указанный в [провайдере сервиса данных](fo_ds-provider.html) (`ICSSoft.STORMNET.Business.DataServiceProvider.DataService`). +Сервис блокировок обращается к хранилищу данных через [сервис данных](fo_data-service.html), зарегистрированный в файле конфигурации с помощью Unity. В хранилище для блокировок должен существовать соответствующий источник. @@ -39,6 +39,6 @@ Console.ReadLine(); SQL CREATE TABLE STORMNETLOCKDATA ( LockKey char (300) NOT NULL , - UserName char (300) NOT NULL + UserName char (300) NOT NULL ) ``` diff --git a/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.en.md b/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.en.md index 58d201e7b..e6a1b04f5 100644 --- a/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.en.md +++ b/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.en.md @@ -227,7 +227,7 @@ public static void Register(HttpConfiguration config) config.DependencyResolver = new UnityDependencyResolver(container); // The most important thing for the ODataService to know what data service is used. You can register here or on the web.config in the section Unity. - container.RegisterInstance(DataServiceProvider.DataService); + container.RegisterInstance(DataServiceProvider.DataService); // DataServiceProvider is deprecated; inject IDataService instead try { @@ -263,7 +263,7 @@ public static void Register(HttpConfiguration config) /// private static object GetLastRoundIdForTopic(ODataFunctions.QueryParameters queryParameters, Dictionary parameters) { - ApplicationLogicBS bs = new ApplicationLogicBS { DataService = DataServiceProvider.DataService }; + ApplicationLogicBS bs = new ApplicationLogicBS { DataService = DataServiceProvider.DataService }; // DataServiceProvider is deprecated; inject IDataService instead return bs.GetLastRoundIdForTopic((string)parameters["topicId"]); } ``` @@ -473,7 +473,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static IEnumerable FunctionWithLcs1(QueryParameters queryParameters, string entitySet) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider is deprecated; inject IDataService instead var type = queryParameters.GetDataObjectType(entitySet); var lcs = queryParameters.CreateLcs(type); var dobjs = dataService.LoadObjects(lcs); @@ -489,7 +489,7 @@ private static IEnumerable FunctionWithLcs1(QueryParameters queryPar /// private static int FunctionWithLcs2(QueryParameters queryParameters, string entitySet, string query) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider is deprecated; inject IDataService instead var type = queryParameters.GetDataObjectType(entitySet); var uri = $"http://a/b/c?{query}"; var lcs = queryParameters.CreateLcs(type, uri); @@ -542,7 +542,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static IEnumerable ActionWithLcs(QueryParameters queryParameters, string entitySet, string query) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider is deprecated; inject IDataService instead var type = queryParameters.GetDataObjectType(entitySet); var uri = $"http://a/b/c?{query}"; var lcs = queryParameters.CreateLcs(type, uri); @@ -598,7 +598,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static Страна[] FunctionExportExcel(QueryParameters queryParameters, string entitySet) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider is deprecated; inject IDataService instead Type type = queryParameters.GetDataObjectType(entitySet); LoadingCustomizationStruct lcs = queryParameters.CreateLcs(type); Страна[] dobjs = dataService.LoadObjects(lcs).Cast<Страна>().ToArray(); diff --git a/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.ru.md b/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.ru.md index dbb25cdcc..5549fce85 100644 --- a/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.ru.md +++ b/pages/products/flexberry-orm/odata-service/fo_orm-odata-service.ru.md @@ -20,7 +20,7 @@ lang: ru ## Логика работы ODataService -ODataService представляет собой WebApi-контроллер, который предоставляет доступ к данным в БД по протоколу OData V4. +ODataService представляет собой WebApi-контроллер, который предоставляет доступ к данным в БД по протоколу OData V4. Типичный запрос на выборку данных работает следующим образом: * HTTP GET запрос формулируется клиентом в виде url с указанием типа требуемых данных, нужных атрибутов, фильтрации, сортировки и т.д. @@ -133,7 +133,7 @@ namespace ODataServiceTemplate - + ``` @@ -225,7 +225,7 @@ public static void Register(HttpConfiguration config) config.DependencyResolver = new UnityDependencyResolver(container); // Самое главное для ODataService - знать какой сервис данных используется. Можно зарегистрировать тут или в web.config в секции Unity. - container.RegisterInstance(DataServiceProvider.DataService); + container.RegisterInstance(DataServiceProvider.DataService); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. try { @@ -261,7 +261,7 @@ public static void Register(HttpConfiguration config) /// private static object GetLastRoundIdForTopic(ODataFunctions.QueryParameters queryParameters, Dictionary parameters) { - ApplicationLogicBS bs = new ApplicationLogicBS { DataService = DataServiceProvider.DataService }; + ApplicationLogicBS bs = new ApplicationLogicBS { DataService = DataServiceProvider.DataService }; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. return bs.GetLastRoundIdForTopic((string)parameters["topicId"]); } ``` @@ -365,7 +365,7 @@ public static void Register(HttpConfiguration config) public static bool BeforeGet(ref LoadingCustomizationStruct lcs) { return true; -} +} /// /// Метод вызываемый после вычитывания объектов. В нем производится дополнительная обработка возвращаемого результата. @@ -459,7 +459,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, ManagementToken odataServiceManagementToken = config.MapODataServiceDataObjectRoute(builder); config.MapODataServiceFileRoute("File", "api/File", HttpContext.Current.Server.MapPath("~/Uploads"), container.Resolve()); odataServiceManagementToken.Functions.Register(new Func>(FunctionWithLcs1)); - odataServiceManagementToken.Functions.Register(new Func(FunctionWithLcs2)); + odataServiceManagementToken.Functions.Register(new Func(FunctionWithLcs2)); } /// @@ -471,7 +471,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static IEnumerable FunctionWithLcs1(QueryParameters queryParameters, string entitySet) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var type = queryParameters.GetDataObjectType(entitySet); var lcs = queryParameters.CreateLcs(type); var dobjs = dataService.LoadObjects(lcs); @@ -487,7 +487,7 @@ private static IEnumerable FunctionWithLcs1(QueryParameters queryPar /// private static int FunctionWithLcs2(QueryParameters queryParameters, string entitySet, string query) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var type = queryParameters.GetDataObjectType(entitySet); var uri = $"http://a/b/c?{query}"; var lcs = queryParameters.CreateLcs(type, uri); @@ -540,7 +540,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static IEnumerable ActionWithLcs(QueryParameters queryParameters, string entitySet, string query) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. var type = queryParameters.GetDataObjectType(entitySet); var uri = $"http://a/b/c?{query}"; var lcs = queryParameters.CreateLcs(type, uri); @@ -596,7 +596,7 @@ public static void Register(HttpConfiguration config, IUnityContainer container, /// private static Страна[] FunctionExportExcel(QueryParameters queryParameters, string entitySet) { - SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; + SQLDataService dataService = DataServiceProvider.DataService as SQLDataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. Type type = queryParameters.GetDataObjectType(entitySet); LoadingCustomizationStruct lcs = queryParameters.CreateLcs(type); Страна[] dobjs = dataService.LoadObjects(lcs).Cast<Страна>().ToArray(); @@ -606,10 +606,10 @@ private static Страна[] FunctionExportExcel(QueryParameters queryParameter ## Пример ограничений на псевдодетейлы в ODataService -`Flexberry ORM` позволяет строить [ограничения на "ассоциацию в обратную сторону" или "псевдодетейлы"](fo_psedodetails-linq-provider.html). Данная возможность предоставляется и при работе с данными через ODataService. -Для того, чтобы появилась возможность построить ограничение подобного вида, надо объявить её допустимость на уровне метаданных в EDM-модели OData. -Рассмотрим данную схему в качестве примера: -![schema](/images/pages/products/flexberry-orm/query-language/pseudo-details.png) +`Flexberry ORM` позволяет строить [ограничения на "ассоциацию в обратную сторону" или "псевдодетейлы"](fo_psedodetails-linq-provider.html). Данная возможность предоставляется и при работе с данными через ODataService. +Для того, чтобы появилась возможность построить ограничение подобного вида, надо объявить её допустимость на уровне метаданных в EDM-модели OData. +Рассмотрим данную схему в качестве примера: +![schema](/images/pages/products/flexberry-orm/query-language/pseudo-details.png) Пример регистрации псевдодетейла: ```csharp diff --git a/pages/products/flexberry-orm/query-language/fo_exist-details.en.md b/pages/products/flexberry-orm/query-language/fo_exist-details.en.md index fd10c9f77..937969f39 100644 --- a/pages/products/flexberry-orm/query-language/fo_exist-details.en.md +++ b/pages/products/flexberry-orm/query-language/fo_exist-details.en.md @@ -31,7 +31,7 @@ The following code assumes that the view `"Servicedisplayname"` always present p Required to deduct the servers that belong to a particular Department (i.e., servers that belong to the specified Unit and some will also be proofread). ```csharp -ExternalLangDef ldef = ExternalLangDef.LanguageDef; +ExternalLangDef ldef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). LoadingCustomizationStruct lcsСервер = LoadingCustomizationStruct.GetSimpleStruct(typeof (Репликации.Сервер), "Server"); lcsСервер.LoadingTypes = new Type[] {typeof (Репликации.Сервер)}; View view = Information.GetView("Servicedisplayname", typeof(Репликации.СерверПодразделения)); @@ -46,13 +46,13 @@ lcsСервер.LimitFunction = ldef.GetFunction(ldef.funcExist, new VariableDef(ldef.GuidType, Division), UpdatedObject.НаправленоИз.__PrimaryKey)); lcsСервер.ReturnTop = 1; -ICSSoft.STORMNET.DataObject[] dobjsСервер = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcsСервер); +ICSSoft.STORMNET.DataObject[] dobjsСервер = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcsСервер); // DataServiceProvider is deprecated; inject IDataService instead ``` You want to subtract only those servers that belong only to one particular Unit (i.e., servers that belong to the specified Division and some will not be proofread). ```csharp -ExternalLangDef ldef = ICSSoft.STORMNET.Windows.Forms.ExternalLangDef.LanguageDef; +ExternalLangDef ldef = ICSSoft.STORMNET.Windows.Forms.ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). LoadingCustomizationStruct lcsСервер = LoadingCustomizationStruct.GetSimpleStruct(typeof (Сервер), "Server"); lcsСервер.LoadingTypes = new[] {typeof (Сервер)}; View view = Information.GetView("Servicedisplayname", typeof(Репликации.СерверПодразделения)); @@ -68,7 +68,7 @@ lcsСервер.LimitFunction = ldef.GetFunction(ldef.funcExistExact, ldef.GetFunction(ldef.funcEQ, new VariableDef(ldef.GuidType, Division), new Guid("6D7DC426-F5E9-4F63-B7B5-20C9E237DF2D"))); -DataObject[] dobjsСервер = DataServiceProvider.DataService.LoadObjects(lcsСервер); +DataObject[] dobjsСервер = DataServiceProvider.DataService.LoadObjects(lcsСервер); // DataServiceProvider is deprecated; inject IDataService instead ``` ## Comparison of properties of two different datalow (not above ground level) with a common aggregator @@ -83,14 +83,14 @@ The order of properties in the comparison function applied to detali has a value view.AddDetailInView("Computer", view2, true); view.AddDetailInView("Computer", view3, true); var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Computer), view); - ExternalLangDef langDef = ExternalLangDef.LanguageDef; + ExternalLangDef langDef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var detail1 = new DetailVariableDef(langDef.GetObjectType("Details"), "Hardware", view2, "Computer"); var detail2 = new DetailVariableDef(langDef.GetObjectType("Details"), "Software", view3, "Computer"); lcs.LimitFunction = langDef.GetFunction(langDef.funcExistDetails, detail1, detail2, langDef.GetFunction(langDef.funcG, new VariableDef(langDef.DateTimeType, "DeliveryDate"), new VariableDef(langDef.DateTimeType, "DeliveryDate"))); - var dos = DataServiceProvider.DataService.LoadObjects(lcs); + var dos = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead ``` diff --git a/pages/products/flexberry-orm/query-language/fo_exist-details.ru.md b/pages/products/flexberry-orm/query-language/fo_exist-details.ru.md index c2a007ca8..ec402d8bc 100644 --- a/pages/products/flexberry-orm/query-language/fo_exist-details.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_exist-details.ru.md @@ -44,13 +44,13 @@ lcsСервер.LimitFunction = ldef.GetFunction(ldef.funcExist, new VariableDef(ldef.GuidType, "Подразделение"), UpdatedObject.НаправленоИз.__PrimaryKey)); lcsСервер.ReturnTop = 1; -ICSSoft.STORMNET.DataObject[] dobjsСервер = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcsСервер); +ICSSoft.STORMNET.DataObject[] dobjsСервер = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcsСервер); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` Требуется вычитать только те сервера, которые принадлежат только одному конкретному Подразделению (т.е. сервера, которые принадлежат и указанному Подразделению и еще какому-то, не будут вычитаны). ```csharp -ExternalLangDef ldef = ICSSoft.STORMNET.Windows.Forms.ExternalLangDef.LanguageDef; +ExternalLangDef ldef = ICSSoft.STORMNET.Windows.Forms.ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). LoadingCustomizationStruct lcsСервер = LoadingCustomizationStruct.GetSimpleStruct(typeof (Сервер), "СерверE"); lcsСервер.LoadingTypes = new[] {typeof (Сервер)}; View view = Information.GetView("СерверПодразделенияE", typeof(Репликации.СерверПодразделения)); @@ -66,7 +66,7 @@ lcsСервер.LimitFunction = ldef.GetFunction(ldef.funcExistExact, ldef.GetFunction(ldef.funcEQ, new VariableDef(ldef.GuidType, "Подразделение"), new Guid("6D7DC426-F5E9-4F63-B7B5-20C9E237DF2D"))); -DataObject[] dobjsСервер = DataServiceProvider.DataService.LoadObjects(lcsСервер); +DataObject[] dobjsСервер = DataServiceProvider.DataService.LoadObjects(lcsСервер); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` ## Сравнения свойств двух различных детейлов (не выше первого уровня) имеющих общий агрегатор @@ -81,12 +81,12 @@ DataObject[] dobjsСервер = DataServiceProvider.DataService.LoadObjects(lcs view.AddDetailInView("Computer", view2, true); view.AddDetailInView("Computer", view3, true); var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Computer), view); - ExternalLangDef langDef = ExternalLangDef.LanguageDef; + ExternalLangDef langDef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var detail1 = new DetailVariableDef(langDef.GetObjectType("Details"), "Hardware", view2, "Computer"); var detail2 = new DetailVariableDef(langDef.GetObjectType("Details"), "Software", view3, "Computer"); lcs.LimitFunction = langDef.GetFunction(langDef.funcExistDetails, detail1, detail2, langDef.GetFunction(langDef.funcG, new VariableDef(langDef.DateTimeType, "DeliveryDate"), new VariableDef(langDef.DateTimeType, "DeliveryDate"))); - var dos = DataServiceProvider.DataService.LoadObjects(lcs); + var dos = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` diff --git a/pages/products/flexberry-orm/query-language/fo_function-builder.en.md b/pages/products/flexberry-orm/query-language/fo_function-builder.en.md index 9f296ea31..ea57756a3 100644 --- a/pages/products/flexberry-orm/query-language/fo_function-builder.en.md +++ b/pages/products/flexberry-orm/query-language/fo_function-builder.en.md @@ -1,13 +1,13 @@ ---- -title: FunctionBuilder -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM, Limitations +--- +title: FunctionBuilder +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM, Limitations summary: Building functions with FunctionBuilder -toc: true -permalink: en/fo_function-builder.html -lang: en +toc: true +permalink: en/fo_function-builder.html +lang: en autotranslated: false ---- +--- [Limit functions](fo_limit-function.html) may be built using [SQLWhereLanguageDef](fo_function-list.html) or [ExternalLangDef](fo_external-lang-def.html), but they has rather bulky syntax. @@ -25,8 +25,8 @@ Imagine domain model with Document entity and DocumentLink entity, which has two In case we need to load from database all DocumentLinks with specified link type name, which links two document and we shouldn't take in account the order of links. So we should get limit function similar to sql query: ``` sql -SELECT * -FROM DocumentLink +SELECT * +FROM DocumentLink JOIN DocumentLinkType ON DocumentLinkType.PrimaryKey = DocumentLink.DocumentLinkType WHERE DocumentLinkType.Name = @typeName AND ((Document = @document1 AND LinkedDocument = @document2) OR (Document = @document2 AND LinkedDocument = @document1)) @@ -38,10 +38,10 @@ var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(DocumentLink), Docum lcs.LimitFunction = langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.StringType, "DocumentLinkType.Name"), typeName), langdef.GetFunction(langdef.funcOR, - langdef.GetFunction(langdef.funcAND, + langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Document"), document1.__PrimaryKey), langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "LinkedDocument"), document2.__PrimaryKey)), - langdef.GetFunction(langdef.funcAND, + langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Document"), document2.__PrimaryKey), langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "LinkedDocument"), document1.__PrimaryKey)))); ``` @@ -67,9 +67,9 @@ lcs.LimitFunction = FunctionBuilder.BuildAnd( As you can see code with FunctionBuilder looks similar but is more readable because of less number of arguments and no need to create VariableDef manually in most cases. Moreover FunctionBuilder protects from making mistake in property path because of generic method using, which controls avaliable properties in object. Similar code may be implemented for `GetFunction` using `Information.ExtractPropertyPath()` method, but it will be even more bulky. ## Source code -`FunctionBuilder` and supporting classes source code is available on [ORM repository](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/ExternalLangDef/FunctionBuilder). All methods are covered with unit tests, source code available in [ORM repository](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/NewPlatform.Flexberry.ORM.Tests/ICSSoft.STORMNET.FunctionalLanguage). +`FunctionBuilder` and supporting classes source code is available on [ORM repository](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/ICSSoft.STORMNET.Business.ExternalLangDef/FunctionBuilder). All methods are covered with unit tests, source code available in [ORM repository](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/NewPlatform.Flexberry.ORM.Tests/ICSSoft.STORMNET.FunctionalLanguage). + - ## FunctionBuilder methods List of methods may change during time, so you may find full list of available methods in [autodocumentation](https://flexberry.github.io/NewPlatform.Flexberry.ORM/autodoc/develop/class_i_c_s_soft_1_1_s_t_o_r_m_n_e_t_1_1_functional_language_1_1_function_builder.html). diff --git a/pages/products/flexberry-orm/query-language/fo_function-builder.ru.md b/pages/products/flexberry-orm/query-language/fo_function-builder.ru.md index 4242771fe..ca4e24dba 100644 --- a/pages/products/flexberry-orm/query-language/fo_function-builder.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_function-builder.ru.md @@ -24,8 +24,8 @@ lang: ru Предположим, нам необходимо вычитать из БД все объекты DocumentLink с определенным наименованием типа связи, связывающие два документа, и при этом не учитывать порядок, в котором фигурируют заданные документы в объекте СвязьДокументов. Таким образом мы должны получить ограничение, примерно соответствующее следующему sql-запросу: ``` sql -SELECT * -FROM DocumentLink +SELECT * +FROM DocumentLink JOIN DocumentLinkType ON DocumentLinkType.PrimaryKey = DocumentLink.DocumentLinkType WHERE DocumentLinkType.Name = @typeName AND ((Document = @document1 AND LinkedDocument = @document2) OR (Document = @document2 AND LinkedDocument = @document1)) @@ -37,10 +37,10 @@ var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(DocumentLink), Docum lcs.LimitFunction = langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.StringType, "DocumentLinkType.Name"), typeName), langdef.GetFunction(langdef.funcOR, - langdef.GetFunction(langdef.funcAND, + langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Document"), document1.__PrimaryKey), langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "LinkedDocument"), document2.__PrimaryKey)), - langdef.GetFunction(langdef.funcAND, + langdef.GetFunction(langdef.funcAND, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Document"), document2.__PrimaryKey), langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "LinkedDocument"), document1.__PrimaryKey)))); ``` @@ -66,7 +66,7 @@ lcs.LimitFunction = FunctionBuilder.BuildAnd( Как можно видеть из примера, код построения функции с использованием FunctionBuilder очень похож, но становится читаемее за счет меньшего количества аргументов у методов, а также отсутствия необходимости создавать VariableDef вручную в большинстве случаев. Кроме того, в примере с `FunctionBuilder-ом` нельзя допустить ошибку в пути свойства, поскольку используется generic-метод, контролирующий имеющиеся в объекте свойства. Аналогичный по возможностям код можно реализовать и в случае использования `GetFunction` с использованием метода `Information.ExtractPropertyPath()`, однако это сделает код еще многословнее. ## Исходный код -С исходным кодом `FunctionBuilder` и вспомогательных классов можно ознакомиться в [репозитории ORM](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/ExternalLangDef/FunctionBuilder). Все методы покрыты тестовыми сценариями, с кодом которых также можно ознакомиться в [репозитории ORM](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/NewPlatform.Flexberry.ORM.Tests/ICSSoft.STORMNET.FunctionalLanguage). +С исходным кодом `FunctionBuilder` и вспомогательных классов можно ознакомиться в [репозитории ORM](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/ICSSoft.STORMNET.Business.ExternalLangDef/FunctionBuilder). Все методы покрыты тестовыми сценариями, с кодом которых также можно ознакомиться в [репозитории ORM](https://github.com/Flexberry/NewPlatform.Flexberry.ORM/tree/develop/NewPlatform.Flexberry.ORM.Tests/ICSSoft.STORMNET.FunctionalLanguage). ## Методы, доступные в FunctionBuilder diff --git a/pages/products/flexberry-orm/query-language/fo_function-list.en.md b/pages/products/flexberry-orm/query-language/fo_function-list.en.md index 926a6a4df..af39460e7 100644 --- a/pages/products/flexberry-orm/query-language/fo_function-list.en.md +++ b/pages/products/flexberry-orm/query-language/fo_function-list.en.md @@ -1,138 +1,140 @@ ---- -title: SQLWhereLanguageDef -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM Limitations -summary: Rules for the imposition of restrictions on the deducted objects -toc: true -permalink: en/fo_function-list.html -lang: en -autotranslated: true -hash: ba32420ecf26a5cd6abe36058dd1070be45d8980b96cdf01f87825cf23655b25 ---- +--- +title: SQLWhereLanguageDef +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM Limitations +summary: Rules for the imposition of restrictions on the deducted objects +toc: true +permalink: en/fo_function-list.html +lang: en +autotranslated: true +hash: ba32420ecf26a5cd6abe36058dd1070be45d8980b96cdf01f87825cf23655b25 +--- -`SQLWhereLanguageDef` class Builder [functions, the restrictions](fo_limit-function.html) deducted on objects. +`SQLWhereLanguageDef` class Builder [functions, the restrictions](fo_limit-function.html) deducted on objects. -There is an extension of basic functional language `SQLWhereLanguageDef`, `[ExternalLangDef](fo_external-lang-def.html). +There is an extension of basic functional language `SQLWhereLanguageDef`, `[ExternalLangDef](fo_external-lang-def.html). -Connection: +Connection: ``` csharp using ICSSoft.STORMNET.FunctionalLanguage; using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; -``` +``` -## the Construction of function, method GetFunction +## the Construction of function, method GetFunction -The construction of the function starts with calling the method `ICSSoft.STORMNET.FunctionalLanguage.FunctionalLanguageDef.GetFucntion(string, params object[));` +The construction of the function starts with calling the method `ICSSoft.STORMNET.FunctionalLanguage.FunctionalLanguageDef.GetFucntion(string, params object[));` -As the first parameter the method takes a function type (a list of available functions below). The method accepts a set of function parameters, number and types of parameters vary depending on the type of function, a detailed description thereof can be found in the article devoted to a particular type of function. +As the first parameter the method takes a function type (a list of available functions below). The method accepts a set of function parameters, number and types of parameters vary depending on the type of function, a detailed description thereof can be found in the article devoted to a particular type of function. -The method returns an object of type `ICSSoft.STORMNET.FunctionalLanguage.Function`. +The method returns an object of type `ICSSoft.STORMNET.FunctionalLanguage.Function`. -Depending on the type of the function parameter of the function `GetFunction` can be passed a description of the variable specified in the class [VariableDef](fo_variable-def.html). +Depending on the type of the function parameter of the function `GetFunction` can be passed a description of the variable specified in the class [VariableDef](fo_variable-def.html). -## the restrictions imposed on the enum type +## the restrictions imposed on the enum type -[Enumerations|Enumeration types) is stored in the database as strings. Accordingly, when constructing the variable description ([VariableDef](fo_variable-def.html)) you must use `StringType`. The argument for comparison is recommended to use `Caption` enumeration object, to `Caption` you can use class `EnumCaption`, which is part of `ICSSoft.STORMNET`. +[Enumerations|Enumeration types) is stored in the database as strings. Accordingly, when constructing the variable description ([VariableDef](fo_variable-def.html)) you must use `StringType`. The argument for comparison is recommended to use `Caption` enumeration object, to `Caption` you can use class `EnumCaption`, which is part of `ICSSoft.STORMNET`. -For example: +For example: -![](/images/pages/products/flexberry-orm/query language/Pol.PNG) +![](/images/pages/products/flexberry-orm/query language/Pol.PNG) -To impose restrictions on the gender of the client, you should compile the following function: +To impose restrictions on the gender of the client, you should compile the following function: ```csharp using ICSSoft.STORMNET; -// ... +// ... var ld = SQLWhereLanguageDef.LanguageDef; var onlyMenFunction = ld.GetFunction(ld.funcEQ, new VariableDef(ld.StringType, Information.ExtractPropertyPath<Клиент>(x => x.Пол)), EnumCaption.GetCaptionFor(tПол.Мужской)); -``` +``` -## the Imposition of limitations on the date components +## the Imposition of limitations on the date components -To impose a restriction on the date part (year, month, or day), you can use the functions `DayPart`, `MonthPart` and `YearPart` for specifying constraints on components of the date. +To impose a restriction on the date part (year, month, or day), you can use the functions `DayPart`, `MonthPart` and `YearPart` for specifying constraints on components of the date. -### Example +### Example ```csharp -//ICSSoft.STORMNET.Windows.Forms.ExternalLangDef (ExternalLangDef.dll) -//ICSSoft.STORMNET.Windows.Forms.ExternalLangDeflangdef = ExternalLangDef.LanguageDef; +//ICSSoft.STORMNET.Windows.Forms.ExternalLangDef (ICSSoft.STORMNET.Business.ExternalLangDef.dll) +//ICSSoft.STORMNET.Windows.Forms.ExternalLangDeflangdef = ExternalLangDef.LanguageDef; using ICSSoft.STORMNET.Windows.Forms; -var langdef = ExternalLangDef.LanguageDef; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead + +var langdef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, - langdef.GetFunction("YearPart", new VariableDef(langdef.DateTimeType, "Datavideo")), "2013"); + langdef.GetFunction("YearPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "2013"); -var only2013year = DataServiceProvider.DataService.LoadObjects(lcs); +var only2013year = dataService.LoadObjects(lcs); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, - langdef.GetFunction("MonthPart", new VariableDef(langdef.DateTimeType, "Datavideo")), "12"); + langdef.GetFunction("MonthPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "12"); -var onlyDecember = DataServiceProvider.DataService.LoadObjects(lcs); +var onlyDecember = dataService.LoadObjects(lcs); lcs.LimitFunction = langdef.GetFunction(langdef.funcAND, - langdef.GetFunction(langdef.funcEQ, + langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("YearPart", new VariableDef(langdef.DateTimeType, "Datavideo")), "2012"), - langdef.GetFunction(langdef.funcEQ, + langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("MonthPart", new VariableDef(langdef.DateTimeType, "Datavideo")), "12")); -var onlyDecember2012 = DataServiceProvider.DataService.LoadObjects(lcs); -``` +var onlyDecember2012 = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead +``` -## Examples of usage +## Examples of usage -Following are some examples of restrictions: +Following are some examples of restrictions: -### the Imposition of constraints on the string variable +### the Imposition of constraints on the string variable ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Личность), Личность.Views.ЛичностьE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.StringType, Information.ExtractPropertyPath<Личность>(x => x.Фамилия)), Petrov); -var клиентыФамилияПетров = DataServiceProvider.DataService.LoadObjects(lcs); -``` +var клиентыФамилияПетров = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead +``` -### the Imposition of limitations on workman the object (the key) +### the Imposition of limitations on workman the object (the key) ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, Information.ExtractPropertyPath<Кредит>(x => x.Личность)), "64F45BC3-339B-4FBA-A036-C5E9FE9EAE53"); -var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); -``` +var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead +``` -### the Imposition of limitations on workman the object (field master) +### the Imposition of limitations on workman the object (field master) ```csharp var langdef = ExternalLangDef.LanguageDef; var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, Information.ExtractPropertyPath<Кредит>(x => x.Личность.Фамилия)), Petrov); -var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); -``` - -{% include important.html content="you Must ensure that the submission is `КредитE` master `Личность` and field `Фамилия`, or an error occurs during query execution." %} - -## List of functions - -* [FuncNOT](fo_func-not.html) -* [FuncIsNull](fo_func-is-null.html) -* [FuncEQ](fo_func-eq.html) -* [FuncNEQ](fo_func-neq.html) -* [FuncG](fo_compare-functions.html) -* [FuncGEQ](fo_compare-functions.html) -* [FuncL](fo_compare-functions.html) -* [FuncLEQ](fo_compare-functions.html) -* [FuncIN](fo_func-in.html) -* [FuncAND](fo_func-and.html) -* [FuncOR](fo_func-or.html) -* [FuncLike](fo_func-like.html) -* [FuncBETWEEN](fo_func-between.html) -* [funcSQL](fo_func-sql.html) +var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead +``` + +{% include important.html content="you Must ensure that the submission is `КредитE` master `Личность` and field `Фамилия`, or an error occurs during query execution." %} + +## List of functions + +* [FuncNOT](fo_func-not.html) +* [FuncIsNull](fo_func-is-null.html) +* [FuncEQ](fo_func-eq.html) +* [FuncNEQ](fo_func-neq.html) +* [FuncG](fo_compare-functions.html) +* [FuncGEQ](fo_compare-functions.html) +* [FuncL](fo_compare-functions.html) +* [FuncLEQ](fo_compare-functions.html) +* [FuncIN](fo_func-in.html) +* [FuncAND](fo_func-and.html) +* [FuncOR](fo_func-or.html) +* [FuncLike](fo_func-like.html) +* [FuncBETWEEN](fo_func-between.html) +* [funcSQL](fo_func-sql.html) diff --git a/pages/products/flexberry-orm/query-language/fo_function-list.ru.md b/pages/products/flexberry-orm/query-language/fo_function-list.ru.md index 5cb7d1f36..c6826bac4 100644 --- a/pages/products/flexberry-orm/query-language/fo_function-list.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_function-list.ru.md @@ -36,7 +36,7 @@ using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; Например: ![](/images/pages/products/flexberry-orm/query-language/Pol.PNG) - + Чтобы наложить ограничение на пол клиента, необходимо составить следующую функцию: ```csharp @@ -53,30 +53,32 @@ var onlyMenFunction = ld.GetFunction(ld.funcEQ, new VariableDef(ld.StringType, I ### Пример ```csharp -//ICSSoft.STORMNET.Windows.Forms.ExternalLangDef (ExternalLangDef.dll) +//ICSSoft.STORMNET.Windows.Forms.ExternalLangDef (ICSSoft.STORMNET.Business.ExternalLangDef.dll) //ICSSoft.STORMNET.Windows.Forms.ExternalLangDeflangdef = ExternalLangDef.LanguageDef; using ICSSoft.STORMNET.Windows.Forms; -var langdef = ExternalLangDef.LanguageDef; +IDataService dataService = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. + +var langdef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("YearPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "2013"); -var only2013year = DataServiceProvider.DataService.LoadObjects(lcs); +var only2013year = dataService.LoadObjects(lcs); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("MonthPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "12"); -var onlyDecember = DataServiceProvider.DataService.LoadObjects(lcs); +var onlyDecember = dataService.LoadObjects(lcs); lcs.LimitFunction = langdef.GetFunction(langdef.funcAND, - langdef.GetFunction(langdef.funcEQ, + langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("YearPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "2012"), - langdef.GetFunction(langdef.funcEQ, + langdef.GetFunction(langdef.funcEQ, langdef.GetFunction("MonthPart", new VariableDef(langdef.DateTimeType, "ДатаВыдачи")), "12")); -var onlyDecember2012 = DataServiceProvider.DataService.LoadObjects(lcs); +var onlyDecember2012 = dataService.LoadObjects(lcs); ``` ## Примеры использования @@ -86,31 +88,31 @@ var onlyDecember2012 = DataServiceProvider.DataService.LoadObjects(lcs); ### Наложение ограничений на строковую переменную ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Личность), Личность.Views.ЛичностьE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.StringType, Information.ExtractPropertyPath<Личность>(x => x.Фамилия)), "Петров"); -var клиентыФамилияПетров = DataServiceProvider.DataService.LoadObjects(lcs); +var клиентыФамилияПетров = dataService.LoadObjects(lcs); ``` ### Наложение ограничений на мастеровой объект (по ключу) ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, Information.ExtractPropertyPath<Кредит>(x => x.Личность)), "64F45BC3-339B-4FBA-A036-C5E9FE9EAE53"); -var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); +var кредиты = dataService.LoadObjects(lcs); ``` ### Наложение ограничений на мастеровой объект (по полю мастера) ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof (Кредит), Кредит.Views.КредитE); lcs.LimitFunction = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, Information.ExtractPropertyPath<Кредит>(x => x.Личность.Фамилия)), "Петров"); -var кредиты = DataServiceProvider.DataService.LoadObjects(lcs); +var кредиты = dataService.LoadObjects(lcs); ``` {% include important.html content="Следует убедиться, что в представлении `КредитE` есть мастер `Личность` и его поле `Фамилия`, иначе произойдёт ошибка при выполнении запроса." %} diff --git a/pages/products/flexberry-orm/query-language/fo_limit-details.en.md b/pages/products/flexberry-orm/query-language/fo_limit-details.en.md index 132ead062..569b7ae58 100644 --- a/pages/products/flexberry-orm/query-language/fo_limit-details.en.md +++ b/pages/products/flexberry-orm/query-language/fo_limit-details.en.md @@ -28,13 +28,13 @@ To identify erroneously entered data in the database: find all companies that ha View view2 = Information.GetView("SoftwareL", typeof(Software)); view.AddDetailInView("Software", view2, true); var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Company), view); - ExternalLangDef langDef = ExternalLangDef.LanguageDef; + ExternalLangDef langDef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var detail = new DetailVariableDef(langDef.GetObjectType("Details"), "Software", view2, "Company"); lcs.LimitFunction = langDef.GetFunction(langDef.funcExist, detail, langDef.GetFunction(langDef.funcL, new VariableDef(langDef.DateTimeType, Information.ExtractPropertyPath(x => x.DateCreation)), new VariableDef(langDef.DateTimeType, Information.ExtractPropertyPath(x => x.Company.DateCreation)))); - var dos = DataServiceProvider.DataService.LoadObjects(lcs); + var dos = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead ``` diff --git a/pages/products/flexberry-orm/query-language/fo_limit-details.ru.md b/pages/products/flexberry-orm/query-language/fo_limit-details.ru.md index 130c95540..fa4471bd5 100644 --- a/pages/products/flexberry-orm/query-language/fo_limit-details.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_limit-details.ru.md @@ -8,7 +8,7 @@ permalink: ru/fo_limit-details.html lang: ru --- -Если необходимо задать условие на существование [детейлов](fd_key-concepts.html) по условию, в котором должно участвовать свойство [агрегатора](fd_key-concepts.html), необходимо использовать функцию [Exist](fo_exist-details.html). При указании свойств в условии для функции `Exist` необходимо явно указывать, что это свойство агрегатора: +Если необходимо задать условие на существование [детейлов](fd_key-concepts.html) по условию, в котором должно участвовать свойство [агрегатора](fd_key-concepts.html), необходимо использовать функцию [Exist](fo_exist-details.html). При указании свойств в условии для функции `Exist` необходимо явно указывать, что это свойство агрегатора: ``` <Имя агрегирующего свойства у детейла>.<Свойство агрегатора>. @@ -26,11 +26,11 @@ lang: ru View view2 = Information.GetView("SoftwareL", typeof(Software)); view.AddDetailInView("Software", view2, true); var lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Company), view); - ExternalLangDef langDef = ExternalLangDef.LanguageDef; + ExternalLangDef langDef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var detail = new DetailVariableDef(langDef.GetObjectType("Details"), "Software", view2, "Company"); lcs.LimitFunction = langDef.GetFunction(langDef.funcExist, detail, langDef.GetFunction(langDef.funcL, new VariableDef(langDef.DateTimeType, Information.ExtractPropertyPath(x => x.DateCreation)), new VariableDef(langDef.DateTimeType, Information.ExtractPropertyPath(x => x.Company.DateCreation)))); - var dos = DataServiceProvider.DataService.LoadObjects(lcs); + var dos = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` diff --git a/pages/products/flexberry-orm/query-language/fo_limit-function-serialization.en.md b/pages/products/flexberry-orm/query-language/fo_limit-function-serialization.en.md index 2bf18ed44..92b68e76c 100644 --- a/pages/products/flexberry-orm/query-language/fo_limit-function-serialization.en.md +++ b/pages/products/flexberry-orm/query-language/fo_limit-function-serialization.en.md @@ -38,7 +38,7 @@ private void Serialize(bool binary) DateTime start = DateTime.Now; string fnStr = ""; - ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; + ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). SQLWhereLanguageDef ldef = SQLWhereLanguageDef.LanguageDef; Function fn = ldef.GetFunction( ldef.funcAND, diff --git a/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.en.md b/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.en.md index 9facb6565..8e6a606de 100644 --- a/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.en.md +++ b/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.en.md @@ -15,7 +15,7 @@ Below are the main opportunities provided by [LINQProvider](fo_linq-provider.htm In the examples `ds` is the service data obtained in the following way: ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead ``` ## Supported diff --git a/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.ru.md b/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.ru.md index fcda414a5..cab37efb6 100644 --- a/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_linq-provider-faetures.ru.md @@ -13,7 +13,7 @@ lang: ru В примерах `ds` - это сервис данных, полученный следующим образом: ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. ``` ## Поддерживаемые типы @@ -64,13 +64,13 @@ List<Порода> objss = ds.Query<Порода>(Порода.Views.Пород ### Дата/Время -Для наложения ограничений на даты можно использовать различные свойства `DateTime`. +Для наложения ограничений на даты можно использовать различные свойства `DateTime`. -[Linq-провайдер](fo_linq-provider.html) не поддерживает метод `DateTime.AddDays`. При попытке ее использования будет брошено исключение `NotImplementedException`. +[Linq-провайдер](fo_linq-provider.html) не поддерживает метод `DateTime.AddDays`. При попытке ее использования будет брошено исключение `NotImplementedException`. Можно использовать числовые компоненты даты, такие как год, месяц, день в месяце, час минута, день недели. При этом дни недели преобразуются в числа как в C# в перечислении `DayOfWeek` (0 – воскресение, 1 – понедельник .. 6 – суббота). Для этого в [была добавлена функция DayOfWeekZeroBased в дополнение к старой DayOfWeek](fo_external-lang-def.html). -При попытке использования свойств Ticks, Second, Millisecond, DayOfYear будет брошено исключение `MethodSignatureException`. +При попытке использования свойств Ticks, Second, Millisecond, DayOfYear будет брошено исключение `MethodSignatureException`. **Выбрать переломы которые были раньше, чем сегодня:** @@ -159,13 +159,13 @@ ds.Query<Кошка>(Кошка.Views.КошкаE).Where(o => o.__PrimaryKey.Equ ### Мастера -Имеется возможность наложить ограничение на мастера, либо его атрибуты типа int, long, bool, string, DateTime. +Имеется возможность наложить ограничение на мастера, либо его атрибуты типа int, long, bool, string, DateTime. Например: ``` csharp Порода порода = ds.Query<Порода>(Порода.Views.ПородаE).First(); // Какой-нибудь объект типа порода Кошка кошка = ds.Query<Кошка>(Кошка.Views.КошкаE).FirstOrDefault(o => o.Порода == порода); //Получить первую кошку данной породы -Кошка кошка2 = ds.Query<Кошка>(Кошка.Views.КошкаE).FirstOrDefault(o => o.Порода.Название == "Дикая"); // Получить кошку по названию породы +Кошка кошка2 = ds.Query<Кошка>(Кошка.Views.КошкаE).FirstOrDefault(o => o.Порода.Название == "Дикая"); // Получить кошку по названию породы ``` При этом допускаются ограничения только на мастеров первого уровня. При попытке выполнить следующий код будет брошено исключение `MasterLevelException`. @@ -217,7 +217,7 @@ var личности = ds.Query<Личность>(Личность.Views.Чел var личности = ds.Query<Личность>(Личность.Views.ЧеловекL.Name).Where(l => l.Уволен); ``` -* Разумеется, условия можно комбинировать: +* Разумеется, условия можно комбинировать: ``` csharp var личности = ds.Query<Личность>(Личность.Views.ЧеловекL.Name).Where(l => l.Уволен && l.ДатаУвольнения > new DateTime(2012, 1, 1)); diff --git a/pages/products/flexberry-orm/query-language/fo_linq-provider.en.md b/pages/products/flexberry-orm/query-language/fo_linq-provider.en.md index c9b640979..5da642355 100644 --- a/pages/products/flexberry-orm/query-language/fo_linq-provider.en.md +++ b/pages/products/flexberry-orm/query-language/fo_linq-provider.en.md @@ -66,7 +66,7 @@ The method returns `IQueryable` that you can pass the query by using the methods using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // The data service. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead Кошка cat = ds.Query<Кошка>(Кошка.Views.КошкаE).First(o => o.Кличка.Contains("Osh")); // Get the object. Console.WriteLine(cat.Кличка); //Use. ``` @@ -77,7 +77,7 @@ Console.WriteLine(cat.Кличка); //Use. using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // The data service. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead Кошка cat = ds.Query<Кошка>(Кошка.Views.КошкаE).Where(o => o.Кличка.Contains("Osh")).Take(1).FirstOrDefault(); // Get the object. Console.WriteLine(cat.Кличка); //Use. ``` @@ -88,7 +88,7 @@ Console.WriteLine(cat.Кличка); //Use. using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // The data service. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Кошка> objs = ds.Query<Кошка>(Кошка.Views.КошкаE); IQueryable<Кошка> query = from o in objs where o.PrimaryKey == "6211E0DE-3E7A-4A68-866A-AB206A005B1C" select o; // Get the cats on a given key value. List<Кошка> data = query.ToList(); // Subtract data to the collection. @@ -98,7 +98,7 @@ Console.WriteLine(data[0).Кличка); // Use the received data. #### the Following code is equivalent to the previous ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; // The data service. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead IQueryable<Кошка> objs = ds.Query<Кошка>(Кошка.Views.КошкаE).Where(o => o.PrimaryKey == "6211E0DE-3E7A-4A68-866A-AB206A005B1C"); // Get the cats on a given key value. List<Кошка> data = objs.ToList(); // Subtract data to the collection. Console.WriteLine(data[0).Кличка); // Use the received data. diff --git a/pages/products/flexberry-orm/query-language/fo_linq-provider.ru.md b/pages/products/flexberry-orm/query-language/fo_linq-provider.ru.md index 942a99696..6d5862237 100644 --- a/pages/products/flexberry-orm/query-language/fo_linq-provider.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_linq-provider.ru.md @@ -64,7 +64,7 @@ public static IQueryable Query(this SQLDataService ds) where T : DataObjec using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // Cервис данных. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. Кошка cat = ds.Query<Кошка>(Кошка.Views.КошкаE).First(o => o.Кличка.Contains("ош")); // Получение объекта. Console.WriteLine(cat.Кличка); //Использование. ``` @@ -75,7 +75,7 @@ Console.WriteLine(cat.Кличка); //Использование. using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // Cервис данных. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. Кошка cat = ds.Query<Кошка>(Кошка.Views.КошкаE).Where(o => o.Кличка.Contains("ош")).Take(1).FirstOrDefault(); // Получение объекта. Console.WriteLine(cat.Кличка); //Использование. ``` @@ -86,8 +86,8 @@ Console.WriteLine(cat.Кличка); //Использование. using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.Business.LINQProvider; //... -var ds = (SQLDataService)DataServiceProvider.DataService; // Сервис данных. -IQueryable<Кошка> objs = ds.Query<Кошка>(Кошка.Views.КошкаE); +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. +IQueryable<Кошка> objs = ds.Query<Кошка>(Кошка.Views.КошкаE); IQueryable<Кошка> query = from o in objs where o.PrimaryKey == "6211E0DE-3E7A-4A68-866A-AB206A005B1C" select o; // Получить кошек по заданному значению ключа. List<Кошка> data = query.ToList(); // Вычитать данные в коллекцию. Console.WriteLine(data[0).Кличка); // Пользуемся полученными данными. @@ -96,7 +96,7 @@ Console.WriteLine(data[0).Кличка); // Пользуемся получен #### Следующий код эквивалентен предыдущему ``` csharp -var ds = (SQLDataService)DataServiceProvider.DataService; // Сервис данных. +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей. IQueryable<Кошка> objs = ds.Query<Кошка>(Кошка.Views.КошкаE).Where(o => o.PrimaryKey == "6211E0DE-3E7A-4A68-866A-AB206A005B1C"); // Получить кошек по заданному значению ключа. List<Кошка> data = objs.ToList(); // Вычитать данные в коллекцию. Console.WriteLine(data[0).Кличка); // Пользуемся полученными данными. diff --git a/pages/products/flexberry-orm/query-language/fo_load-limitation-example.en.md b/pages/products/flexberry-orm/query-language/fo_load-limitation-example.en.md index 0060211f0..47c78e075 100644 --- a/pages/products/flexberry-orm/query-language/fo_load-limitation-example.en.md +++ b/pages/products/flexberry-orm/query-language/fo_load-limitation-example.en.md @@ -54,6 +54,8 @@ ObjectStringDataView[] stringedview = DataServiceProvider.DataService.LoadString // 3. To obtain the number of objects without loading data. int iObjsCount = DataServiceProvider.DataService.GetObjectsCount(lcs); +// P.S. Starting from ORM v8.0 DataServiceProvider is deprecated; inject IDataService instead + stopwatch.Stop(); Console.WriteLine("Time taken for all loadings: {0} ms.", stopwatch.ElapsedMilliseconds); ``` diff --git a/pages/products/flexberry-orm/query-language/fo_load-limitation-example.ru.md b/pages/products/flexberry-orm/query-language/fo_load-limitation-example.ru.md index 3bb7eb61a..f3f389c66 100644 --- a/pages/products/flexberry-orm/query-language/fo_load-limitation-example.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_load-limitation-example.ru.md @@ -28,7 +28,7 @@ LoadingCustomizationStruct lcs = new LoadingCustomizationStruct(null); lcs.View = CD.Views.CD_E; lcs.LoadingTypes = new[] { typeof(CDDA), typeof(CDDD), typeof(DVD) }; -// Ограничение, использующие свойства классов, на которые ссылается класс CS. Могут быть использованы те свойства, +// Ограничение, использующие свойства классов, на которые ссылается класс CS. Могут быть использованы те свойства, // которые указаны в представлении, по которому производится загрузка объектов. lcs.LimitFunction = ld.GetFunction(ld.funcEQ, new VariableDef(ld.StringType, Information.ExtractPropertyPath(c => c.Publisher.Country.Name)), "USA"); @@ -45,13 +45,15 @@ stopwatch.Start(); // 1. Загрузить из БД записи и для каждой из них создать экземпляр объекта данных. ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); -// 2. Загрузить без создания экземпляров (каждый объект представлен в виде строки из значений свойств с разделителями). +// 2. Загрузить без создания экземпляров (каждый объект представлен в виде строки из значений свойств с разделителями). // Используется, когда не требуется редактирование объектов. Он намного быстрее! ObjectStringDataView[] stringedview = DataServiceProvider.DataService.LoadStringedObjectView(';', lcs); // 3. Получить количество объектов, без загрузки данных. int iObjsCount = DataServiceProvider.DataService.GetObjectsCount(lcs); +// P.S. С версии ORM 8.0 DataServiceProvider устарел; вместо него используйте внедрение зависимостей. + stopwatch.Stop(); Console.WriteLine("Time taken for all loadings: {0} ms.", stopwatch.ElapsedMilliseconds); ``` diff --git a/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.en.md b/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.en.md index eec975ff9..3be406095 100644 --- a/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.en.md +++ b/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.en.md @@ -23,7 +23,7 @@ You need to restrict clients by setting the limit to reference them loans. The s Let: ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead ``` Job restriction pseudometal a little less intuitive than the use of [other features LinqProvider](fo_linq-provider-faetures.html). diff --git a/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.ru.md b/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.ru.md index 991655e46..526ee9caa 100644 --- a/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_psedodetails-linq-provider.ru.md @@ -21,7 +21,7 @@ lang: ru Пусть: ```csharp -var ds = (SQLDataService)DataServiceProvider.DataService; +var ds = (SQLDataService)DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей ``` Задание ограничение на псевдодетейлы чуть менее интуитивно, чем использование [других возможностей LinqProvider](fo_linq-provider-faetures.html). @@ -169,7 +169,7 @@ ds.Query<Порода>(Порода.Views.ПородаE).Where( // Все породы, для которых определены кошки, у которых кличка не "Барсик" ds.Query<Порода>(Порода.Views.ПородаE) .Where( - y => + y => new PseudoDetail<Порода, Кошка>( Information.GetView("КошкаE", typeof(Кошка)), Information.ExtractPropertyPath<Кошка>(x => x.Порода)) @@ -183,7 +183,7 @@ ds.Query<Порода>(Порода.Views.ПородаE) // Все породы, где кошки не носят кличку "Барсик" ds.Query<Порода>(Порода.Views.ПородаE) .Where( - y => + y => new PseudoDetail<Порода, Кошка>( Information.GetView("КошкаE", typeof(Кошка)), Information.ExtractPropertyPath<Кошка>(x => x.Порода)) diff --git a/pages/products/flexberry-orm/query-language/fo_restriction-datetime.en.md b/pages/products/flexberry-orm/query-language/fo_restriction-datetime.en.md index 6b31c4b04..33364aaec 100644 --- a/pages/products/flexberry-orm/query-language/fo_restriction-datetime.en.md +++ b/pages/products/flexberry-orm/query-language/fo_restriction-datetime.en.md @@ -18,7 +18,7 @@ The function to retrieve parts of dates are available in [ExternalLangDef](fo_ex In the examples below we will use the following code: ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). var order = LoadingCustomizationStruct.GetSimpleStruct(typeof (Заказ), Заказ.Views.ЗаказL); ``` diff --git a/pages/products/flexberry-orm/query-language/fo_restriction-datetime.ru.md b/pages/products/flexberry-orm/query-language/fo_restriction-datetime.ru.md index 921a8b1eb..b5dcb6281 100644 --- a/pages/products/flexberry-orm/query-language/fo_restriction-datetime.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_restriction-datetime.ru.md @@ -16,7 +16,7 @@ lang: ru В примерах ниже будем использовать следующий код: ```csharp -var langdef = ExternalLangDef.LanguageDef; +var langdef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). var order = LoadingCustomizationStruct.GetSimpleStruct(typeof (Заказ), Заказ.Views.ЗаказL); ``` @@ -33,7 +33,7 @@ SELECT * FROM [dbo].[Заказ] WHERE YEAR([ДатаВыдачи]) = 2014 Через [ExternalLangDef](fo_external-lang-def.html) ```csharp -order.LimitFunction = langdef.GetFunction(langdef.funcEQ, +order.LimitFunction = langdef.GetFunction(langdef.funcEQ, langdef.GetFunction(langdef.funcYearPart, new VariableDef(langdef.DateTimeType, Information.ExtractPropertyPath<Заказ>(x => x.ДатаВыдачи))), "2014"); ``` @@ -116,16 +116,16 @@ order.LimitFunction = langdef.GetFunction(langdef.funcEQ, order.LimitFunction = langdef.GetFunction( langdef.funcAND, langdef.GetFunction( - langdef.funcEQ, + langdef.funcEQ, langdef.GetFunction( - langdef.funcHHPart, - new VariableDef(langdef.DateTimeType, Information.ExtractPropertyPath<Заказ>(x => x.ДатаВыдачи))), + langdef.funcHHPart, + new VariableDef(langdef.DateTimeType, Information.ExtractPropertyPath<Заказ>(x => x.ДатаВыдачи))), 10), langdef.GetFunction( - langdef.funcEQ, + langdef.funcEQ, langdef.GetFunction( - langdef.funcMIPart, - new VariableDef(langdef.DateTimeType, Information.ExtractPropertyPath<Заказ>(x => x.ДатаВыдачи))), + langdef.funcMIPart, + new VariableDef(langdef.DateTimeType, Information.ExtractPropertyPath<Заказ>(x => x.ДатаВыдачи))), 20)); ``` @@ -163,8 +163,8 @@ Function function = langDef.GetFunction(langDef.funcEQ, ```csharp // Создаем ограничение на объект. - lcs.LimitFunction = - // Ограничение, что функция возвращает объекты. + lcs.LimitFunction = + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (=) значению параметра 2. ldef.funcEQ, @@ -187,7 +187,7 @@ Function function = langDef.GetFunction(langDef.funcEQ, ```csharp // Создаем ограничение на объект. LimitFunction = - // Ограничение, что функция возвращает объекты. + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (=) значению параметра 2. ldef.funcEQ, @@ -213,7 +213,7 @@ LimitFunction = ```csharp // Создаем ограничение на объект. LimitFunction = - // Ограничение, что функция возвращает объекты. + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -236,10 +236,10 @@ LimitFunction = ```csharp // Создаем ограничение на объект ("Дата"<=paramTODAY). LimitFunction = - // Ограничение, что функция возвращает объекты. - ldef.GetFunction( + // Ограничение, что функция возвращает объекты. + ldef.GetFunction( // В которых значения параметра 1 (<=) значению параметра 2. - ldef.funcLEQ, + ldef.funcLEQ, // Параметр 1: Ограничение, что из поля "Дата", возвращаются только значения месяца. ldef.GetFunction(ldef.funcMonthPart, new VariableDef(ldef.DateTimeType, "Дата")), // Параметр 2: Ограничение, что из сегодняшней даты, возвращаются только значения месяца. @@ -252,8 +252,8 @@ LimitFunction = ```csharp // Создаем ограничение на объект. -lcs.LimitFunction = - // Ограничение, что функция возвращает объекты. +lcs.LimitFunction = + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -273,8 +273,8 @@ lcs.LimitFunction = ```csharp // Создаем ограничение на объект. -lcs.LimitFunction = - // Ограничение, что функция возвращает объекты. +lcs.LimitFunction = + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -294,8 +294,8 @@ lcs.LimitFunction = ```csharp // Создаем ограничение на объект. -lcs.LimitFunction = - // Ограничение, что функция возвращает объекты. +lcs.LimitFunction = + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -315,8 +315,8 @@ lcs.LimitFunction = ```csharp // Создаем ограничение на объект. -lcs.LimitFunction = - // Ограничение, что функция возвращает объекты. +lcs.LimitFunction = + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -337,7 +337,7 @@ lcs.LimitFunction = ```csharp // Создаем ограничение на объект. LimitFunction = - // Ограничение, что функция возвращает объекты. + // Ограничение, что функция возвращает объекты. ldef.GetFunction( // В которых значения параметра 1 (<) значению параметра 2. ldef.funcL, @@ -348,5 +348,5 @@ LimitFunction = 3, new VariableDef(ldef.DateTimeType, Information.ExtractPropertyPath(x => x.PoleDateTime))), // Параметр 2: Ограничение, что из сегодняшней даты, возвращаются только дату(без времени). - ldef.GetFunction(ldef.funcOnlyDate, DateTime.Now)); + ldef.GetFunction(ldef.funcOnlyDate, DateTime.Now)); ``` diff --git a/pages/products/flexberry-orm/query-language/fo_variable-def.en.md b/pages/products/flexberry-orm/query-language/fo_variable-def.en.md index 6dc2f0dd6..fed262684 100644 --- a/pages/products/flexberry-orm/query-language/fo_variable-def.en.md +++ b/pages/products/flexberry-orm/query-language/fo_variable-def.en.md @@ -1,145 +1,145 @@ ---- -title: description of the variables in the build functions limitations -sidebar: flexberry-orm_sidebar -keywords: Flexberry ORM Limitations -summary: examples of the use VariableDef and DetailVariableDef -toc: true -permalink: en/fo_variable-def.html -lang: en -autotranslated: true -hash: 23ea816cedb1e06d8904289e5b6fa1c1d66242fe69c16e688e757d4bc664e846 ---- +--- +title: description of the variables in the build functions limitations +sidebar: flexberry-orm_sidebar +keywords: Flexberry ORM Limitations +summary: examples of the use VariableDef and DetailVariableDef +toc: true +permalink: en/fo_variable-def.html +lang: en +autotranslated: true +hash: 23ea816cedb1e06d8904289e5b6fa1c1d66242fe69c16e688e757d4bc664e846 +--- -When constructing constraints using the method `GetFunction` argument to this method depending on the type of applied functions may be passed a description of the variable: +When constructing constraints using the method `GetFunction` argument to this method depending on the type of applied functions may be passed a description of the variable: -* when setting limits with [SQLWhereLanguageDef](fo_function-list.html) class is used `VariableDef`, -* when imposing restrictions on detail with [ExternalLangDef](fo_external-lang-def.html) to describe the variable-detail used class `DetailVariableDef`. +* when setting limits with [SQLWhereLanguageDef](fo_function-list.html) class is used `VariableDef`, +* when imposing restrictions on detail with [ExternalLangDef](fo_external-lang-def.html) to describe the variable-detail used class `DetailVariableDef`. -## VariableDef +## VariableDef -Class `VariableDef` is used to define the variable in the restriction (usually indicates an attribute [object](fo_data-object.html)). Used together with [SQLWhereLanguageDef](fo_function-list.html). +Class `VariableDef` is used to define the variable in the restriction (usually indicates an attribute [object](fo_data-object.html)). Used together with [SQLWhereLanguageDef](fo_function-list.html). -Defined in namespace: `ICSSoft.STORMNET.FunctionalLanguage`. +Defined in namespace: `ICSSoft.STORMNET.FunctionalLanguage`. -Build: `ICSSoft.STORMNET.FunctionalLanguage.dll`. +Build: `ICSSoft.STORMNET.FunctionalLanguage.dll`. -The most common constructor that is used when building constraints: +The most common constructor that is used when building constraints: ```csharp public VariableDef(ObjectType objType, string objStringedView) -``` +``` -He is passed the parameters: +He is passed the parameters: -* `objType` - ObjectType-the type of the variable (for example, `langdef.StringType`), -* `objStringedView` - the property name of the object on which the plan limitation. +* `objType` - ObjectType-the type of the variable (for example, `langdef.StringType`), +* `objStringedView` - the property name of the object on which the plan limitation. -Examples of design `VariableDef` when specifying constraints, see [SQLWhereLanguageDef](fo_function-list.html). +Examples of design `VariableDef` when specifying constraints, see [SQLWhereLanguageDef](fo_function-list.html). -### VariableDef to PrimaryKey +### VariableDef to PrimaryKey -When building restrictions on [primary keys](fo_primary-keys-objects.html) deducted objects (private keys) it is worth considering that [SQLWhereLanguageDef](fo_function-list.html) ignores constant `PrimaryKey`. Instead of a constant `PrimaryKey` better to use `StormMainObjectKey` (determined by the corresponding constant). +When building restrictions on [primary keys](fo_primary-keys-objects.html) deducted objects (private keys) it is worth considering that [SQLWhereLanguageDef](fo_function-list.html) ignores constant `PrimaryKey`. Instead of a constant `PrimaryKey` better to use `StormMainObjectKey` (determined by the corresponding constant). -__Wrong__: +__Wrong__: ```csharp var ld = SQLWhereLanguageDef.LanguageDef; ld.GetFunction(ld.funcEQ, new VariableDef(ld.GuidType, "PrimaryKey"), "64F45BC3-339B-4FBA-A036-C5E9FE9EAE53"); -``` +``` -__True__: +__True__: ```csharp var ld = SQLWhereLanguageDef.LanguageDef; ld.GetFunction(ld.funcEQ, new VariableDef(ld.GuidType, SQLWhereLanguageDef.StormMainObjectKey), "64F45BC3-339B-4FBA-A036-C5E9FE9EAE53"); -``` +``` -It should be noted that the restriction on [primary key](fo_primary-keys-objects.html) __masters__ is imposed as follows: +It should be noted that the restriction on [primary key](fo_primary-keys-objects.html) __masters__ is imposed as follows: ``` csharp var ld = SQLWhereLanguageDef.LanguageDef; ld.GetFunction(ld.funcEQ, new VariableDef(ld.GuidType, Information.ExtractPropertyPath<СамОбъект>(x => x.СсылкаНаМастера)), "84F456C1-312F-30C0-A238-11E3FE68E852"); -``` +``` -where "Silentmaster" - a reference to the master. +where "Silentmaster" - a reference to the master. -## DetailVariableDef +## DetailVariableDef -Class `DetailVariableDef` is used to determine the variable restrictions, to describe detailov. Used in conjunction with [ExternalLangDef](fo_external-lang-def.html). +Class `DetailVariableDef` is used to determine the variable restrictions, to describe detailov. Used in conjunction with [ExternalLangDef](fo_external-lang-def.html). -Defined in namespace: `ICSSoft.STORMNET.Windows.Forms`. -Build: `ExternalLangDef.dll`. +Defined in namespace: `ICSSoft.STORMNET.Windows.Forms`. +Build: `ICSSoft.STORMNET.Business.ExternalLangDef.dll`. -When designing `DetailVariableDef` specify the settings: +When designing `DetailVariableDef` specify the settings: -* `Type` - ObjectType-the type (you can get `ldef.GetObjectType("Details")`), -* `View` - the view name of detail, -* `ConnectMasterProp` - way from detail (see description below) -* `OwnerConnectProp` - detalu from the object (see the description later). +* `Type` - ObjectType-the type (you can get `ldef.GetObjectType("Details")`), +* `View` - the view name of detail, +* `ConnectMasterProp` - way from detail (see description below) +* `OwnerConnectProp` - detalu from the object (see the description later). -Examples of design `DetailVariableDef` when setting restrictions is available in the article: +Examples of design `DetailVariableDef` when setting restrictions is available in the article: -* [Restrictions on detali](fo_exist-details.html), -* [The limit on detaily using the properties of aggregator](fo_limit-details.html). +* [Restrictions on detali](fo_exist-details.html), +* [The limit on detaily using the properties of aggregator](fo_limit-details.html). -### Job OwnerConnectProp and ConnectMasterProp +### Job OwnerConnectProp and ConnectMasterProp -Problems often arise in determining what to specify as `ConnectMasterProp` and `OwnerConnectProp`. +Problems often arise in determining what to specify as `ConnectMasterProp` and `OwnerConnectProp`. -`ConnectMasterProp` specifies the path from detail and `OwnerConnectProp` - detalu from the object. +`ConnectMasterProp` specifies the path from detail and `OwnerConnectProp` - detalu from the object. -The bundle is as follows: **Detail.ConnectMasterProp = Object.OwnerConnectProp**. +The bundle is as follows: **Detail.ConnectMasterProp = Object.OwnerConnectProp**. -It is worth noting that the property `OwnerConnectProp` determines what objects are detaily. If the property is not specified (i.e., specified `null`), the conjunction occurs on the [primary key](fo_primary-keys-objects.html)(i.e. `StormMainObjectKey`). +It is worth noting that the property `OwnerConnectProp` determines what objects are detaily. If the property is not specified (i.e., specified `null`), the conjunction occurs on the [primary key](fo_primary-keys-objects.html)(i.e. `StormMainObjectKey`). -#### Examples of usage +#### Examples of usage -##### Example 1 +##### Example 1 -![](/images/pages/products/flexberry-orm/query-language/diagramm.JPG) +![](/images/pages/products/flexberry-orm/query-language/diagramm.JPG) -It is necessary to filter Odottamattomasti for Salenatural. -When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Person, `ConnectMasterProp` = Identity. +It is necessary to filter Odottamattomasti for Salenatural. +When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Person, `ConnectMasterProp` = Identity. -##### Example 2 +##### Example 2 -![](/images/pages/products/flexberry-orm/query language/diagramm-2.PNG) +![](/images/pages/products/flexberry-orm/query language/diagramm-2.PNG) -It is necessary to filter Obrazovatelnogo for Stroyrekonstruksiya. -When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Zaveniaghina.Personality `ConnectMasterProp` = Identity. +It is necessary to filter Obrazovatelnogo for Stroyrekonstruksiya. +When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Zaveniaghina.Personality `ConnectMasterProp` = Identity. -It is necessary to filter Obrazovatelnogo for Stroyrekonstruksiya. -When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Zaveniaghina.Personality `ConnectMasterProp` = Identity. +It is necessary to filter Obrazovatelnogo for Stroyrekonstruksiya. +When setting `DetailVariableDef` should specify: `OwnerConnectProp` = Zaveniaghina.Personality `ConnectMasterProp` = Identity. -### setting limits on pseudometal +### setting limits on pseudometal -For example, the entity "Customer" and "Credit" are connected shown in the image. +For example, the entity "Customer" and "Credit" are connected shown in the image. -![](/images/pages/products/flexberry-orm/query language/pseudo-details.png) +![](/images/pages/products/flexberry-orm/query language/pseudo-details.png) -You need to restrict clients by setting the limit to reference them loans. +You need to restrict clients by setting the limit to reference them loans. -It is obvious that from the point of view of storage of this object model in the database in accordance with [existing rules](fo_storing-data-objects.html), there is no distinction between aggregation and simple Association. However, restricting the sample according to the criteria of the child table do not differ in the case of aggregation and Association. Therefore to build restrictions in the case of pseudometal you must use `DetailVariableDef` together with [ExternalLangDef](fo_external-lang-def.html). +It is obvious that from the point of view of storage of this object model in the database in accordance with [existing rules](fo_storing-data-objects.html), there is no distinction between aggregation and simple Association. However, restricting the sample according to the criteria of the child table do not differ in the case of aggregation and Association. Therefore to build restrictions in the case of pseudometal you must use `DetailVariableDef` together with [ExternalLangDef](fo_external-lang-def.html). -If in the above example, it is necessary to select customers that have loans for more than 15 years, the code will look as follows: +If in the above example, it is necessary to select customers that have loans for more than 15 years, the code will look as follows: ``` csharp -ExternalLangDef ldef = ExternalLangDef.LanguageDef; +ExternalLangDef ldef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). LoadingCustomizationStruct lcsДолгосрочныеКлиенты = LoadingCustomizationStruct.GetSimpleStruct(typeof(Клиент), "Client"); -lcsДолгосрочныеКлиенты.LoadingTypes = new[) { typeof(Клиент) }; +lcsДолгосрочныеКлиенты.LoadingTypes = new[] { typeof(Клиент) }; var view = Information.GetView("Loan", typeof(Кредит)); var dvd = new DetailVariableDef { ConnectMasterPorp = "Client", - OwnerConnectProp = new[) { SQLWhereLanguageDef.StormMainObjectKey }, + OwnerConnectProp = new[] { SQLWhereLanguageDef.StormMainObjectKey }, View = view, Type = ldef.GetObjectType("Details") }; lcsДолгосрочныеКлиенты.LimitFunction = ldef.GetFunction(ldef.funcExist, dvd, - ldef.GetFunction(ldef.funcGEQ, + ldef.GetFunction(ldef.funcGEQ, new VariableDef(ldef.GuidType, "Loanyears"), 15)); -ICSSoft.STORMNET.DataObject[) dobjsДолгосрочныеКлиенты = DataServiceProvider.DataService.LoadObjects(lcsДолгосрочныеКлиенты); -``` +ICSSoft.STORMNET.DataObject[] dobjsДолгосрочныеКлиенты = DataServiceProvider.DataService.LoadObjects(lcsДолгосрочныеКлиенты); // DataServiceProvider is deprecated; inject IDataService instead +``` diff --git a/pages/products/flexberry-orm/query-language/fo_variable-def.ru.md b/pages/products/flexberry-orm/query-language/fo_variable-def.ru.md index bf78ea215..86223ba56 100644 --- a/pages/products/flexberry-orm/query-language/fo_variable-def.ru.md +++ b/pages/products/flexberry-orm/query-language/fo_variable-def.ru.md @@ -66,7 +66,7 @@ ld.GetFunction(ld.funcEQ, new VariableDef(ld.GuidType, Information.ExtractProper Класс `DetailVariableDef` служит для определения переменной ограничения, предназначенного для описания детейлов. Используется совместно с [ExternalLangDef](fo_external-lang-def.html). Определен в пространстве имен: `ICSSoft.STORMNET.Windows.Forms`. -Сборка: `ExternalLangDef.dll`. +Сборка: `ICSSoft.STORMNET.Business.ExternalLangDef.dll`. При конструировании `DetailVariableDef` следует задать параметры: @@ -84,7 +84,7 @@ ld.GetFunction(ld.funcEQ, new VariableDef(ld.GuidType, Information.ExtractProper Часто возникают сложности при определении, что указывать в качестве `ConnectMasterProp` и `OwnerConnectProp`. -`ConnectMasterProp` указывается путь от детейла, а в `OwnerConnectProp` - к детейлу от объекта. +`ConnectMasterProp` указывается путь от детейла, а в `OwnerConnectProp` - к детейлу от объекта. Связка происходит следующим образом: **Детейл.ConnectMasterProp = Объект.OwnerConnectProp**. @@ -96,17 +96,17 @@ Cтоит отметить, что свойство `OwnerConnectProp` опре ![](/images/pages/products/flexberry-orm/query-language/diagramm.JPG) -Необходимо отфильтровать УдостоверяющиеДокументы для ЗаявленияАбитуриента. +Необходимо отфильтровать УдостоверяющиеДокументы для ЗаявленияАбитуриента. При задании `DetailVariableDef` следует указать: `OwnerConnectProp` = Личность, `ConnectMasterProp` = Личность. ##### Пример2 ![](/images/pages/products/flexberry-orm/query-language/diagramm-2.PNG) -Необходимо отфильтровать ОбразовательныеДокументы для СтрокиРекомендательногоСписка. +Необходимо отфильтровать ОбразовательныеДокументы для СтрокиРекомендательногоСписка. При задании `DetailVariableDef` следует указать: `OwnerConnectProp` = ЗаявлениеАбитуриента.Личность, `ConnectMasterProp` = Личность. -Необходимо отфильтровать ОбразовательныеДокументы для СтрокиРекомендательногоСписка. +Необходимо отфильтровать ОбразовательныеДокументы для СтрокиРекомендательногоСписка. При задании `DetailVariableDef` следует указать: `OwnerConnectProp` = ЗаявлениеАбитуриента.Личность, `ConnectMasterProp` = Личность. ### Задание ограничений на псевдодетейлы @@ -116,25 +116,25 @@ Cтоит отметить, что свойство `OwnerConnectProp` опре ![](/images/pages/products/flexberry-orm/query-language/pseudo-details.png) Нужно ограничить клиентов, задав при этом ограничение на ссылающихся на них кредиты. - -Очевидно, что с точки зрения хранения данной объектной модели в БД в соответствии с [существующими правилами](fo_storing-data-objects.html), нет различия между агрегацией и простой ассоциацией. Поэтому запросы, ограничивающие выборку по критериям из дочерней таблицы, не отличаются в случае агрегации и ассоциации. Следовательно для построения ограничения в случае всевдодетейла необходимо использовать `DetailVariableDef` совместно с [ExternalLangDef](fo_external-lang-def.html). - + +Очевидно, что с точки зрения хранения данной объектной модели в БД в соответствии с [существующими правилами](fo_storing-data-objects.html), нет различия между агрегацией и простой ассоциацией. Поэтому запросы, ограничивающие выборку по критериям из дочерней таблицы, не отличаются в случае агрегации и ассоциации. Следовательно для построения ограничения в случае всевдодетейла необходимо использовать `DetailVariableDef` совместно с [ExternalLangDef](fo_external-lang-def.html). + Если в описанном примере надо выбрать клиентов, у которых есть кредиты на срок более 15 лет, код будет выглядеть следующим образом: ``` csharp -ExternalLangDef ldef = ExternalLangDef.LanguageDef; +ExternalLangDef ldef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). LoadingCustomizationStruct lcsДолгосрочныеКлиенты = LoadingCustomizationStruct.GetSimpleStruct(typeof(Клиент), "КлиентE"); -lcsДолгосрочныеКлиенты.LoadingTypes = new[) { typeof(Клиент) }; +lcsДолгосрочныеКлиенты.LoadingTypes = new[] { typeof(Клиент) }; var view = Information.GetView("КредитE", typeof(Кредит)); var dvd = new DetailVariableDef { ConnectMasterPorp = "Клиент", - OwnerConnectProp = new[) { SQLWhereLanguageDef.StormMainObjectKey }, + OwnerConnectProp = new[] { SQLWhereLanguageDef.StormMainObjectKey }, View = view, Type = ldef.GetObjectType("Details") }; lcsДолгосрочныеКлиенты.LimitFunction = ldef.GetFunction(ldef.funcExist, dvd, - ldef.GetFunction(ldef.funcGEQ, + ldef.GetFunction(ldef.funcGEQ, new VariableDef(ldef.GuidType, "СрокКредита"), 15)); -ICSSoft.STORMNET.DataObject[) dobjsДолгосрочныеКлиенты = DataServiceProvider.DataService.LoadObjects(lcsДолгосрочныеКлиенты); +ICSSoft.STORMNET.DataObject[] dobjsДолгосрочныеКлиенты = DataServiceProvider.DataService.LoadObjects(lcsДолгосрочныеКлиенты); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей ``` diff --git a/pages/products/flexberry-platform/fp_flexberry-nuget-packages.en.md b/pages/products/flexberry-platform/fp_flexberry-nuget-packages.en.md index 188436d70..ebae98da2 100644 --- a/pages/products/flexberry-platform/fp_flexberry-nuget-packages.en.md +++ b/pages/products/flexberry-platform/fp_flexberry-nuget-packages.en.md @@ -145,7 +145,7 @@ The package contains the components [of the service of the current user](fo_curr Assemblies included in this package: -* ICSSoft.Services.CurrentUserService.dll +* NewPlatform.Flexberry.ORM.CurrentUserService.dll ## Flexberry UserSettingsService @@ -153,13 +153,13 @@ Assemblies included in this package: * UserSettingsService.dll -## Flexberry UnityFactor +## Flexberry UnityFactory The package contains the components [UnityFactory](fo_unity-factory.html). Assemblies included in this package: -* ICSSoft.Services.UnityFactory.dll +* NewPlatform.Flexberry.ORM.UnityFactory.dll ## Flexberry ServiceBus diff --git a/pages/products/flexberry-platform/fp_flexberry-nuget-packages.ru.md b/pages/products/flexberry-platform/fp_flexberry-nuget-packages.ru.md index e95948e3f..11ff74d6e 100644 --- a/pages/products/flexberry-platform/fp_flexberry-nuget-packages.ru.md +++ b/pages/products/flexberry-platform/fp_flexberry-nuget-packages.ru.md @@ -1,176 +1,176 @@ ---- -title: NuGet-пакеты Flexberry -sidebar: flexberry-platform_sidebar -keywords: NuGet, библиотеки, продукты -summary: Перечень библиотек и их зависимостей для продуктов платформы Flexberry -toc: true -permalink: ru/flexberry-nuget-packages.html -lang: ru ---- - -Отдельные компоненты технологии проектирования и программирования Flexberry распространяются через пакетный менеджер [NuGet](https://nuget.org). - -Часть пакетов располагается в открытом публичном доступе в галерее [NuGet.org](https://www.nuget.org/packages?q=Flexberry). - -Для ведения версий пакетов применяется принцип [семантического версионирования](http://semver.org/lang/ru/). - -## Flexberry ORM - -Пакет содержит компоненты для объектно-реляционного отображения. - -Сборки, входящие в пакет описаны в статье [Библиотеки Flexberry ORM](fo_flexberry-orm-libraries.html). - -### Пакеты для ODataService - -* Flexberry ORM ODataService - пакет содержит компоненты для создания OData-сервиса. - -Сборки, входящие в пакет описаны в статье [Flexberry ORM ODataService](fo_orm-odata-service.html). - -* Flexberry ORM MongoDbDataService - -### Пакеты для настройки взаимодействия Flexberry ORM и Flexberry GIS - -* Flexberry ORM GisMSSQLDataService -* Flexberry ORM GisPostgresDataService - -## Flexberry ASP.NET - -Сборки, входящие в пакет [Flexberry ASP.NET](fa_flexberry-asp-net.html): - -* CacheBaseLibrary.dll -* ClientLibrary.dll -* CustomSiteMapProvider.dll -* ExpressionBuilder.dll -* HttpCompress.dll -* ICSSoft.STORMNET.Business.BFDataService.dll -* ICSSoft.STORMNET.Business.HttpDataService.dll -* ICSSoft.STORMNET.EBSI.dll -* ICSSoft.STORMNET.LockServices.dll -* ICSSoft.STORMNET.Web.AjaxControls.dll -* ICSSoft.STORMNET.Web.Tools.dll -* IIS.ExpressionSerialization.dll -* IIS.Flex.CaseberryInteraction.dll -* IIS.Validation.dll -* IIS.Аудит(Objects).dll -* ImageResizerKernel.dll -* NewPlatform.Flexberry.Web.Http.dll -* NewPlatform.Flexberry.Web.LimitEditor.dll -* OfficeWebUI.dll -* SmartScroller.dll - -### Пакеты для настройки стилей приложений - -* Flexberry ASP.NET BaseTheme -* Flexberry ASP.NET SpringTheme -* Flexberry ASP.NET SmartTheme -* Flexberry ASP.NET DefaultTheme -* Flexberry ASP.NET LightTheme -* Flexberry ASP.NET BlueSkyTheme - -### Flexberry ASP.NET WebApi Cors - -## Flexberry Winforms - -Пакет содержит компоненты фреймворка Flexberry Winforms: WinForms-контролы и основные типы, необходимые для работы генерируемых WinForms-приложений. - -Сборки, входящие в пакет: - -* AdmConsole(Objects).dll -* ICSSoft.STORMNET.BusinessTaskMonitor.dll -* ICSSoft.STORMNET.Deployment.dll -* ICSSoft.STORMNET.EBSI.dll -* ICSSoft.STORMNET.FileType.dll -* ICSSoft.STORMNET.UI.dll -* ICSSoft.STORMNET.Windows.Forms.dll -* ICSSoft.STORMNET.Windows.Forms.AdditionalControls.dll -* ICSSoft.STORMNET.Windows.Forms.MaskEditControl.dll -* ICSSoft.STORMNET.Windows.Forms.XmlViewer.dll -* Repository.dll -* C1.Common.dll -* C1.Win.C1FlexGrid.dll -* ActiveReports.dll -* ActiveReports.Viewer.dll -* MagicLocalLibrary.dll - -## Flexberry Security - -Пакет содержит компоненты [подсистемы полномочий](efs_security.html). - -Сборки, входящие в пакет: - -* CheckingLibrary.dll -* ICSSoft.STORMNET.AzManBridge.dll -* ICSSoft.STORMNET.RightManager.dll -* Security(BusinessServers).dll -* Security(Objects).dll -* NewPlatform.Flexberry.Security.dll -* Interop.ActiveDs.dll -* Microsoft.Interop.Security.AzRoles.dll - -## Flexberry Audit - -Пакет содержит компоненты [подсистемы аудита](fa_audit-web.html). - -Сборки, входящие в пакет: - -* ICSSoft.STORMNET.Business.Audit.dll - -## Flexberry LogService - -Пакет содержит компоненты [сервиса логирования событий](fo_log-service-log4net.html) (этот пакет также определяет используемую версию сборки log4net). - -Сборки, входящие в пакет: - -* LogService.dll - -### Flexberry LogService Objects - -Сборки, входящие в пакет: - -* IIS.Flexberry.Logging(BusinessServers).dll -* IIS.Flexberry.Logging(Objects).dll -* IIS.Flexberry.Logging.MsEntLib.dll - -### Flexberry LogService Winforms - -Сборки, входящие в пакет: - -* IIS.Flexberry.Logging(Forms).dll - -## Flexberry CurrentUserService - -Пакет содержит компоненты [сервиса текущего пользователя](fo_current-user-service.html). - -Сборки, входящие в пакет: - -* ICSSoft.Services.CurrentUserService.dll - -## Flexberry UserSettingsService - -Сборки, входящие в пакет: - -* UserSettingsService.dll - -## Flexberry UnityFactor - -Пакет содержит компоненты [UnityFactory](fo_unity-factory.html). - -Сборки, входящие в пакет: - -* ICSSoft.Services.UnityFactory.dll - -## Flexberry ServiceBus - -### Дополнительные пакеты для Flexberry ServiceBus - -* Flexberry ServiceBus Objects -* Flexberry ServiceBus ClientTools -* Flexberry ServiceBus Components -* Flexberry ServiceBus RabbitMQ - -## Дополнительно - -* Flexberry GIS Objects -* Flexberry Caching -* Flexberry Reports ExportToExcel -* Flexberry EasyNetQ Management Client +--- +title: NuGet-пакеты Flexberry +sidebar: flexberry-platform_sidebar +keywords: NuGet, библиотеки, продукты +summary: Перечень библиотек и их зависимостей для продуктов платформы Flexberry +toc: true +permalink: ru/flexberry-nuget-packages.html +lang: ru +--- + +Отдельные компоненты технологии проектирования и программирования Flexberry распространяются через пакетный менеджер [NuGet](https://nuget.org). + +Часть пакетов располагается в открытом публичном доступе в галерее [NuGet.org](https://www.nuget.org/packages?q=Flexberry). + +Для ведения версий пакетов применяется принцип [семантического версионирования](http://semver.org/lang/ru/). + +## Flexberry ORM + +Пакет содержит компоненты для объектно-реляционного отображения. + +Сборки, входящие в пакет описаны в статье [Библиотеки Flexberry ORM](fo_flexberry-orm-libraries.html). + +### Пакеты для ODataService + +* Flexberry ORM ODataService - пакет содержит компоненты для создания OData-сервиса. + +Сборки, входящие в пакет описаны в статье [Flexberry ORM ODataService](fo_orm-odata-service.html). + +* Flexberry ORM MongoDbDataService + +### Пакеты для настройки взаимодействия Flexberry ORM и Flexberry GIS + +* Flexberry ORM GisMSSQLDataService +* Flexberry ORM GisPostgresDataService + +## Flexberry ASP.NET + +Сборки, входящие в пакет [Flexberry ASP.NET](fa_flexberry-asp-net.html): + +* CacheBaseLibrary.dll +* ClientLibrary.dll +* CustomSiteMapProvider.dll +* ExpressionBuilder.dll +* HttpCompress.dll +* ICSSoft.STORMNET.Business.BFDataService.dll +* ICSSoft.STORMNET.Business.HttpDataService.dll +* ICSSoft.STORMNET.EBSI.dll +* ICSSoft.STORMNET.LockServices.dll +* ICSSoft.STORMNET.Web.AjaxControls.dll +* ICSSoft.STORMNET.Web.Tools.dll +* IIS.ExpressionSerialization.dll +* IIS.Flex.CaseberryInteraction.dll +* IIS.Validation.dll +* IIS.Аудит(Objects).dll +* ImageResizerKernel.dll +* NewPlatform.Flexberry.Web.Http.dll +* NewPlatform.Flexberry.Web.LimitEditor.dll +* OfficeWebUI.dll +* SmartScroller.dll + +### Пакеты для настройки стилей приложений + +* Flexberry ASP.NET BaseTheme +* Flexberry ASP.NET SpringTheme +* Flexberry ASP.NET SmartTheme +* Flexberry ASP.NET DefaultTheme +* Flexberry ASP.NET LightTheme +* Flexberry ASP.NET BlueSkyTheme + +### Flexberry ASP.NET WebApi Cors + +## Flexberry Winforms + +Пакет содержит компоненты фреймворка Flexberry Winforms: WinForms-контролы и основные типы, необходимые для работы генерируемых WinForms-приложений. + +Сборки, входящие в пакет: + +* AdmConsole(Objects).dll +* ICSSoft.STORMNET.BusinessTaskMonitor.dll +* ICSSoft.STORMNET.Deployment.dll +* ICSSoft.STORMNET.EBSI.dll +* ICSSoft.STORMNET.FileType.dll +* ICSSoft.STORMNET.UI.dll +* ICSSoft.STORMNET.Windows.Forms.dll +* ICSSoft.STORMNET.Windows.Forms.AdditionalControls.dll +* ICSSoft.STORMNET.Windows.Forms.MaskEditControl.dll +* ICSSoft.STORMNET.Windows.Forms.XmlViewer.dll +* Repository.dll +* C1.Common.dll +* C1.Win.C1FlexGrid.dll +* ActiveReports.dll +* ActiveReports.Viewer.dll +* MagicLocalLibrary.dll + +## Flexberry Security + +Пакет содержит компоненты [подсистемы полномочий](efs_security.html). + +Сборки, входящие в пакет: + +* CheckingLibrary.dll +* ICSSoft.STORMNET.AzManBridge.dll +* ICSSoft.STORMNET.RightManager.dll +* Security(BusinessServers).dll +* Security(Objects).dll +* NewPlatform.Flexberry.Security.dll +* Interop.ActiveDs.dll +* Microsoft.Interop.Security.AzRoles.dll + +## Flexberry Audit + +Пакет содержит компоненты [подсистемы аудита](fa_audit-web.html). + +Сборки, входящие в пакет: + +* ICSSoft.STORMNET.Business.Audit.dll + +## Flexberry LogService + +Пакет содержит компоненты [сервиса логирования событий](fo_log-service-log4net.html) (этот пакет также определяет используемую версию сборки log4net). + +Сборки, входящие в пакет: + +* LogService.dll + +### Flexberry LogService Objects + +Сборки, входящие в пакет: + +* IIS.Flexberry.Logging(BusinessServers).dll +* IIS.Flexberry.Logging(Objects).dll +* IIS.Flexberry.Logging.MsEntLib.dll + +### Flexberry LogService Winforms + +Сборки, входящие в пакет: + +* IIS.Flexberry.Logging(Forms).dll + +## Flexberry CurrentUserService + +Пакет содержит компоненты [сервиса текущего пользователя](fo_current-user-service.html). + +Сборки, входящие в пакет: + +* NewPlatform.Flexberry.ORM.CurrentUserService.dll + +## Flexberry UserSettingsService + +Сборки, входящие в пакет: + +* UserSettingsService.dll + +## Flexberry UnityFactor + +Пакет содержит компоненты [UnityFactory](fo_unity-factory.html). + +Сборки, входящие в пакет: + +* NewPlatform.Flexberry.ORM.UnityFactory.dll + +## Flexberry ServiceBus + +### Дополнительные пакеты для Flexberry ServiceBus + +* Flexberry ServiceBus Objects +* Flexberry ServiceBus ClientTools +* Flexberry ServiceBus Components +* Flexberry ServiceBus RabbitMQ + +## Дополнительно + +* Flexberry GIS Objects +* Flexberry Caching +* Flexberry Reports ExportToExcel +* Flexberry EasyNetQ Management Client diff --git a/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.en.md b/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.en.md index 7db8d2c6d..a42dabd9f 100644 --- a/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.en.md +++ b/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.en.md @@ -112,7 +112,7 @@ public class C__ПокупкаE : ICSSoft.STORMNET.UI.BaseIndpdEdit if ((dobject.GetStatus(false) != ICSSoft.STORMNET.ObjectStatus.Created) || dobject.Prototyped) { - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(m_objView, dobject, false, false); + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(m_objView, dobject, false, false); // DataServiceProvider is deprecated; inject IDataService instead dobject.InitDataCopy(); } // *** Start programmer edit section *** (PrepareDataObjectForEdit (DataObject) end) @@ -134,7 +134,7 @@ ICSSoft.STORMNET.View дочитать_View = m_objView - ge_View; //if it has been opened before foreach (string altprop in dobject.GetAlteredPropertyNames()) дочитать_View.RemoveProperty(altprop); -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(дочитать_View, dobject, false, false); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(дочитать_View, dobject, false, false); // DataServiceProvider is deprecated; inject IDataService instead return; ``` diff --git a/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.ru.md b/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.ru.md index 2fcdeec46..193f7080b 100644 --- a/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.ru.md +++ b/pages/products/flexberry-winforms/controls/groupedit/fw_ge-editor-ext.ru.md @@ -1,139 +1,139 @@ ---- -title: Редактирование детейлов на отдельной форме -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, Controls, GroupEdit, GEEditorExt -summary: Правила подключения компонента для редактирования детейлов на отдельной форме -toc: true -permalink: ru/fw_ge-editor-ext.html -lang: ru ---- - -`GEEditorExt` - расширение компонента [GroupEdit](fw_group-edit.html), позволяющее организовать следующее поведение: - -1. На панель инструментов `GroupEdit` добавляются кнопки "Создать" и "Открыть" -2. При нажатии на кнопку "Открыть" поднимается форма редактирования, соответствующая типу объекта в `GroupEdit`. При поднятии формы данные, введённые в `GroupEdit`, отражаются на форме. -3. При нажатии на "Создать" поднимается форма редактирования детейла, соответствующая типу объекта в `GroupEdit`, при сохранении которого создаётся строчка в `GroupEdit`. -4. При сохранении детейла на форме редактирования не происходит запись в БД - детейл запишется в БД вместе со своим мастером при его сохранении. -5. В случае, когда объект открыт на форме редактирования, запрещено его редактировать в `GroupEdit`(выдаётся предупреждение и выводится на передний план форма редактирования). Для согласованности отображения в `GroupEdit` изменённых на форме данных синхронизируется отображение данных при выходе с формы редактирования и при ее активации. - -{% include important.html content="GEEditorExt не входит в стандартную поставку Flexberry Winforms." %} - -## Как подключить GEEditorExt - -Подключение `GEEditorExt` рассмотрено на примере: "Покупатель" - это [класс мастера](fd_key-concepts.html), "Покупка" - [класс детейла](fd_key-concepts.html). - -![Пример диаграммы](/images/pages/products/flexberry-winforms/controls/groupedit/class-diagram_-customer-purchase2.jpg) - -{% include note.html content="Для редактирования детейлов необходимо сгенерировать соответствующую форму редактирования (при быстрой прототипизации она не создаётся)." %} - -1.В классе формы агрегатора объявляется переменную типа `GEEditorExt`: - -```csharp -public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE -{ - IIS.AMS02.GEEditorExt extGEПокупки; - //... -} -``` - -2.В метод `Edit` формы агрегатора добавляется код по инициализации данной переменной. Конструктору класса `GEEditorExt` в качестве параметра передается [`GroupEdit`](fw_group-edit.html), функциональность которого планируется расширить. - -```csharp -public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE -{ - IIS.AMS02.GEEditorExt extGEПокупки; - public override void Edit(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname, object tag) - { - //... - #region возможность создания и редактирования реагирований на отдельной формы из GE - if (this.extGEПокупки == null) - this.extGEПокупки = new IIS.AMS02.GEEditorExt(Покупки); - #endregion возможность создания и редактирования реагирований на отдельной формы из GE - //... - } - //... -} -``` - -{% include note.html content="Вместо пунктов 1 и 2, если не надо совершать дополнительных действий с кнопками (скрывать их, переименовывать и т.п.) можно использовать метод-расширение у GroupEdit." %} - -3.В метод `GetEditor` формы агрегатора добавляется код, указывающий, какую форму поднимать для редактирования конкретного детейла: - -```csharp -public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE -{ - public override Type GetEditor(ICSSoft.STORMNET.UI.EventType eventtype, ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) - { - if ((propertyname == "Покупка")) - { - return System.Type.GetType("IIS.MasterField.C__ПокупкаE"); - } - //... - } - //... -} -``` - -4.Переопределить метод `PromtUserForActionAtClose` формы детейла (это связанно с особенностью 1 класса `GEEditorExt`): - -```csharp -public class WinformC__ПокупкаE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупкаE -{ - public override ICSSoft.STORMNET.UI.DialogResult PromtUserForActionAtClose() - { - if (EditManager.DataObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Created && - EditManager.DataObject.DynamicProperties.ContainsKey("Псевдосохранен") || - EditManager.DataObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.UnAltered && - EditManager.DataObject.GetAlteredPropertyNames().Length == 0) - return ICSSoft.STORMNET.UI.DialogResult.Yes; - return base.PromtUserForActionAtClose(); - } - //... -} -``` - -5.В независимой форме детейла переопределить метод вычитки из БД (для того, чтобы не вычитывался полностью объект при поднятии формы редактирования): - -```csharp -public class C__ПокупкаE : ICSSoft.STORMNET.UI.BaseIndpdEdit -{ - protected override void PrepareDataObjectForEdit(ICSSoft.STORMNET.DataObject dobject) - { - // *** Start programmer edit section *** (PrepareDataObjectForEdit (DataObject) start) - if (dobject.GetStatus(false) == ICSSoft.STORMNET.ObjectStatus.Altered) - { - m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); - return; - } - // *** End programmer edit section *** (PrepareDataObjectForEdit (DataObject) start) - m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); - if ((dobject.GetStatus(false) != ICSSoft.STORMNET.ObjectStatus.Created) - || dobject.Prototyped) - { - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(m_objView, dobject, false, false); - dobject.InitDataCopy(); - } - // *** Start programmer edit section *** (PrepareDataObjectForEdit (DataObject) end) - - // *** End programmer edit section *** (PrepareDataObjectForEdit (DataObject) end) - } - //... -} -``` - -Здесь предполагается, что представления для отображения детейла на форме редактирования и в [GroupEdit](fw_group-edit.html) совпадают (т.е. это одно и то же представление или представления с одинаковым набором атрибутов). Если представления разные, то код в скобках программиста в приведенном выше методе `PrepareDataObjectForEdit` надо заменить на такой: - -```csharp -m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); -ICSSoft.STORMNET.View ge_View = ICSSoft.STORMNET.Information.GetView("C__ПокупкаD", typeof(IIS.MasterField.Покупка)); -//дочитываем то, что есть на форме редактирования, но нет в GE -ICSSoft.STORMNET.View дочитать_View = m_objView - ge_View; -//из этого представления убираем свойства, которые могли быть изменены на форме редактирования, -//если она открывалась ранее -foreach (string altprop in dobject.GetAlteredPropertyNames()) - дочитать_View.RemoveProperty(altprop); -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(дочитать_View, dobject, false, false); -return; -``` - -Однако в данном случае (в случае разных представлений) проявится особенность: если открыть мастер, ничего на нем не менять, открыть детейл на редактирование и сразу закрыть форму, то она закроется без вопроса о сохранении, а форма мастера спросит о сохранении. Это связано с тем, что после вычитывания дополнительных свойств детейла его набор атрибутов в копии мастера будет отличаться от набора в самом мастере. Избавиться от этого можно ручным исправлением копии мастера перед открытием формы редактирования детейла. +--- +title: Редактирование детейлов на отдельной форме +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, Controls, GroupEdit, GEEditorExt +summary: Правила подключения компонента для редактирования детейлов на отдельной форме +toc: true +permalink: ru/fw_ge-editor-ext.html +lang: ru +--- + +`GEEditorExt` - расширение компонента [GroupEdit](fw_group-edit.html), позволяющее организовать следующее поведение: + +1. На панель инструментов `GroupEdit` добавляются кнопки "Создать" и "Открыть" +2. При нажатии на кнопку "Открыть" поднимается форма редактирования, соответствующая типу объекта в `GroupEdit`. При поднятии формы данные, введённые в `GroupEdit`, отражаются на форме. +3. При нажатии на "Создать" поднимается форма редактирования детейла, соответствующая типу объекта в `GroupEdit`, при сохранении которого создаётся строчка в `GroupEdit`. +4. При сохранении детейла на форме редактирования не происходит запись в БД - детейл запишется в БД вместе со своим мастером при его сохранении. +5. В случае, когда объект открыт на форме редактирования, запрещено его редактировать в `GroupEdit`(выдаётся предупреждение и выводится на передний план форма редактирования). Для согласованности отображения в `GroupEdit` изменённых на форме данных синхронизируется отображение данных при выходе с формы редактирования и при ее активации. + +{% include important.html content="GEEditorExt не входит в стандартную поставку Flexberry Winforms." %} + +## Как подключить GEEditorExt + +Подключение `GEEditorExt` рассмотрено на примере: "Покупатель" - это [класс мастера](fd_key-concepts.html), "Покупка" - [класс детейла](fd_key-concepts.html). + +![Пример диаграммы](/images/pages/products/flexberry-winforms/controls/groupedit/class-diagram_-customer-purchase2.jpg) + +{% include note.html content="Для редактирования детейлов необходимо сгенерировать соответствующую форму редактирования (при быстрой прототипизации она не создаётся)." %} + +1.В классе формы агрегатора объявляется переменную типа `GEEditorExt`: + +```csharp +public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE +{ + IIS.AMS02.GEEditorExt extGEПокупки; + //... +} +``` + +2.В метод `Edit` формы агрегатора добавляется код по инициализации данной переменной. Конструктору класса `GEEditorExt` в качестве параметра передается [`GroupEdit`](fw_group-edit.html), функциональность которого планируется расширить. + +```csharp +public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE +{ + IIS.AMS02.GEEditorExt extGEПокупки; + public override void Edit(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname, object tag) + { + //... + #region возможность создания и редактирования реагирований на отдельной формы из GE + if (this.extGEПокупки == null) + this.extGEПокупки = new IIS.AMS02.GEEditorExt(Покупки); + #endregion возможность создания и редактирования реагирований на отдельной формы из GE + //... + } + //... +} +``` + +{% include note.html content="Вместо пунктов 1 и 2, если не надо совершать дополнительных действий с кнопками (скрывать их, переименовывать и т.п.) можно использовать метод-расширение у GroupEdit." %} + +3.В метод `GetEditor` формы агрегатора добавляется код, указывающий, какую форму поднимать для редактирования конкретного детейла: + +```csharp +public class WinformC__ПокупательE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупательE +{ + public override Type GetEditor(ICSSoft.STORMNET.UI.EventType eventtype, ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) + { + if ((propertyname == "Покупка")) + { + return System.Type.GetType("IIS.MasterField.C__ПокупкаE"); + } + //... + } + //... +} +``` + +4.Переопределить метод `PromtUserForActionAtClose` формы детейла (это связанно с особенностью 1 класса `GEEditorExt`): + +```csharp +public class WinformC__ПокупкаE : ICSSoft.STORMNET.UI.BaseWinEdit, IIS.MasterField.DPDIC__ПокупкаE +{ + public override ICSSoft.STORMNET.UI.DialogResult PromtUserForActionAtClose() + { + if (EditManager.DataObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Created && + EditManager.DataObject.DynamicProperties.ContainsKey("Псевдосохранен") || + EditManager.DataObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.UnAltered && + EditManager.DataObject.GetAlteredPropertyNames().Length == 0) + return ICSSoft.STORMNET.UI.DialogResult.Yes; + return base.PromtUserForActionAtClose(); + } + //... +} +``` + +5.В независимой форме детейла переопределить метод вычитки из БД (для того, чтобы не вычитывался полностью объект при поднятии формы редактирования): + +```csharp +public class C__ПокупкаE : ICSSoft.STORMNET.UI.BaseIndpdEdit +{ + protected override void PrepareDataObjectForEdit(ICSSoft.STORMNET.DataObject dobject) + { + // *** Start programmer edit section *** (PrepareDataObjectForEdit (DataObject) start) + if (dobject.GetStatus(false) == ICSSoft.STORMNET.ObjectStatus.Altered) + { + m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); + return; + } + // *** End programmer edit section *** (PrepareDataObjectForEdit (DataObject) start) + m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); + if ((dobject.GetStatus(false) != ICSSoft.STORMNET.ObjectStatus.Created) + || dobject.Prototyped) + { + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(m_objView, dobject, false, false); + dobject.InitDataCopy(); + } + // *** Start programmer edit section *** (PrepareDataObjectForEdit (DataObject) end) + + // *** End programmer edit section *** (PrepareDataObjectForEdit (DataObject) end) + } + //... +} +``` + +Здесь предполагается, что представления для отображения детейла на форме редактирования и в [GroupEdit](fw_group-edit.html) совпадают (т.е. это одно и то же представление или представления с одинаковым набором атрибутов). Если представления разные, то код в скобках программиста в приведенном выше методе `PrepareDataObjectForEdit` надо заменить на такой: + +```csharp +m_objView = ICSSoft.STORMNET.Information.GetView("C__ПокупкаE", typeof(IIS.MasterField.Покупка)); +ICSSoft.STORMNET.View ge_View = ICSSoft.STORMNET.Information.GetView("C__ПокупкаD", typeof(IIS.MasterField.Покупка)); +//дочитываем то, что есть на форме редактирования, но нет в GE +ICSSoft.STORMNET.View дочитать_View = m_objView - ge_View; +//из этого представления убираем свойства, которые могли быть изменены на форме редактирования, +//если она открывалась ранее +foreach (string altprop in dobject.GetAlteredPropertyNames()) + дочитать_View.RemoveProperty(altprop); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(дочитать_View, dobject, false, false); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей +return; +``` + +Однако в данном случае (в случае разных представлений) проявится особенность: если открыть мастер, ничего на нем не менять, открыть детейл на редактирование и сразу закрыть форму, то она закроется без вопроса о сохранении, а форма мастера спросит о сохранении. Это связано с тем, что после вычитывания дополнительных свойств детейла его набор атрибутов в копии мастера будет отличаться от набора в самом мастере. Избавиться от этого можно ручным исправлением копии мастера перед открытием формы редактирования детейла. diff --git a/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.en.md b/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.en.md index 31ab15111..da1bedd9f 100644 --- a/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.en.md +++ b/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.en.md @@ -167,7 +167,7 @@ public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contp { ДежурнаяГруппаСмены ДежГрСмены = (ДежурнаяГруппаСмены)ДежурныеГруппыСмены.EditManager.DataObject; ДежурнаяГруппа ДежГр = ((ЧленДежурнойГруппы)dataobject).ДежураяГруппа; - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject("Diurnale", ДежГр); + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject("Diurnale", ДежГр); // DataServiceProvider is deprecated; inject IDataService instead ДежГрСмены.НомерГруппы = ДежГр.НомерГруппы; ДежГрСмены.ТипДежурнойГруппы = ДежГр.ТипДежурнойГруппы; ДежГрСмены.Руководитель = ДежГр.Руководитель; diff --git a/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.ru.md b/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.ru.md index c4a2632a3..db98e0cdd 100644 --- a/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.ru.md +++ b/pages/products/flexberry-winforms/controls/lookup/fw_lookup-another-object.ru.md @@ -1,189 +1,189 @@ ---- -title: Вызов независимого мастера -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, Controls, LookUp, master -summary: Алгоритм добавления ссылок на независимого мастера для основной формы редактирования и детейлов, примеры использования -toc: true -permalink: ru/fw_lookup-another-object.html -lang: ru ---- - -Существует два способа добавить на форму редактирования [Lookup](fw_lookup.html) для выбора объекта, несвязанного с редактируемым на текущей форме: - -1. Добавить вычислимое поле в основной объект и перегенерировать форму с помощью [Flexberry Desinger](fd_flexberry-designer.html). -2. В коде приложения добавить Lookup на форму. - -### Алгоритм добавления LookUp в коде приложения - -* Добавить на форму [LookUp-контрол](fw_lookup.html). -* Создать еще один [EditManager](fw_editmanager.html). -* Приписать `LookUp` к созданному `EditManager` в методе `TuneLookupInformation`, а также добавить соответсвующую запись в метод `GetRunners()`. -* Добавить в конец пути контрола "(GroupEditBase)". - -{% include important.html content="Последний пункт нужен для того, чтобы система не считала данный лукап и объект, который в нём выбирается, редактируемым объектом. Без указания этого пути система будет сохранять данный объект в базу сразу после выбора объекта." %} - -## Пример вызова независимого списка мастеровых объектов - -На примере показано, как можно вызвать на лукап список объектов, не имеющих связей c объектом-инициатором и не являющихся мастером для какого-либо другого объекта в модели предметной области: - -* вызывается списочная форма объектов для выбора, -* процедуре вызова этой формы передаётся класс и название свойства этого класса, значением которого является объект класса, выбираемый на форме. - -Если такого класса нет, то его следует _создать_. - -### Пример - -Есть класс `Реагирование` и не связанный с ним (отношениями ассоциации или композиции) класс `ДежурнаяГруппа`. - -С формы редактирования `Реагирования` требуется вызвать список дежурных групп для размазывания свойств конкретной выбранной дежурной группы по свойствам `Реагирования` (точнее, добавления соответствующих детейлов). - -В модели нет класса, который содержал бы ссылку на дежурную группу, соответственно, его необходимо доьавить: - -1.Создать _класс_ внутри формы Реагирования (где осуществляется вызов списка). Объект должен быть _нехранимым_. Таким образом не требуеся менять модель на диаграмме, так как класс ннеобходим только для LookUp. - -```csharp -public class WinformРеагированиеE : ICSSoft.STORMNET.UI.BaseWinEdit, ICSSoft.AMS02.Происшествия.DPDIРеагированиеE -{ - // ..... - - [AutoAltered()] - [NotStored()] - class Временный_ДежурнаяГруппа : ICSSoft.STORMNET.DataObject - { - private Объекты.ДежурнаяГруппа fДЖ = null; - public virtual Объекты.ДежурнаяГруппа ДЖ - { - get - { - return fДЖ; - } - set - { - fДЖ = value; - } - } - } - - //..... -} -``` - -{% include important.html content="ДЖ должно быть свойством (а не публичным полем), т.к. вызывается метод __SetPropByName__, который работает только со __свойствами__. При несоблюдении отображается ошибка о невозможности внести изменения в свойство." %} - -2.Для кнопки открытия списка добавляется следующее: - -```csharp - string propertyName = "ДЖ"; - string contPath = ""; - base.OnEdit(propertyName, new Временный_ДежурнаяГруппа(), contPath, null); -``` - -__propertyName__ - имя свойства класса, который передаётся вторым параметром (в данном случае Временный_ДежурнаяГруппа), в который вернётся выбранный элемент. - -Применимо в случае, если класс _хранимый_, т.к. возврат параметров происходит через `SaveEvent`. - -Чтобы этого избежать следует: - -```csharp - { - object form = null; - System.Type FormType = null; - ICSSoft.STORMNET.DataObject dobj = null; - string propertyName = "ДЖ"; - - FormType = System.Type.GetType("ICSSoft.AMS02.Происшествия.ДежурнаяГруппаL,Происшествия(Forms)"); - - Временный_ДежурнаяГруппа FL = new Временный_ДежурнаяГруппа(); - //FL.ДЖ = ...; - dobj = FL; - - form = ICSSoft.STORMNET.UI.ContRunner.RunForm(FormType); - if (form is ICSSoft.STORMNET.UI.BaseIndpdList) - { - (form as ICSSoft.STORMNET.UI.BaseIndpdList).SaveEvent += new ICSSoft.STORMNET.UI.SaveEventArgsHandler(OnReturnFromList); - (form as ICSSoft.STORMNET.UI.BaseIndpdList).Edit(dobj, "", propertyName, null); - } - } - - Объекты.ДежурнаяГруппа ДежурГр; - - private void OnReturnFromList(object sender, ICSSoft.STORMNET.UI.SaveEventArgs e) - { - this.ДежурГр = ((Временный_ДежурнаяГруппа)e.dataobject).ДЖ; - } -``` - -3.Подписаться на созданный обработчик сохранения и дописать все необходимые операции. Если FL.ДЖ присвоить конкретное значение, то в списке будет подсвечен (выбран) этот элемент. - -## Использование в GroupEdit - -Например, есть класс __ДежурнаяГруппаСмены__ и не связанный с ним (отношениями ассоциации или композиции) класс __ДежурнаяГруппа__. По лукапу номера группы нужно вызвать список ДежурныхГрупп для заполнения полей ДежурнойГруппыСмены из свойств выбранной ДежурнойГруппы. - -Для этого: - -* В методе __GetControl__ класса CustomControlProvide устанавить контрол для поля НомерГруппы: - -```csharp - if (view.Name # "ДежурнаяГруппаСменыE" && propertyName "НомерГруппы") - { - ICSSoft.STORMNET.Windows.Forms.LookUp lookUp = new ICSSoft.STORMNET.Windows.Forms.LookUp(); - - ctrl = new ICSSoft.STORMNET.Windows.Forms.Binders.ControlForBindStruct(lookUp, "Value"); - } -``` - -* Переопределить метод `OnEdit` в winformДежурнаяСменаE. Так как класс ДежурнаяГруппаСмены не имеет ссылки на ДежурнуюГруппу, то выбрать любой другой класс, имеющий такую ссылку, например, _ЧленДежурнойГруппы_. - -```csharp -dataobject = new ЧленДежурнойГруппы(); //класс, имеющий ссылку на дежурную группу -propertyname = "ДежураяГруппа"; //имя ссылки - -public override void OnEdit(string propertyname, ICSSoft.STORMNET.DataObject dataobject, string contpath, object tag) - { - if (dataobject is ДежурнаяГруппаСмены && propertyname == "ДежурныеГруппыСмены.НомерГруппы") - { - if (((ДежурнаяГруппаСмены)dataobject).ТипДежурнойГруппы != null) - { - tag = FunctionBuilder.BuildEquals("ТипДежурнойГруппы", ((ДежурнаяГруппаСмены)dataobject).ТипДежурнойГруппы); - } - dataobject = new ЧленДежурнойГруппы(); - propertyname = "ДежураяГруппа"; - } - - base.OnEdit(propertyname, dataobject, contpath, tag); - } -``` - -* Переопределить метод __Edited__ в winformДежурнаяСменаE. Записываем все необходимые свойства в ДежурнуюГруппуСмены из выбранной ДежурнойГруппы: - -```csharp -public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) - { - base.Edited(dataobject, contpath, propertyname); - - if (dataobject is ЧленДежурнойГруппы && propertyname == "ДежураяГруппа") - { - ДежурнаяГруппаСмены ДежГрСмены = (ДежурнаяГруппаСмены)ДежурныеГруппыСмены.EditManager.DataObject; - ДежурнаяГруппа ДежГр = ((ЧленДежурнойГруппы)dataobject).ДежураяГруппа; - ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject("ДежурнаяГруппаE", ДежГр); - ДежГрСмены.НомерГруппы = ДежГр.НомерГруппы; - ДежГрСмены.ТипДежурнойГруппы = ДежГр.ТипДежурнойГруппы; - ДежГрСмены.Руководитель = ДежГр.Руководитель; - ДежГрСмены.Комментарий = ДежГр.Комментарий; - ДежГрСмены.Позывной = ДежГр.Позывной; - ДежГрСмены.ЧленыДежГруппыСмены.Clear(); - - for (int t = 0; t < ДежГр.ЧленыДежурнойГруппы.Count; t++) - { - Объекты.ЧленДежурнойГруппы членДежГр = ДежГр.ЧленыДежурнойГруппы[t]; - Объекты.ЧленДежГруппыСмены чдгс = new Объекты.ЧленДежГруппыСмены(); - чдгс.ДежурнаяГруппаСмены = ДежГрСмены; - чдгс.НомерПП = членДежГр.НомерПП; - чдгс.Сотрудник = членДежГр.Сотрудник; - чдгс.Позывной = членДежГр.Позывной; - ДежГрСмены.ЧленыДежГруппыСмены.Add(чдгс); - } - ДежурныеГруппыСмены.EditManager.Change(); - } - } -``` +--- +title: Вызов независимого мастера +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, Controls, LookUp, master +summary: Алгоритм добавления ссылок на независимого мастера для основной формы редактирования и детейлов, примеры использования +toc: true +permalink: ru/fw_lookup-another-object.html +lang: ru +--- + +Существует два способа добавить на форму редактирования [Lookup](fw_lookup.html) для выбора объекта, несвязанного с редактируемым на текущей форме: + +1. Добавить вычислимое поле в основной объект и перегенерировать форму с помощью [Flexberry Desinger](fd_flexberry-designer.html). +2. В коде приложения добавить Lookup на форму. + +### Алгоритм добавления LookUp в коде приложения + +* Добавить на форму [LookUp-контрол](fw_lookup.html). +* Создать еще один [EditManager](fw_editmanager.html). +* Приписать `LookUp` к созданному `EditManager` в методе `TuneLookupInformation`, а также добавить соответсвующую запись в метод `GetRunners()`. +* Добавить в конец пути контрола "(GroupEditBase)". + +{% include important.html content="Последний пункт нужен для того, чтобы система не считала данный лукап и объект, который в нём выбирается, редактируемым объектом. Без указания этого пути система будет сохранять данный объект в базу сразу после выбора объекта." %} + +## Пример вызова независимого списка мастеровых объектов + +На примере показано, как можно вызвать на лукап список объектов, не имеющих связей c объектом-инициатором и не являющихся мастером для какого-либо другого объекта в модели предметной области: + +* вызывается списочная форма объектов для выбора, +* процедуре вызова этой формы передаётся класс и название свойства этого класса, значением которого является объект класса, выбираемый на форме. + +Если такого класса нет, то его следует _создать_. + +### Пример + +Есть класс `Реагирование` и не связанный с ним (отношениями ассоциации или композиции) класс `ДежурнаяГруппа`. + +С формы редактирования `Реагирования` требуется вызвать список дежурных групп для размазывания свойств конкретной выбранной дежурной группы по свойствам `Реагирования` (точнее, добавления соответствующих детейлов). + +В модели нет класса, который содержал бы ссылку на дежурную группу, соответственно, его необходимо доьавить: + +1.Создать _класс_ внутри формы Реагирования (где осуществляется вызов списка). Объект должен быть _нехранимым_. Таким образом не требуеся менять модель на диаграмме, так как класс ннеобходим только для LookUp. + +```csharp +public class WinformРеагированиеE : ICSSoft.STORMNET.UI.BaseWinEdit, ICSSoft.AMS02.Происшествия.DPDIРеагированиеE +{ + // ..... + + [AutoAltered()] + [NotStored()] + class Временный_ДежурнаяГруппа : ICSSoft.STORMNET.DataObject + { + private Объекты.ДежурнаяГруппа fДЖ = null; + public virtual Объекты.ДежурнаяГруппа ДЖ + { + get + { + return fДЖ; + } + set + { + fДЖ = value; + } + } + } + + //..... +} +``` + +{% include important.html content="ДЖ должно быть свойством (а не публичным полем), т.к. вызывается метод __SetPropByName__, который работает только со __свойствами__. При несоблюдении отображается ошибка о невозможности внести изменения в свойство." %} + +2.Для кнопки открытия списка добавляется следующее: + +```csharp + string propertyName = "ДЖ"; + string contPath = ""; + base.OnEdit(propertyName, new Временный_ДежурнаяГруппа(), contPath, null); +``` + +__propertyName__ - имя свойства класса, который передаётся вторым параметром (в данном случае Временный_ДежурнаяГруппа), в который вернётся выбранный элемент. + +Применимо в случае, если класс _хранимый_, т.к. возврат параметров происходит через `SaveEvent`. + +Чтобы этого избежать следует: + +```csharp + { + object form = null; + System.Type FormType = null; + ICSSoft.STORMNET.DataObject dobj = null; + string propertyName = "ДЖ"; + + FormType = System.Type.GetType("ICSSoft.AMS02.Происшествия.ДежурнаяГруппаL,Происшествия(Forms)"); + + Временный_ДежурнаяГруппа FL = new Временный_ДежурнаяГруппа(); + //FL.ДЖ = ...; + dobj = FL; + + form = ICSSoft.STORMNET.UI.ContRunner.RunForm(FormType); + if (form is ICSSoft.STORMNET.UI.BaseIndpdList) + { + (form as ICSSoft.STORMNET.UI.BaseIndpdList).SaveEvent += new ICSSoft.STORMNET.UI.SaveEventArgsHandler(OnReturnFromList); + (form as ICSSoft.STORMNET.UI.BaseIndpdList).Edit(dobj, "", propertyName, null); + } + } + + Объекты.ДежурнаяГруппа ДежурГр; + + private void OnReturnFromList(object sender, ICSSoft.STORMNET.UI.SaveEventArgs e) + { + this.ДежурГр = ((Временный_ДежурнаяГруппа)e.dataobject).ДЖ; + } +``` + +3.Подписаться на созданный обработчик сохранения и дописать все необходимые операции. Если FL.ДЖ присвоить конкретное значение, то в списке будет подсвечен (выбран) этот элемент. + +## Использование в GroupEdit + +Например, есть класс __ДежурнаяГруппаСмены__ и не связанный с ним (отношениями ассоциации или композиции) класс __ДежурнаяГруппа__. По лукапу номера группы нужно вызвать список ДежурныхГрупп для заполнения полей ДежурнойГруппыСмены из свойств выбранной ДежурнойГруппы. + +Для этого: + +* В методе __GetControl__ класса CustomControlProvide устанавить контрол для поля НомерГруппы: + +```csharp + if (view.Name # "ДежурнаяГруппаСменыE" && propertyName "НомерГруппы") + { + ICSSoft.STORMNET.Windows.Forms.LookUp lookUp = new ICSSoft.STORMNET.Windows.Forms.LookUp(); + + ctrl = new ICSSoft.STORMNET.Windows.Forms.Binders.ControlForBindStruct(lookUp, "Value"); + } +``` + +* Переопределить метод `OnEdit` в winformДежурнаяСменаE. Так как класс ДежурнаяГруппаСмены не имеет ссылки на ДежурнуюГруппу, то выбрать любой другой класс, имеющий такую ссылку, например, _ЧленДежурнойГруппы_. + +```csharp +dataobject = new ЧленДежурнойГруппы(); //класс, имеющий ссылку на дежурную группу +propertyname = "ДежураяГруппа"; //имя ссылки + +public override void OnEdit(string propertyname, ICSSoft.STORMNET.DataObject dataobject, string contpath, object tag) + { + if (dataobject is ДежурнаяГруппаСмены && propertyname == "ДежурныеГруппыСмены.НомерГруппы") + { + if (((ДежурнаяГруппаСмены)dataobject).ТипДежурнойГруппы != null) + { + tag = FunctionBuilder.BuildEquals("ТипДежурнойГруппы", ((ДежурнаяГруппаСмены)dataobject).ТипДежурнойГруппы); + } + dataobject = new ЧленДежурнойГруппы(); + propertyname = "ДежураяГруппа"; + } + + base.OnEdit(propertyname, dataobject, contpath, tag); + } +``` + +* Переопределить метод __Edited__ в winformДежурнаяСменаE. Записываем все необходимые свойства в ДежурнуюГруппуСмены из выбранной ДежурнойГруппы: + +```csharp +public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) + { + base.Edited(dataobject, contpath, propertyname); + + if (dataobject is ЧленДежурнойГруппы && propertyname == "ДежураяГруппа") + { + ДежурнаяГруппаСмены ДежГрСмены = (ДежурнаяГруппаСмены)ДежурныеГруппыСмены.EditManager.DataObject; + ДежурнаяГруппа ДежГр = ((ЧленДежурнойГруппы)dataobject).ДежураяГруппа; + ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject("ДежурнаяГруппаE", ДежГр); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей + ДежГрСмены.НомерГруппы = ДежГр.НомерГруппы; + ДежГрСмены.ТипДежурнойГруппы = ДежГр.ТипДежурнойГруппы; + ДежГрСмены.Руководитель = ДежГр.Руководитель; + ДежГрСмены.Комментарий = ДежГр.Комментарий; + ДежГрСмены.Позывной = ДежГр.Позывной; + ДежГрСмены.ЧленыДежГруппыСмены.Clear(); + + for (int t = 0; t < ДежГр.ЧленыДежурнойГруппы.Count; t++) + { + Объекты.ЧленДежурнойГруппы членДежГр = ДежГр.ЧленыДежурнойГруппы[t]; + Объекты.ЧленДежГруппыСмены чдгс = new Объекты.ЧленДежГруппыСмены(); + чдгс.ДежурнаяГруппаСмены = ДежГрСмены; + чдгс.НомерПП = членДежГр.НомерПП; + чдгс.Сотрудник = членДежГр.Сотрудник; + чдгс.Позывной = членДежГр.Позывной; + ДежГрСмены.ЧленыДежГруппыСмены.Add(чдгс); + } + ДежурныеГруппыСмены.EditManager.Change(); + } + } +``` diff --git a/pages/products/flexberry-winforms/controls/lookup/fw_lookup.en.md b/pages/products/flexberry-winforms/controls/lookup/fw_lookup.en.md index 9ee84982a..87bc35a39 100644 --- a/pages/products/flexberry-winforms/controls/lookup/fw_lookup.en.md +++ b/pages/products/flexberry-winforms/controls/lookup/fw_lookup.en.md @@ -47,7 +47,7 @@ public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contp Э.ФИОСотрудника = Э.Сотрудник.ОпрПолноеФИО(); if (р.Должность != null) { - DataServiceProvider.DataService.LoadObject(р.Должность); + DataServiceProvider.DataService.LoadObject(р.Должность); // DataServiceProvider is deprecated; inject IDataService instead Э.Должность = р.Должность.Наименование; } else Э.Должность = ""; @@ -88,7 +88,7 @@ public void ПоказатьСписок() LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лицо), "ЛицоL"); lcs.LimitFunction = lf; - ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); + ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider is deprecated; inject IDataService instead if (objs.Length == 0) { diff --git a/pages/products/flexberry-winforms/controls/lookup/fw_lookup.ru.md b/pages/products/flexberry-winforms/controls/lookup/fw_lookup.ru.md index 2f68bbf51..292379481 100644 --- a/pages/products/flexberry-winforms/controls/lookup/fw_lookup.ru.md +++ b/pages/products/flexberry-winforms/controls/lookup/fw_lookup.ru.md @@ -1,225 +1,225 @@ ---- -title: LookUp -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, Controls, LookUp -summary: Внешний вид, множественный выбор, переопределение методов, возможные проблемы использования и пути их решения -toc: true -permalink: ru/fw_lookup.html -lang: ru ---- - -`LookUp` (действие) - выбор мастерового объекта (проставление ссылки на мастеровой объект). - -`LookUp` (контрол) - контрол для выбора мастерового объекта, возвращающий ссылку на него. - -## Возврат нескольких объектов - -Существует возможность получать все объекты, выбранные на списке по Lookup. - -Это используется в [редакторе ограничений](fw_limit-editor-advanced-view.html), где для вида ограничения `Среди значений` возвращаются все выбранные на списке по лукапу объекты. - -Все выбранные объекты можно получить, обратившись к `DynamicProperties` стандартно возвращаемого объекта. А именно: - -```csharp -o.DynamicProperties["retFromObjectListView"] as List -``` - -Полученный список не будет содержать первого выбранного объекта `o`. - -__Замечание:__ на формах, имеющих несколько [ObjectListView](fw_objectlistview.html) или `ObjectHierarchicalView`, нужно убрать перегрузку `prv_EditData` и подписку на `OLV.ReturnData`. - -## Переопределить метода Edited - -На примере показано как можно переопределить метод __Edited__, чтобы использовать полученные от LookUp данные. - -```csharp -public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) - { - base.Edited (dataobject, contpath, propertyname); - - if (propertyname == "Сотрудник") - { - Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject; - Объекты.Сотрудник р = (Объекты.Сотрудник)Э.Сотрудник; - - Э.ФИОСотрудника = Э.Сотрудник.ОпрПолноеФИО(); - if (р.Должность != null) - { - DataServiceProvider.DataService.LoadObject(р.Должность); - Э.Должность = р.Должность.Наименование; - } - else Э.Должность = ""; - - EditManager.Change("ФИОСотрудника"); - EditManager.Change("Должность"); - } - - if (propertyname == "Сотрудник") - { - Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject; - Объекты.ОтвЗаРешение р = (Объекты.ОтвЗаРешение)Э.УКогоНаходится; - - if (р != null) - { - extTextControl1.Text = р.Наименование; - } - else extTextControl1.Text = ""; - } - } -``` - -## Кнопка отображения списка - -Для того чтобы добавить кнопку отображения мастерового списка к Lookup, нужно: - -* Создать плоский контрол __button__ -* Добавить иконку из __ImageList__. -* На нажатие кнопки добавить __вызов__ следующей функции: - -```csharp -public void ПоказатьСписок() - { - SQLWhereLanguageDef langdef = SQLWhereLanguageDef.LanguageDef; - Function lf = null; - - // формируем lf - LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лицо), "ЛицоL"); - lcs.LimitFunction = lf; - - ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); - - if (objs.Length == 0) - { - Tools.ShowInformation("Не найдено ни одного лица с заданными параметрами"); - return; - } - else // хоть кого-то нашли - { - string contpath = "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(Tab" + "Control)/panel(TabPage)/panel(GroupBox)/ctrlЛицо(LookUp)"; - base.OnEdit("Лицо", EditManager.DataObject, contpath, lf); - } - } -``` - -## Изменение внешнего вида - -Существует два способа изменить изображения на кнопках LookUp. - -1.В случае если требуется изменить изображения в рамках всего приложения, необходимо инициализировать _статический ImageList_ при запуске приложения. В этом списке должны присутствовать изображения с именами "LookUp", "Clear" и "Edit". - -__Пример:__ - -```csharp -LookUp.UserImageList.Images.Add("LookUp", Properties.Resources.LookUpImage); -LookUp.UserImageList.Images.Add("Clear", Properties.Resources.ClearImage); -LookUp.UserImageList.Images.Add("Edit", Properties.Resources.EditImage); -``` - -2.Для конкретного экземпляра `LookUp` с помощью свойства `UserImageList` можно назначить _пользовательский ImageList_, в котором также должны быть изображения с именами "LookUp", "Clear" и "Edit". - -### Размер и границы кнопок - -Размер кнопок задается с помощью свойства `ButtonSize`, при изменении данного свойства должно выполнится перевычисление размера всего контрола. - -За отображение границ кнопок отвечает свойство `ButtonBorder`. - -## Запрет изменения в BeforeChangeProperty - -Уставновка признака Cancel в методе BeforeChangeProperty при изменении мастерового поля не блокирует Lookup и последующее изменение свойства. - -## Смена обработчика look_LookUpEvent - -Для того чтобы заменить обработчик `look_LookUpEvent` на свой, нужно: - -* создать контейнер-runner, -* подписаться на события сохранения (отказа от сохранения), -* задать свои действия при наступлении событий. - -```csharp -private void look_LookUpEvent1(object sender, System.EventArgs e) -{ - Посетитель oПосетитель = (Посетитель)this.EditManager.DataObject; - - Function lf = FunctionBuilder.BuildTrue(); - - //создадим контейнер-раннер - ICSSoft.АдресноеБюро.ЛичностьL FormЛичностьL = (ICSSoft.АдресноеБюро.ЛичностьL) ICSSoft.STORMNET.UI.ContRunner.RunForm(typeof(ICSSoft.АдресноеБюро.ЛичностьL)); - FormЛичностьL.Edit(oПосетитель, "Личность", "Личность",lf); - - //подпишемся на события - FormЛичностьL.SaveEvent+=new ICSSoft.STORMNET.UI.SaveEventArgsHandler(FormЛичностьL_SaveEvent);FormЛичностьL.CancelEvent+=new ICSSoft.STORMNET.UI.CancelEventArgsHandler(FormЛичностьL_CancelEvent); -} - -private void FormЛичностьL_SaveEvent(object sender, ICSSoft.STORMNET.UI.SaveEventArgs e) -{ - //наши действия -} - -private void FormЛичностьL_CancelEvent(object sender, ICSSoft.STORMNET.UI.CancelEventArgs e) -{ - //наши действия -} -``` - -## Возможные проблемы использования - -### Стандартно сгенерированный lookup - -#### На форме - -Если не срабатывает обработчик события `look_LookUpEvent` (в зависимой форме). - -* Правильно указать путь на форме до `Lookup` в методе `prv_TuneLookupInformations` (в зависимой форме). -* Указать форму вызова в методе `GetEditor` независимой формы. -* На кнопку `LookUp` (например, для Гражданства это будет ctrlГражданство) навесить обработчик __события__ LookUp. - -```csharp -this.ctrlГражданство.LookUpEvent += look_LookUpEvent -``` - -#### В GroupEdit - -* Привязка [GropEdit](fw_group-edit.html) к EditManager формы -* Наличие обработчика `this.gr_SetupEditorEventHandler` типа `OnSetupEditorEventHandler` для события `SetupEditor` -* Упоминание `GroupEdit` в методе `prv_TuneLookupInformations` (в зависимой форме), _например_: - -```csharp -m_arrGroupEditInformations.Add( - new ICSSoft.STORMNET.UI.GroupEditInformation(this.ПредметыИзъятия, - "ИтогиИзъятия.ПредметыИзъятия", - "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(TabControl)/panel(TabPage)/ПредметыИзъятия(GroupEditBase)")); -``` - -### Нестандартные случаи использования Lookup - -#### Не поднимается форма по Lookup - -Нужно учесть особенности контрола: - -* Если не существует свойство, имя которого передаётся в качестве `PropertyName`, то лучше указать пустую строку, иначе метод `Save` не будет вызываться. -* Нехранимые объекты, поднимаемые по Lookup, scriptizer обрабатываются нестандартно и событие необходимо прописывать вручную. - -Также следует проверить: - -* Хранимый ли объект, с которого поднимается LookUp. -* Какие формы поднимаются и с какой формы. -* Поднимается ли с формы по кнопке LookUp. Если да, то поднимается ли с формы LookUp. Если да, то _неправильно указываются параметры_. Если не поднимается ни по кнопке, ни из метода, то есть ошибка, скорее всего, носит системный характер. - -#### Не выдаётся сообщение о сохранении объекта при закрытии формы - -Необходимо проверить: - -* Объект имеет статус _Altered_ -* Объект изменил свои свойства с момента поднятия формы по Lookup. При поднятии по Lookup форма-инициатор в методе `PrepareDataObjectForEdit` создаёт копию данных, и при закрытии сравнивается эта копия с текущим на момент закрытия объектом. Сохранение произойдёт только в случае наличия разницы между объектом и его копией. -* Форма корректно поднята по Lookup: - * передаётся объект формы-инициатора LookUp, а не тот, который надо редактировать - * указано существующее свойство или пустая строка - -## Изменение названия списка для Lookup - -Изменить название списка для Lookup, находящегося на разных формах редактирования можно задать условия на форме редактирования, а на списковой форме добавить обработчик данного события. Например, на форме редактирования при открытии Lookup в объект данных добавить необходимое название в `DynamicProperties`, а на списковой форме его вычитывать. - -## Дополнительно - -* [Лукап с предиктивным вводом](fw_extended-lookup.html) -* [Вызов независимого мастера](fw_lookup-another-object.html) +--- +title: LookUp +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, Controls, LookUp +summary: Внешний вид, множественный выбор, переопределение методов, возможные проблемы использования и пути их решения +toc: true +permalink: ru/fw_lookup.html +lang: ru +--- + +`LookUp` (действие) - выбор мастерового объекта (проставление ссылки на мастеровой объект). + +`LookUp` (контрол) - контрол для выбора мастерового объекта, возвращающий ссылку на него. + +## Возврат нескольких объектов + +Существует возможность получать все объекты, выбранные на списке по Lookup. + +Это используется в [редакторе ограничений](fw_limit-editor-advanced-view.html), где для вида ограничения `Среди значений` возвращаются все выбранные на списке по лукапу объекты. + +Все выбранные объекты можно получить, обратившись к `DynamicProperties` стандартно возвращаемого объекта. А именно: + +```csharp +o.DynamicProperties["retFromObjectListView"] as List +``` + +Полученный список не будет содержать первого выбранного объекта `o`. + +__Замечание:__ на формах, имеющих несколько [ObjectListView](fw_objectlistview.html) или `ObjectHierarchicalView`, нужно убрать перегрузку `prv_EditData` и подписку на `OLV.ReturnData`. + +## Переопределить метода Edited + +На примере показано как можно переопределить метод __Edited__, чтобы использовать полученные от LookUp данные. + +```csharp +public override void Edited(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname) + { + base.Edited (dataobject, contpath, propertyname); + + if (propertyname == "Сотрудник") + { + Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject; + Объекты.Сотрудник р = (Объекты.Сотрудник)Э.Сотрудник; + + Э.ФИОСотрудника = Э.Сотрудник.ОпрПолноеФИО(); + if (р.Должность != null) + { + DataServiceProvider.DataService.LoadObject(р.Должность); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей + Э.Должность = р.Должность.Наименование; + } + else Э.Должность = ""; + + EditManager.Change("ФИОСотрудника"); + EditManager.Change("Должность"); + } + + if (propertyname == "Сотрудник") + { + Объекты.ДвижениеГруппыОтказнМатер Э = (Объекты.ДвижениеГруппыОтказнМатер)EditManager.DataObject; + Объекты.ОтвЗаРешение р = (Объекты.ОтвЗаРешение)Э.УКогоНаходится; + + if (р != null) + { + extTextControl1.Text = р.Наименование; + } + else extTextControl1.Text = ""; + } + } +``` + +## Кнопка отображения списка + +Для того чтобы добавить кнопку отображения мастерового списка к Lookup, нужно: + +* Создать плоский контрол __button__ +* Добавить иконку из __ImageList__. +* На нажатие кнопки добавить __вызов__ следующей функции: + +```csharp +public void ПоказатьСписок() + { + SQLWhereLanguageDef langdef = SQLWhereLanguageDef.LanguageDef; + Function lf = null; + + // формируем lf + LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Лицо), "ЛицоL"); + lcs.LimitFunction = lf; + + ICSSoft.STORMNET.DataObject[] objs = DataServiceProvider.DataService.LoadObjects(lcs); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей + + if (objs.Length == 0) + { + Tools.ShowInformation("Не найдено ни одного лица с заданными параметрами"); + return; + } + else // хоть кого-то нашли + { + string contpath = "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(Tab" + "Control)/panel(TabPage)/panel(GroupBox)/ctrlЛицо(LookUp)"; + base.OnEdit("Лицо", EditManager.DataObject, contpath, lf); + } + } +``` + +## Изменение внешнего вида + +Существует два способа изменить изображения на кнопках LookUp. + +1.В случае если требуется изменить изображения в рамках всего приложения, необходимо инициализировать _статический ImageList_ при запуске приложения. В этом списке должны присутствовать изображения с именами "LookUp", "Clear" и "Edit". + +__Пример:__ + +```csharp +LookUp.UserImageList.Images.Add("LookUp", Properties.Resources.LookUpImage); +LookUp.UserImageList.Images.Add("Clear", Properties.Resources.ClearImage); +LookUp.UserImageList.Images.Add("Edit", Properties.Resources.EditImage); +``` + +2.Для конкретного экземпляра `LookUp` с помощью свойства `UserImageList` можно назначить _пользовательский ImageList_, в котором также должны быть изображения с именами "LookUp", "Clear" и "Edit". + +### Размер и границы кнопок + +Размер кнопок задается с помощью свойства `ButtonSize`, при изменении данного свойства должно выполнится перевычисление размера всего контрола. + +За отображение границ кнопок отвечает свойство `ButtonBorder`. + +## Запрет изменения в BeforeChangeProperty + +Уставновка признака Cancel в методе BeforeChangeProperty при изменении мастерового поля не блокирует Lookup и последующее изменение свойства. + +## Смена обработчика look_LookUpEvent + +Для того чтобы заменить обработчик `look_LookUpEvent` на свой, нужно: + +* создать контейнер-runner, +* подписаться на события сохранения (отказа от сохранения), +* задать свои действия при наступлении событий. + +```csharp +private void look_LookUpEvent1(object sender, System.EventArgs e) +{ + Посетитель oПосетитель = (Посетитель)this.EditManager.DataObject; + + Function lf = FunctionBuilder.BuildTrue(); + + //создадим контейнер-раннер + ICSSoft.АдресноеБюро.ЛичностьL FormЛичностьL = (ICSSoft.АдресноеБюро.ЛичностьL) ICSSoft.STORMNET.UI.ContRunner.RunForm(typeof(ICSSoft.АдресноеБюро.ЛичностьL)); + FormЛичностьL.Edit(oПосетитель, "Личность", "Личность",lf); + + //подпишемся на события + FormЛичностьL.SaveEvent+=new ICSSoft.STORMNET.UI.SaveEventArgsHandler(FormЛичностьL_SaveEvent);FormЛичностьL.CancelEvent+=new ICSSoft.STORMNET.UI.CancelEventArgsHandler(FormЛичностьL_CancelEvent); +} + +private void FormЛичностьL_SaveEvent(object sender, ICSSoft.STORMNET.UI.SaveEventArgs e) +{ + //наши действия +} + +private void FormЛичностьL_CancelEvent(object sender, ICSSoft.STORMNET.UI.CancelEventArgs e) +{ + //наши действия +} +``` + +## Возможные проблемы использования + +### Стандартно сгенерированный lookup + +#### На форме + +Если не срабатывает обработчик события `look_LookUpEvent` (в зависимой форме). + +* Правильно указать путь на форме до `Lookup` в методе `prv_TuneLookupInformations` (в зависимой форме). +* Указать форму вызова в методе `GetEditor` независимой формы. +* На кнопку `LookUp` (например, для Гражданства это будет ctrlГражданство) навесить обработчик __события__ LookUp. + +```csharp +this.ctrlГражданство.LookUpEvent += look_LookUpEvent +``` + +#### В GroupEdit + +* Привязка [GropEdit](fw_group-edit.html) к EditManager формы +* Наличие обработчика `this.gr_SetupEditorEventHandler` типа `OnSetupEditorEventHandler` для события `SetupEditor` +* Упоминание `GroupEdit` в методе `prv_TuneLookupInformations` (в зависимой форме), _например_: + +```csharp +m_arrGroupEditInformations.Add( + new ICSSoft.STORMNET.UI.GroupEditInformation(this.ПредметыИзъятия, + "ИтогиИзъятия.ПредметыИзъятия", + "STORMCASE.STORMNET.Generator.SerializeNewEditForm/EditPanel(Panel)/TabControl(TabControl)/panel(TabPage)/ПредметыИзъятия(GroupEditBase)")); +``` + +### Нестандартные случаи использования Lookup + +#### Не поднимается форма по Lookup + +Нужно учесть особенности контрола: + +* Если не существует свойство, имя которого передаётся в качестве `PropertyName`, то лучше указать пустую строку, иначе метод `Save` не будет вызываться. +* Нехранимые объекты, поднимаемые по Lookup, scriptizer обрабатываются нестандартно и событие необходимо прописывать вручную. + +Также следует проверить: + +* Хранимый ли объект, с которого поднимается LookUp. +* Какие формы поднимаются и с какой формы. +* Поднимается ли с формы по кнопке LookUp. Если да, то поднимается ли с формы LookUp. Если да, то _неправильно указываются параметры_. Если не поднимается ни по кнопке, ни из метода, то есть ошибка, скорее всего, носит системный характер. + +#### Не выдаётся сообщение о сохранении объекта при закрытии формы + +Необходимо проверить: + +* Объект имеет статус _Altered_ +* Объект изменил свои свойства с момента поднятия формы по Lookup. При поднятии по Lookup форма-инициатор в методе `PrepareDataObjectForEdit` создаёт копию данных, и при закрытии сравнивается эта копия с текущим на момент закрытия объектом. Сохранение произойдёт только в случае наличия разницы между объектом и его копией. +* Форма корректно поднята по Lookup: + * передаётся объект формы-инициатора LookUp, а не тот, который надо редактировать + * указано существующее свойство или пустая строка + +## Изменение названия списка для Lookup + +Изменить название списка для Lookup, находящегося на разных формах редактирования можно задать условия на форме редактирования, а на списковой форме добавить обработчик данного события. Например, на форме редактирования при открытии Lookup в объект данных добавить необходимое название в `DynamicProperties`, а на списковой форме его вычитывать. + +## Дополнительно + +* [Лукап с предиктивным вводом](fw_extended-lookup.html) +* [Вызов независимого мастера](fw_lookup-another-object.html) diff --git a/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.en.md b/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.en.md index c61851918..ee9bdc6f8 100644 --- a/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.en.md +++ b/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.en.md @@ -22,22 +22,22 @@ Typical and recommended implementation from the application project can be done * The dependent form contains events that are generated by the interface part (go forward, backward, on the specified object, etc.). The triggering of these events is linked to the corresponding controls. Example: ```csharp -/// -/// Delegate for event rewind objects -/// -/// -/// +/// +/// Delegate for event rewind objects +/// +/// +/// public delegate void PrevNextEventArgsHandler(object sender, EventArgs e); -//... -// *** Start programmer edit section *** (WinformПланетаE CustomMembers) -/// -/// Forward -/// +//... +// *** Start programmer edit section *** (WinformПланетаE CustomMembers) +/// +/// Forward +/// public event PrevNextEventArgsHandler NextEvent; -/// -/// Rewind -/// +/// +/// Rewind +/// public event PrevNextEventArgsHandler PrevEvent; private void button1_Click(object sender, EventArgs e) @@ -56,29 +56,29 @@ private void button2_Click(object sender, EventArgs e) } } -// *** End programmer edit section *** (WinformПланетаE CustomMembers) +// *** End programmer edit section *** (WinformПланетаE CustomMembers) ``` * Independent form sees these events, but through the interface (after the code class independent Flexberry generates an interface to define event methods and attributes dependent form) ```csharp -/// -/// this interface definition, which is inherited by the dependent form, but it is in the file independent -/// +/// +/// this interface definition, which is inherited by the dependent form, but it is in the file independent +/// public interface DPDIПланетаE { - // *** Start programmer edit section *** (DPDIПланетаE Members) - /// - /// Forward - /// + // *** Start programmer edit section *** (DPDIПланетаE Members) + /// + /// Forward + /// event PrevNextEventArgsHandler NextEvent; - /// - /// Rewind - /// + /// + /// Rewind + /// event PrevNextEventArgsHandler PrevEvent; - // *** End programmer edit section *** (DPDIПланетаE Members) + // *** End programmer edit section *** (DPDIПланетаE Members) } ``` @@ -88,7 +88,7 @@ public interface DPDIПланетаE ```csharp protected virtual void prv_AttachEventsFromDpdForm(object form) { - // *** Start programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) + // *** Start programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) IIS.AlteredHierarchy.DPDIПланетаE form1 = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); form1.NextEvent -= new PrevNextEventArgsHandler(form1_NextEvent); form1.NextEvent += new PrevNextEventArgsHandler(form1_NextEvent); @@ -96,12 +96,12 @@ protected virtual void prv_AttachEventsFromDpdForm(object form) form1.PrevEvent -= new PrevNextEventArgsHandler(form1_PrevEvent); form1.PrevEvent += new PrevNextEventArgsHandler(form1_PrevEvent); - // *** End programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) + // *** End programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) IIS.AlteredHierarchy.DPDIПланетаE typedForm = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); } -//... -// *** Start programmer edit section *** (Planete CustomMembers) +//... +// *** Start programmer edit section *** (Planete CustomMembers) void form1_PrevEvent(object sender, EventArgs e) { GetNextOrPrevObj(false); @@ -112,30 +112,30 @@ void form1_NextEvent(object sender, EventArgs e) GetNextOrPrevObj(true); } -/// -/// An example of a method that gets the previous or next object and changes the object that we are editing -/// -/// +/// +/// An example of a method that gets the previous or next object and changes the object that we are editing +/// +/// private void GetNextOrPrevObj(bool next) { KeyGuid pk = (KeyGuid)((BaseWinEdit)Editor).DataObject.__PrimaryKey; - IDataService ds = DataServiceProvider.DataService; + IDataService ds = DataServiceProvider.DataService; // DataServiceProvider is deprecated; inject IDataService instead LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Планета), "Planetae"); lcs.ColumnsSort = new[] { new ColumnsSortDef("primaryKey", SortOrder.Asc) }; - lcs.ReturnTop = 1; - Function f = next ? FunctionBuilder.BuildGreater(pk) : FunctionBuilder.BuildLess(pk); + lcs.ReturnTop = 1; + Function f = next ? FunctionBuilder.BuildGreater(pk) : FunctionBuilder.BuildLess(pk); lcs.LimitFunction = f; DataObject[] dataObjects = ds.LoadObjects(lcs); if (dataObjects.Length > 0) { DataObject dataObject = dataObjects[0]; - //dataObject.LockObject("AnyKey"); Uncomment if the view in read-only mode + //dataObject.LockObject("AnyKey"); Uncomment if the view in read-only mode SwitchEditingObject(dataObject); } } -// *** End programmer edit section *** (Planete CustomMembers) +// *** End programmer edit section *** (Planete CustomMembers) ``` When you switch object logic works, the same logic close a form relevant to the request for saving a modified object, clearing the lock. Then everything works the same as the opening: checked lock, is installed or is proposed to open in read-only mode. If the user refuses to open a locked object read-only, then form tries to open the previous object completely by running logic on opening (in a method `PrepareDataObjectForEdit(ICSSoft.STORMNET.DataObject dobject)` happens zachitka object, if this logic is not overridden). diff --git a/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.ru.md b/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.ru.md index d7f559c67..f67493295 100644 --- a/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.ru.md +++ b/pages/products/flexberry-winforms/forms/editform/fw_edit-objects-on-forms.ru.md @@ -1,176 +1,176 @@ ---- -title: Редактирование объектов данных на формах -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, формы, контролы, объекты данных -summary: Переключение редактируемых объектов, ручное создание формы редактирования, обновление и межформенное взаимодействие при редактировании объекта -toc: true -permalink: ru/fw_edit-objects-on-forms.html -lang: ru ---- - -Редактирование объектов данных на формах имеет множество нюансов и возможностей. Наиболее распространенные изложены в данной статье. - -## Переключение редактируемого объекта без закрытия формы редактирования - -Иногда сценарий работы системы подразумевает последовательное переключение просматриваемых или редактируемых объектов на форме редактирования без закрытия самой этой формы. Аналогом такой функциональности является просмотр событий в системном логе Windows (EventLog). Flexberry Platform для организации данного сценария поддерживает специальную функцию, доступную из независимых форм редактирования: `SwitchEditingObject(newObject)`. -Типичная и рекомендуемая реализация со стороны прикладного проекта может быть выполнена следующим образом: - -* Зависимая форма включает интерфейсную часть по переключению объектов (имеется в виду пользовательский интерфейс: кнопки и прочие контролы). - -* Зависимая форма содержит события, которые генерирует интерфейсная часть (переход вперёд, назад, на указанный объект и пр.). Срабатывание этих событий привязано к соответствующим контролам. Пример: - -```csharp -/// -/// Делегат для события перемотки объектов -/// -/// -/// -public delegate void PrevNextEventArgsHandler(object sender, EventArgs e); - -//... -// *** Start programmer edit section *** (WinformПланетаE CustomMembers) -/// -/// Перемотка вперёд -/// -public event PrevNextEventArgsHandler NextEvent; -/// -/// Перемотка назад -/// -public event PrevNextEventArgsHandler PrevEvent; - -private void button1_Click(object sender, EventArgs e) -{ - if (NextEvent != null) - { - NextEvent(this, e); - } -} - -private void button2_Click(object sender, EventArgs e) -{ - if (PrevEvent != null) - { - PrevEvent(this, e); - } -} - -// *** End programmer edit section *** (WinformПланетаE CustomMembers) -``` - -* Независимая форма видит эти события, но через интерфейс (после кода класса независимой формы Flexberry генерирует интерфейс для определения событий методов и атрибутов зависимой формы) - -```csharp -/// -/// это определение интерфейса, от которого наследуется зависимая форма, но оно находится в файле независимой формы -/// -public interface DPDIПланетаE -{ - - // *** Start programmer edit section *** (DPDIПланетаE Members) - /// - /// Перемотка вперёд - /// - event PrevNextEventArgsHandler NextEvent; - /// - /// Перемотка назад - /// - event PrevNextEventArgsHandler PrevEvent; - - // *** End programmer edit section *** (DPDIПланетаE Members) - -} -``` - -* Независимая форма подписывается на эти дополнительные события зависимой формы в специальном методе `prv_AttachEventsFromDpdForm(object form)` - -```csharp -protected virtual void prv_AttachEventsFromDpdForm(object form) -{ - // *** Start programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) - IIS.AlteredHierarchy.DPDIПланетаE form1 = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); - form1.NextEvent -= new PrevNextEventArgsHandler(form1_NextEvent); - form1.NextEvent += new PrevNextEventArgsHandler(form1_NextEvent); - - form1.PrevEvent -= new PrevNextEventArgsHandler(form1_PrevEvent); - form1.PrevEvent += new PrevNextEventArgsHandler(form1_PrevEvent); - - // *** End programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) - IIS.AlteredHierarchy.DPDIПланетаE typedForm = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); -} - -//... -// *** Start programmer edit section *** (ПланетаE CustomMembers) -void form1_PrevEvent(object sender, EventArgs e) -{ - GetNextOrPrevObj(false); -} - -void form1_NextEvent(object sender, EventArgs e) -{ - GetNextOrPrevObj(true); -} - -/// -/// Пример метода, который получает предыдущий или последующий объект и переключает объект, который мы редактируем -/// -/// -private void GetNextOrPrevObj(bool next) -{ - KeyGuid pk = (KeyGuid)((BaseWinEdit)Editor).DataObject.__PrimaryKey; - IDataService ds = DataServiceProvider.DataService; - - LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Планета), "ПланетаE"); - lcs.ColumnsSort = new[] { new ColumnsSortDef("primaryKey", SortOrder.Asc) }; - lcs.ReturnTop = 1; - Function f = next ? FunctionBuilder.BuildGreater(pk) : FunctionBuilder.BuildLess(pk); - lcs.LimitFunction = f; - DataObject[] dataObjects = ds.LoadObjects(lcs); - if (dataObjects.Length > 0) - { - DataObject dataObject = dataObjects[0]; - //dataObject.LockObject("AnyKey"); Раскомментировать, если просмотр нужен в режиме только для чтения - - SwitchEditingObject(dataObject); - } -} -// *** End programmer edit section *** (ПланетаE CustomMembers) -``` - -При переключении объекта срабатывает логика, аналогичная логике закрытия формы, касающейся запроса о сохранении изменённого объекта, очистка блокировки. Дальше всё работает аналогично открытию: проверяется блокировка, устанавливается либо предлагается открыть в режиме только для чтения. Если пользователь откажется открыть заблокированный объект только на чтение, то форма попытается открыть предыдущий объект полностью выполнив логику по открытию (в методе `PrepareDataObjectForEdit(ICSSoft.STORMNET.DataObject dobject)` происходит зачитка объекта, если эта логика не переопределена). - -## Обновление локальной копии объекта формы - -При открытии формы на редактирование у нее создается локальная копия объекта. Вопрос о сохранении задается при различии этой локальной копии и редактируемого объекта данных. - -Возникают ситуации, когда объект в базе изменился во время редактирования формы, т.е. локальная копия формы устарела. В такой ситуации необходимо обновить локальную копию формы с помощью вызова метода `ResetDataObjectCopy` у независимой формы. В качестве параметра метода передается объект, который теперь будет являться локальной копией формы. - -## Создание формы редактирования объекта - -Существует несколько способов "ручного" создания формы редактирования объекта с возможностью связать ее со свойствами существующего объекта данных. Они подробно описаны в статье [Менеджер редактирования](fw_editmanager.html). - -## Работа на форме редактирования с полями нескольких объектов - -Иногда встаёт задача организовать работу с полями объектов разных классов на одной форме редактирования. Например, необходима форма для быстрого ввода, где часть полей принадлежит одному классу, часть - другому и т.д. В таком случае необходимо отслеживать сохранение этого "сложного представления". - -Одним из вариантов решения поставленной задачи может быть использование нескольких [EditManager](fw_editmanager.html). - -Для этого нужно создать объекты и привязать к ним `EditManager`. - -Логика сохранения объектов из "сложного представления" зависит от конкретной задачи (например, по каким полям определять, что такой же объект уже есть в базе, как интерпретировать изменение сохранённого объекта и прочее). При сохранении "сложного представления" необходимо обратить внимание на моменты, отмеченные в статьях: - -* [Обработка множества объектов (в т.ч. и разнотипных)](fo_processing-multiple-objects.html) -* [Обновление связанных объектов](fo_update-related-objects.html) - -## Межформенное взаимодействие при редактировании объектов - -В основном, взаимодействия происходят вызовом формы редактирования с формы списка (например, при открытии объекта на редактирование) и, наоборот, с формы редактирования на форму списка (например, для выбора связанного объекта). Так или иначе, суть состоит в том, что с одной формы на другую передаётся некоторый объект данных с целью его редактирования целиком, либо его части. Соответственно, в конкретном (относительном) межформенном взаимодействии одна форма выступает в качестве __инициатора__ редактирования, а вторая, — в качестве __редактора__. - -* Если объект открывается из списка на редактирование, форма списка — инициатор, а форма редактирования — редактор. В этом случае, очевидно — объект передаётся на редактирование в форму редактирования. -* Если из формы редактирования для выбора связанного объекта (мастерового) открывается форма списка, то форма редактирования — инициатор, а форма списка — редактор. - -Разница между случаями 1 и 2 лишь в том, что в случае 2 объект редактируется не целиком, а только его часть. - -## Полезные ссылки - -* [Чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html) -* [Универсальная форма редактирования](fw_editform.html) +--- +title: Редактирование объектов данных на формах +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, формы, контролы, объекты данных +summary: Переключение редактируемых объектов, ручное создание формы редактирования, обновление и межформенное взаимодействие при редактировании объекта +toc: true +permalink: ru/fw_edit-objects-on-forms.html +lang: ru +--- + +Редактирование объектов данных на формах имеет множество нюансов и возможностей. Наиболее распространенные изложены в данной статье. + +## Переключение редактируемого объекта без закрытия формы редактирования + +Иногда сценарий работы системы подразумевает последовательное переключение просматриваемых или редактируемых объектов на форме редактирования без закрытия самой этой формы. Аналогом такой функциональности является просмотр событий в системном логе Windows (EventLog). Flexberry Platform для организации данного сценария поддерживает специальную функцию, доступную из независимых форм редактирования: `SwitchEditingObject(newObject)`. +Типичная и рекомендуемая реализация со стороны прикладного проекта может быть выполнена следующим образом: + +* Зависимая форма включает интерфейсную часть по переключению объектов (имеется в виду пользовательский интерфейс: кнопки и прочие контролы). + +* Зависимая форма содержит события, которые генерирует интерфейсная часть (переход вперёд, назад, на указанный объект и пр.). Срабатывание этих событий привязано к соответствующим контролам. Пример: + +```csharp +/// +/// Делегат для события перемотки объектов +/// +/// +/// +public delegate void PrevNextEventArgsHandler(object sender, EventArgs e); + +//... +// *** Start programmer edit section *** (WinformПланетаE CustomMembers) +/// +/// Перемотка вперёд +/// +public event PrevNextEventArgsHandler NextEvent; +/// +/// Перемотка назад +/// +public event PrevNextEventArgsHandler PrevEvent; + +private void button1_Click(object sender, EventArgs e) +{ + if (NextEvent != null) + { + NextEvent(this, e); + } +} + +private void button2_Click(object sender, EventArgs e) +{ + if (PrevEvent != null) + { + PrevEvent(this, e); + } +} + +// *** End programmer edit section *** (WinformПланетаE CustomMembers) +``` + +* Независимая форма видит эти события, но через интерфейс (после кода класса независимой формы Flexberry генерирует интерфейс для определения событий методов и атрибутов зависимой формы) + +```csharp +/// +/// это определение интерфейса, от которого наследуется зависимая форма, но оно находится в файле независимой формы +/// +public interface DPDIПланетаE +{ + + // *** Start programmer edit section *** (DPDIПланетаE Members) + /// + /// Перемотка вперёд + /// + event PrevNextEventArgsHandler NextEvent; + /// + /// Перемотка назад + /// + event PrevNextEventArgsHandler PrevEvent; + + // *** End programmer edit section *** (DPDIПланетаE Members) + +} +``` + +* Независимая форма подписывается на эти дополнительные события зависимой формы в специальном методе `prv_AttachEventsFromDpdForm(object form)` + +```csharp +protected virtual void prv_AttachEventsFromDpdForm(object form) +{ + // *** Start programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) + IIS.AlteredHierarchy.DPDIПланетаE form1 = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); + form1.NextEvent -= new PrevNextEventArgsHandler(form1_NextEvent); + form1.NextEvent += new PrevNextEventArgsHandler(form1_NextEvent); + + form1.PrevEvent -= new PrevNextEventArgsHandler(form1_PrevEvent); + form1.PrevEvent += new PrevNextEventArgsHandler(form1_PrevEvent); + + // *** End programmer edit section *** (prv_AttachEventsFromDpdForm( object form )) + IIS.AlteredHierarchy.DPDIПланетаE typedForm = ((IIS.AlteredHierarchy.DPDIПланетаE)(form)); +} + +//... +// *** Start programmer edit section *** (ПланетаE CustomMembers) +void form1_PrevEvent(object sender, EventArgs e) +{ + GetNextOrPrevObj(false); +} + +void form1_NextEvent(object sender, EventArgs e) +{ + GetNextOrPrevObj(true); +} + +/// +/// Пример метода, который получает предыдущий или последующий объект и переключает объект, который мы редактируем +/// +/// +private void GetNextOrPrevObj(bool next) +{ + KeyGuid pk = (KeyGuid)((BaseWinEdit)Editor).DataObject.__PrimaryKey; + IDataService ds = DataServiceProvider.DataService; // DataServiceProvider устарел; вместо него используйте внедрение зависимостей + + LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Планета), "ПланетаE"); + lcs.ColumnsSort = new[] { new ColumnsSortDef("primaryKey", SortOrder.Asc) }; + lcs.ReturnTop = 1; + Function f = next ? FunctionBuilder.BuildGreater(pk) : FunctionBuilder.BuildLess(pk); + lcs.LimitFunction = f; + DataObject[] dataObjects = ds.LoadObjects(lcs); + if (dataObjects.Length > 0) + { + DataObject dataObject = dataObjects[0]; + //dataObject.LockObject("AnyKey"); Раскомментировать, если просмотр нужен в режиме только для чтения + + SwitchEditingObject(dataObject); + } +} +// *** End programmer edit section *** (ПланетаE CustomMembers) +``` + +При переключении объекта срабатывает логика, аналогичная логике закрытия формы, касающейся запроса о сохранении изменённого объекта, очистка блокировки. Дальше всё работает аналогично открытию: проверяется блокировка, устанавливается либо предлагается открыть в режиме только для чтения. Если пользователь откажется открыть заблокированный объект только на чтение, то форма попытается открыть предыдущий объект полностью выполнив логику по открытию (в методе `PrepareDataObjectForEdit(ICSSoft.STORMNET.DataObject dobject)` происходит зачитка объекта, если эта логика не переопределена). + +## Обновление локальной копии объекта формы + +При открытии формы на редактирование у нее создается локальная копия объекта. Вопрос о сохранении задается при различии этой локальной копии и редактируемого объекта данных. + +Возникают ситуации, когда объект в базе изменился во время редактирования формы, т.е. локальная копия формы устарела. В такой ситуации необходимо обновить локальную копию формы с помощью вызова метода `ResetDataObjectCopy` у независимой формы. В качестве параметра метода передается объект, который теперь будет являться локальной копией формы. + +## Создание формы редактирования объекта + +Существует несколько способов "ручного" создания формы редактирования объекта с возможностью связать ее со свойствами существующего объекта данных. Они подробно описаны в статье [Менеджер редактирования](fw_editmanager.html). + +## Работа на форме редактирования с полями нескольких объектов + +Иногда встаёт задача организовать работу с полями объектов разных классов на одной форме редактирования. Например, необходима форма для быстрого ввода, где часть полей принадлежит одному классу, часть - другому и т.д. В таком случае необходимо отслеживать сохранение этого "сложного представления". + +Одним из вариантов решения поставленной задачи может быть использование нескольких [EditManager](fw_editmanager.html). + +Для этого нужно создать объекты и привязать к ним `EditManager`. + +Логика сохранения объектов из "сложного представления" зависит от конкретной задачи (например, по каким полям определять, что такой же объект уже есть в базе, как интерпретировать изменение сохранённого объекта и прочее). При сохранении "сложного представления" необходимо обратить внимание на моменты, отмеченные в статьях: + +* [Обработка множества объектов (в т.ч. и разнотипных)](fo_processing-multiple-objects.html) +* [Обновление связанных объектов](fo_update-related-objects.html) + +## Межформенное взаимодействие при редактировании объектов + +В основном, взаимодействия происходят вызовом формы редактирования с формы списка (например, при открытии объекта на редактирование) и, наоборот, с формы редактирования на форму списка (например, для выбора связанного объекта). Так или иначе, суть состоит в том, что с одной формы на другую передаётся некоторый объект данных с целью его редактирования целиком, либо его части. Соответственно, в конкретном (относительном) межформенном взаимодействии одна форма выступает в качестве __инициатора__ редактирования, а вторая, — в качестве __редактора__. + +* Если объект открывается из списка на редактирование, форма списка — инициатор, а форма редактирования — редактор. В этом случае, очевидно — объект передаётся на редактирование в форму редактирования. +* Если из формы редактирования для выбора связанного объекта (мастерового) открывается форма списка, то форма редактирования — инициатор, а форма списка — редактор. + +Разница между случаями 1 и 2 лишь в том, что в случае 2 объект редактируется не целиком, а только его часть. + +## Полезные ссылки + +* [Чтение принадлежащих различным классам объектов в одном представлении](fo_reading-several-types-objects.html) +* [Универсальная форма редактирования](fw_editform.html) diff --git a/pages/products/flexberry-winforms/forms/editform/fw_editform.en.md b/pages/products/flexberry-winforms/forms/editform/fw_editform.en.md index ebfe392aa..d9f985b8c 100644 --- a/pages/products/flexberry-winforms/forms/editform/fw_editform.en.md +++ b/pages/products/flexberry-winforms/forms/editform/fw_editform.en.md @@ -149,12 +149,12 @@ However, by default generates a separate form to display a hierarchy (in this ca * Add to the form in Designer `Form Fields`: ```csharp -// *** Start programmer edit section *** (Form Designer Fields) +// *** Start programmer edit section *** (Form Designer Fields) - //... + //... private ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView objectHierarchicalView1; -// *** End programmer edit section *** (Form Designer Fields) +// *** End programmer edit section *** (Form Designer Fields) ``` * Next, you should amend `InitializeComponent`. @@ -167,12 +167,12 @@ For correct display `ObjectHierarchicalView` need to set all the properties of t private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WinformTestHierarchicalForm)); - //... + //... this.objectHierarchicalView1 = new ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView(); - // - // objectHierarchicalView1 - // + // + // objectHierarchicalView1 + // this.objectHierarchicalView1.AdvansedColumns = null; this.objectHierarchicalView1.AdvansedMarks = false; this.objectHierarchicalView1.AllowSorting = true; @@ -187,7 +187,7 @@ For correct display `ObjectHierarchicalView` need to set all the properties of t this.objectHierarchicalView1.FillDataOnLoadUserAllowed = true; this.objectHierarchicalView1.GrayedOnLoad = true; this.objectHierarchicalView1.HideToolBar = false; - this.objectHierarchicalView1.HierarchicalMasterName = Hierarchy; //The name of the workman of the object specified in the HierarchicalMaster list form*. + this.objectHierarchicalView1.HierarchicalMasterName = Hierarchy; //The name of the workman of the object specified in the HierarchicalMaster list form*. this.objectHierarchicalView1.Limit = null; this.objectHierarchicalView1.LoadingPackageSize = 500; this.objectHierarchicalView1.Location = new System.Drawing.Point(10, 100); @@ -213,7 +213,7 @@ For correct display `ObjectHierarchicalView` need to set all the properties of t this.objectHierarchicalView1.UseHotkeyForEdit = true; this.objectHierarchicalView1.UseLimitFunctionExtension = false; this.objectHierarchicalView1.UseToolBar = null; - this.objectHierarchicalView1.ViewName = "ТерриторияL";//The view name that is used in a hierarchical list. + this.objectHierarchicalView1.ViewName = "ТерриторияL";//The view name that is used in a hierarchical list. ``` ## Recommendations for improvement of forms edit @@ -256,7 +256,7 @@ Call edit form ```csharp Объект oОбъект = new Объект(); oОбъект.__PrimaryKey = 'чего-то там'; -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); // DataServiceProvider is deprecated; inject IDataService instead ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); cont.Edit(oОбъект, "", ""); @@ -267,7 +267,7 @@ If you want the functionality to preserve object when pressing on the button "Sa ```csharp Объект oОбъект = new Объект(); oОбъект.__PrimaryKey = 'чего-то там'; -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); // DataServiceProvider is deprecated; inject IDataService instead ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); cont.SaveEvent += (sr, ea) => { new BusinessService().UpdateObject(ea.dataobject); }; @@ -289,28 +289,28 @@ arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(IIS.LimitsTesting_Blog.LTB_Б Parameter in list form gets in the method `Activate(object tag)`. You should pay attention to the number of parameters in the overloaded method `OnNewEvent()`. You should overload a method with two parameters but call it method three. Default object creation occurs without the transfer of the tag. ```csharp -// *** Start programmer edit section *** (LTB_БлогL CustomMembers) +// *** Start programmer edit section *** (LTB_БлогL CustomMembers) private object _tagFromRunner; public override void Activate(object tag) { _tagFromRunner = tag; - // MessageBox.Show("Activate" (tag??"")); + // MessageBox.Show("Activate" (tag??"")); base.Activate(tag); } protected override void OnNewEvent(Type dataobjecttype, string contpath) { - // MessageBox.Show("OnNewEvent"); + // MessageBox.Show("OnNewEvent"); base.OnNewEvent(dataobjecttype, contpath, _tagFromRunner); } protected override void OnEditEvent(string propertyname, ICSSoft.STORMNET.DataObject dataobject, string contpath, object tag) { - // MessageBox.Show("OnEditEvent" (tag ?? "")); + // MessageBox.Show("OnEditEvent" (tag ?? "")); base.OnEditEvent(propertyname, dataobject, contpath, _tagFromRunner); } -// *** End programmer edit section *** (LTB_БлогL CustomMembers) +// *** End programmer edit section *** (LTB_БлогL CustomMembers) ``` ### Receiving option on the edit form @@ -318,13 +318,13 @@ protected override void OnEditEvent(string propertyname, ICSSoft.STORMNET.DataOb In the method `Edit` with the largest number of options comes the same tag. ```csharp -// *** Start programmer edit section *** (WinformLTB_БлогE CustomMembers) +// *** Start programmer edit section *** (WinformLTB_БлогE CustomMembers) public override void Edit(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname, object tag) { - // MessageBox.Show("Blog tag:" (tag??"")); + // MessageBox.Show("Blog tag:" (tag??"")); base.Edit(dataobject, contpath, propertyname, tag); } -// *** End programmer edit section *** (WinformLTB_БлогE CustomMembers) +// *** End programmer edit section *** (WinformLTB_БлогE CustomMembers) ``` ## Related articles diff --git a/pages/products/flexberry-winforms/forms/editform/fw_editform.ru.md b/pages/products/flexberry-winforms/forms/editform/fw_editform.ru.md index 91c852ee8..818849e67 100644 --- a/pages/products/flexberry-winforms/forms/editform/fw_editform.ru.md +++ b/pages/products/flexberry-winforms/forms/editform/fw_editform.ru.md @@ -1,330 +1,330 @@ ---- -title: Формы редактирования (классы со стереотипом editform) -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, формы, форма редактирования -summary: Особенности генерации, свойства, атрибуты, методы, интерфейсы формы редактирования, универсальная форма редактирования, использование иерархического списка на форме редактирования, рекомендации -toc: true -permalink: ru/fw_editform.html -lang: ru ---- - -Описание среды `Flexberry` относительно пользовательского интерфейса изложено в [Учебник программиста Flexberry Platform](gbt_flexberry-platform-guide.html) раздел "Пользовательский интерфейс "(пункт 45-65). - -Форма редактирования обеспечивает пользовательский интерфейс по вводу/редактированию экземпляра объекта данных в одном, либо нескольких представлениях. - -Для описания формы редактирования необходимо создать в CASE UML-класс со стереотипом "editform". Например: - -![Пример формы редактирования на диаграмме](/images/pages/products/flexberry-winforms/forms/editform.png) - -## Что генерируется - -* Класс UI-независимой формы редактирования, наследующийся от ICSSoft.STORMNET.UI.BaseIndpdEdit. -* .Net-интерфейс для зависимой формы редактирования. -* UI-зависимая форма редактирования (если необходимо). -* Атрибуты формы генерируются следующим образом: - - * Если включена генерация UI-зависимой формы, то генерируется .Net-интерфейс UI-зависимой формы редактирования с определением свойства, но только, если этот атрибут публичный. - * В код UI-зависимой формы генерируется реализующее вышеуказанное интерфейсное определение виртуального свойства, а также приватный член и в обоих аксессорах код по установке/получению значения приватного члена, сопровождаемый скобками программиста. - * В код UI-независимой формы генерируется определение виртуального свойства с указанным модификатором. Если генерация UI-зависимой формы включена, то в код свойства генерируется вызов того же свойства UI-зависимой формы через интерфейс. - * Методы формы генерируются следующим образом: - - * Если включена генерация UI-зависимой формы, то генерируется .Net-интерфейс UI-зависимой формы редактирования с определением метода, но только, если этот метод публичный. - * В код UI-зависимой формы генерируется реализующий вышеуказанное интерфейсное определение виртуальный метод и в нём скобка программиста (подобно тому, как описано в статье [Методы классов и параметры методов](fd_methods-parameters.html)). - * В код UI-независимой формы генерируется определение виртуального метода с указанным модификатором. Если генерация UI-зависимой формы включена, то в код метода генерируется вызов того же метода UI-зависимой формы через интерфейс. - -## Дополнительно редактируемые свойства и что как генерируется - -Самое главное в дополнительно редактируемых свойствах - выбор класса и представления, в котором должен редактироваться объект этого класса. Указание этого производится на закладке "Составные представления": - -![Представления для формы редактирования](/images/pages/products/flexberry-winforms/forms/editformviews.jpg) - -В `Flexberry Plugins` можно указать только один класс и одно представление, в котором должен редактироваться объект на этой форме. Если указать несколько классов и/или представлений, все, кроме первого, будут проигнорированы. - -Итак, для того, чтобы выбрать класс и представление, нужно нажать на кнопку "...": - -![Выбор представления](/images/pages/products/flexberry-winforms/forms/view-sel.jpg) - -### Закладка "Форма" - -![Свойства формы редактирования](/images/pages/products/flexberry-winforms/forms/editformprops.jpg) - -| Свойство-Описание | Генерация в .Net-язык | -|--|--| -| `Name` - имя UML-класса | Имя .Net-класса независимой формы и производное от него для зависимой (например, ```winform[Name]```). -| `Description` - некоторое описание класса.| `DocComment` перед определением класса независимой формы -| `Caption` - некоторое пользовательское имя (отображается в пользовательском интерфейсе)| Заголовок на форме -| `GenerateDependedForm`| Если галочка установлена, - генерируется UI-зависимая (WinForm) форма пользовательского интерфейса в исходном коде, что позволяет "вручную" разместить на форме элементы управления. Если галочка не установлена, используется универсальная UI-независимая форма редактирования, на которой элементы управления, соответствующие атрибутам в представлении размещаются автоматически. -| `FixDependedForm`| Если галочка установлена, - UI-зависимая (WinForm) форма не перегенерируется. Это сделано для уверенности в том, что внесённые в форму изменения в части состава и расположения элементов управления не будут потеряны, что иногда происходит из-за наличия (к сожалению) ошибок в среде `Visual Studio .Net`.
Если галочка не установлена генерация происходит следующим образом:
1. Если представление (его имя и атрибутный состав) не изменилось, тогда перегенерируется невизуальная часть формы (методы, свойства и т.д.);
2. Если полностью изменилось представление (его имя, т.е. после последней генерации было указано другое используемое представление), то визуальная часть перегенерируется полностью, все элементы управления удаляются и размещаются новые в соответствии с новым представлением.
3. Если изменился атрибутный состав представления, то на форму добавляются элементы управления, соответствующие добавленным в представление атрибутам. Эл-ты управления, соотв. удалённым атрибутам не уничтожаются на форме. -| `Packet, NamespacePostfix` - позволяют настроить сборку и пространство имен | см. [Расположение сборок после генерации кода](fo_location-assembly.html). -| `PBCustomAttributes` - позволяет указать, необходима ли скобка программиста непосредственно перед описанием класса для "ручного" внесения атрибутов | Если галочка указана - генерируется скобка программиста для "ручного" внесения .Net атрибутов перед классом независимой формы. -| `PBMembers`| Если галочка указана - генерируется скобка программиста для "ручного" внесения членов класса независимой формы. -| `PropertyLookup`| Позволяет на отдельной форме настроить, какие списковые формы должны открываться с этой формы для выбора соответствующих связанных объектов (мастеров). -| `EditFormOperations`| Настройка доступных на форме операций. -| `PrintContainer` - имя класса со стереотипом `printform`, являющегося печатной формой, которая используется при печати с формы редактирования.| В коде независимой формы генерируется перегрузка метода GetPrinter, в котором:
* Если `PrintContainer` не указан, возвращается ошибка `NoSuchContainerException`;
* Если `PrintContainer` указан, возвращается тип контейнера;
В этом методе перед возвратом значения располагается неотключаемая скобка программиста, в которой можно закодировать "вручную" возвращаемый тип в случае наличия логики, которая, например, возвращает печатную форму в зависимости от свойств объекта. -| `ScriptName` - имя сценария, который должен использоваться этой формой. Соответствует имени EBSD-диаграммы, использующейся для описания сценария.| Метод `GetScript` в классе независимой формы перегружается таким образом, что возвращает из провайдера сценариев сценарий с указанным именем. -| `PublishToEBSD`| Если галочка указана - перед классом независимой формы генерируется указание атрибута `PublishToEBSDAttribute`, который указывает доступность данного класса для использования в редакторе диаграмм сценариев.| - -#### PropertyLookup - -`PropertyLookup` генерируется в код метода `GetEditor` UI-независимой формы редактирования, который и возвращает тип списковой формы в зависимости от имени мастерового свойства. - -![PropertyLookup](/images/pages/products/flexberry-winforms/forms/propertylookup.jpg) - -В верхнем списке расположены мастеровые свойства, в нижнем выпадающем списке следует выбрать форму, которая должна открываться для выбора пользователем соотв. связанного объекта. - -#### EditFormOperations - -Позволяет указать, какие операции доступны на этой форме (соответственно, какие кнопки появляются на панели управления): - -* `Save` - сохранение; -* `Save and Close` - сохранение с последующим закрытием формы; -* `Print` - печать; -* `Print preview` - предварительный просмотр. - -![EditFormOperations](/images/pages/products/flexberry-winforms/forms/editformoperations.jpg) - -Генерируется: - -* Если используется универсальная форма (галочка `GenerateDependedForm` не установлена), генерируется параметром при вызове конструктора зависимой формы в методе `GetDpdForm()` независимой формы; -* Если используется генерируемая форма, генерируется напрямую в зависимой форме установкой видимости кнопок панели инструментов. - -### Свойства атрибутов - -Свойства атрибутов аналогичны указанным в статье [Атрибуты классов данных](fo_attributes-class-data.html), с учётом вышеуказанных (в п 4 "Что генерируется") замечаний. - -### Свойства методов - -Свойства методов аналогичны указанным в статье [Методы классов и параметры методов](fd_methods-parameters.html), с учётом вышеуказанных (в п 5"Что генерируется") замечаний. - -## Универсальная форма редактирования - -Конечно, можно «вручную» размещать контролы и связывать их через `EditManager` с объектами данных, однако, для облегчения этого труда, существует универсальная форма редактирования, которая автоматически, по указанию типа объекта данных, представлений, размещает элементы управления и обеспечивает пользователя интерфейсом по редактированию объекта данных (панель инструментов, строка статуса). - -Для того чтобы использовать универсальную форму редактирования, необходимо: - -* Конструировать универсальную форму редактирования, передав в конструктор параметром представления, в которых должно осуществляться редактирование: - -```csharp -StormNetUI.IDpdEditForm editcont = new StormNetUI.UniWinEdit(new StormNet.View[]{viewforedit}); -``` - -* Установить обработчики на события (как минимум, на `CloseEvent`, чтобы можно было закрыть форму и `SaveEvent`, чтобы «отловить» вызов пользователем сохранения). -* Вызвать метод Edit, передавая объект данных. - -Следует понимать, что форма реализует абсолютно «голый» пользовательский интерфейс, вся реакция от пользователя транслируется «наружу» формы через события, соответственно, эта управление формой производится через набор методов. Так, когда пользователь просто закрывает форму редактирования, посылается сообщение `CloseEvent`, но сама форма не закрывается. Чтобы закрыть форму, необходимо вызвать метод `Close`. - -_Пример обработчика события `CloseEvent`:_ - -```csharp -private void ContainerCloseHandler (object sender, StormNetUI.CloseEventArgs args) - { - ((StormNetUI.IDpdForm)sender).CloseForm(); - } -``` - -{% include note.html content="Если необходимо выполнить переход на генерируемую форму с универсальной с контролами ICustomizable, метод Customize необходимо вызвать вручную в перегруженном методе Edit." %} - -## Фокус ввода и «Ctrl+S» - -При сохранении формы редактирования по комбинации __«Ctrl+S»__ фокус остается на активном контроле, текущее значение попадает в объект данных с помощью вызова `EditManager.ApplyDataFromControl(ActiveControl)`. - -## Интерфейсы форм редактирования - -Нижеприведённая диаграмма показывает интерфейсы для инициатора, для редактора: -![Интерфейсы формы редактирования](/images/pages/products/flexberry-winforms/forms/primer10.jpg) - -## Создание формы редактирования с иерархическим списком - -Бывают случаи, когда на форме редактирования необходимо создать иерархический список. - -Например, в модели иерархический список выглядит так: - -![Пример иерархического списка](/images/pages/products/flexberry-winforms/controls/olv/object-hierarchical-view.png) - -Однако по-умолчанию генерируется отдельная форма для отображения иерархии (в данном случае, "Территория)". Для того чтобы иерархический список был отображен на форме редактирования, на форму необходимо добавить контрол `ObjectHierarchicalView`. Чтобы это сделать следует выполнить ряд действий: - -* Сгенерировать форму редактирования. -* Добавить на форму в `Form Designer Fields`: - -```csharp -// *** Start programmer edit section *** (Form Designer Fields) - - //... - private ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView objectHierarchicalView1; - -// *** End programmer edit section *** (Form Designer Fields) -``` - -* Далее следует внести дополнения в `InitializeComponent`. - - * Дополнения InitializeComponent - -Для корректного отображения `ObjectHierarchicalView` необходимо правильно прописать все свойства контрола. - -```csharp - private void InitializeComponent() -{ - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WinformTestHierarchicalForm)); - //... - this.objectHierarchicalView1 = new ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView(); - - // - // objectHierarchicalView1 - // - this.objectHierarchicalView1.AdvansedColumns = null; - this.objectHierarchicalView1.AdvansedMarks = false; - this.objectHierarchicalView1.AllowSorting = true; - this.objectHierarchicalView1.AutoRefreshSupport = false; - this.objectHierarchicalView1.DataObjectTypes = new System.Type[] { - ((System.Type)(typeof(IIS.TestStandWinforms.Территория)))}; - this.objectHierarchicalView1.DataService = null; - this.objectHierarchicalView1.Dock = System.Windows.Forms.DockStyle.None; - this.objectHierarchicalView1.DrawGrid = false; - this.objectHierarchicalView1.ExtendLastCol = true; - this.objectHierarchicalView1.FillDataOnLoad = true; - this.objectHierarchicalView1.FillDataOnLoadUserAllowed = true; - this.objectHierarchicalView1.GrayedOnLoad = true; - this.objectHierarchicalView1.HideToolBar = false; - this.objectHierarchicalView1.HierarchicalMasterName = "Иерархия"; //Имя мастерового объекта, указывается в поле HierarchicalMaster списковой формы*. - this.objectHierarchicalView1.Limit = null; - this.objectHierarchicalView1.LoadingPackageSize = 500; - this.objectHierarchicalView1.Location = new System.Drawing.Point(10, 100); - this.objectHierarchicalView1.MemoryTimeLoadLimit = ((long)(200)); - this.objectHierarchicalView1.Name = "objectHierarchicalView1"; - this.objectHierarchicalView1.NodesStyle = ((ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle)((ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle.Lines | ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle.Symbols))); - this.objectHierarchicalView1.RowCountQuery = 12345; - this.objectHierarchicalView1.SaveExpandedRows = false; - this.objectHierarchicalView1.ShowCyclicalReferencedObjects = false; - this.objectHierarchicalView1.ShowStatusBar = true; - this.objectHierarchicalView1.ShowToolTip = false; - this.objectHierarchicalView1.ShowTreeColumnName = ""; - this.objectHierarchicalView1.Size = new System.Drawing.Size(600, 322); - this.objectHierarchicalView1.TabIndex = 6; - this.objectHierarchicalView1.TreeLeafImage = null; - this.objectHierarchicalView1.TreeLineColor = System.Drawing.Color.DarkGray; - this.objectHierarchicalView1.TreeLineStyle = System.Drawing.Drawing2D.DashStyle.Dot; - this.objectHierarchicalView1.TreeNodeImage = null; - this.objectHierarchicalView1.TreeNodeImageCollapsed = null; - this.objectHierarchicalView1.TreeNodeImageExpanded = null; - this.objectHierarchicalView1.UseAlternativeColoring = false; - this.objectHierarchicalView1.UseColumnOptimization = false; - this.objectHierarchicalView1.UseHotkeyForEdit = true; - this.objectHierarchicalView1.UseLimitFunctionExtension = false; - this.objectHierarchicalView1.UseToolBar = null; - this.objectHierarchicalView1.ViewName = "ТерриторияL";//Имя представления, которое используется на иерархическом списке. -``` - -## Рекомендации по доработке форм редактирования - -Важно понимать, что форма служит не только для редактирования данных, но и для просмотра данных, а также для управления данными - запуск операции экспорта, печати, работы с данными аудита и прочее. - -Поэтому проработку внешнего вида лучше начинать с того, что следует определить какие задачи пользователи будут выполнять с помощью формы. Основные - уже перечислены, это: редактирование, просмотр, выполенение операций над объектом, редактируемым на форме (экспорт, печать и прочее). - -Для того чтобы сделать форму удобной для ввода, следует обратить внимание на следующие моменты: - -* порядок обхода (переход по Tab), -* визуальное выделение фокуса - неопытные пользователи могут даже и не знать, что такое фокус ввода и что он отображется мигающей вертикальной чертой в поле ввода, -* [предиктивный ввод](fw_predict-input.html), -* отображение полей, обязательных для ввода.
Вариант реализации: через [DataObjectErrorProvider](fw_edit-form-validation.html). DataObjectErrorProvider позволит быстро и со вкусом прописать в коде перечень обязательных полей и пользователи приложения не смогут его менять. -* значения по умолчанию, -* автоматизация ввода пользовательских данных, например, ввод адреса или возможность ввести ключевые реквизиты другого объекта данных с возможностью автоматического поиска. - -Для облегчения просмотра и поиска глазами на форме нужных данных применяются следующие механизмы: - -* объединение элементов управления в логические группы (GroupBox) с указанием названия группы - общего признака всех атрибутов в этой группе, -* расположение контролов по сетке в несколько столбцов и строк. ширина полей ввода в одном столбце должна быть одинаковой, заголовки полей в столбцах начинаются с одной позиции в строке, -* увеличения шрифта. Бывают случаи, когда шрифт должен быть увеличен (например, когда большинство пользователей этой формы - пожилые люди с плохим зрением), -* реализация работы формы редактирования в режиме "[Только на чтение](fw_editmanager.html)" . Здесь работа заключается в проверке, что ненужные функции заблокированы, а нужные работают корректно. - -Для выполнения операций над данными зачастую используется панель инструментов, на которой по умолчанию есть кнопки "Сохранить" и "Сохранить и закрыть". Для каждой операции лучше создавать отдельную кнопку на этой панели с чёткой иконкой, лаконичной надписью и понятной всплывающей подсказкой (tooltip). Между кнопками используйте вертикальный разделитель. - -Расположение контролов на форме и группировка их в группы - комплексная задача, которая должна решаться совместно с аналитиком. - -Также формы редактирования могут предоставлять следующие универсальные сервисы: - -* аудирование изменений данных и предоставление доступа к данным аудита, -* проверка данных на соблюдение пользовательских условий, -* разграничение доступа к данным с помощью системы полномочий, -* хранение пользовательских настроек. - -## Принудительный вызов формы редактирования - -Вызов формы редактирования - -```csharp -Объект oОбъект = new Объект(); -oОбъект.__PrimaryKey = 'чего-то там'; -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); -ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); -ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); -cont.Edit(oОбъект, "", ""); -``` - -Если требуется функциональность по сохранению объекта при нажатию на кнопку "Сохранить" или "Сохранить и закрыть" на зависимой форме, то код будет выглядеть таким образом: - -```csharp -Объект oОбъект = new Объект(); -oОбъект.__PrimaryKey = 'чего-то там'; -ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); -ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); -ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); -cont.SaveEvent += (sr, ea) => { new BusinessService().UpdateObject(ea.dataobject); }; -cont.Edit(oОбъект, "", ""); -``` - -## Передача параметров от ContRunner до формы редактирования - -### Передача параметров в DesktopCustomizer - -Для того чтобы передать параметр контейнеру запуска, необходимо использовать перегруженный метод создания `ContRunner`. - -```csharp -arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(IIS.LimitsTesting_Blog.LTB_БлогL), "MyTag1FromContRunner", "LimitsTesting_Blog", "Блог", "")); -``` - -### Приём параметра в списковой форме и передача на форму редактирования - -Параметр в списковую форму попадает в метод `Activate(object tag)`. Следует обращать внимание на количество параметров в перегруженном методе `OnNewEvent()`. Перегрузить следует метод с двумя параметрами, а вызвать в нём метод с тремя. По-умолчанию создание объектов происходит без передачи тега. - -```csharp -// *** Start programmer edit section *** (LTB_БлогL CustomMembers) -private object _tagFromRunner; - -public override void Activate(object tag) -{ - _tagFromRunner = tag; - // MessageBox.Show("Activate " + (tag??"<пусто>")); - base.Activate(tag); -} - -protected override void OnNewEvent(Type dataobjecttype, string contpath) -{ - // MessageBox.Show("OnNewEvent"); - base.OnNewEvent(dataobjecttype, contpath, _tagFromRunner); -} - -protected override void OnEditEvent(string propertyname, ICSSoft.STORMNET.DataObject dataobject, string contpath, object tag) -{ - // MessageBox.Show("OnEditEvent " + (tag ?? "<пусто>")); - base.OnEditEvent(propertyname, dataobject, contpath, _tagFromRunner); -} -// *** End programmer edit section *** (LTB_БлогL CustomMembers) -``` - -### Приём параметра на форме редактирования - -В метод `Edit` с самым большим числом параметров придёт тот самый тег. - -```csharp -// *** Start programmer edit section *** (WinformLTB_БлогE CustomMembers) -public override void Edit(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname, object tag) -{ - // MessageBox.Show("БлогE tag: " + (tag??"<пусто>")); - base.Edit(dataobject, contpath, propertyname, tag); -} -// *** End programmer edit section *** (WinformLTB_БлогE CustomMembers) -``` - -## Связанные статьи - -[E-представление](fd_e-view.html) +--- +title: Формы редактирования (классы со стереотипом editform) +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, формы, форма редактирования +summary: Особенности генерации, свойства, атрибуты, методы, интерфейсы формы редактирования, универсальная форма редактирования, использование иерархического списка на форме редактирования, рекомендации +toc: true +permalink: ru/fw_editform.html +lang: ru +--- + +Описание среды `Flexberry` относительно пользовательского интерфейса изложено в [Учебник программиста Flexberry Platform](gbt_flexberry-platform-guide.html) раздел "Пользовательский интерфейс "(пункт 45-65). + +Форма редактирования обеспечивает пользовательский интерфейс по вводу/редактированию экземпляра объекта данных в одном, либо нескольких представлениях. + +Для описания формы редактирования необходимо создать в CASE UML-класс со стереотипом "editform". Например: + +![Пример формы редактирования на диаграмме](/images/pages/products/flexberry-winforms/forms/editform.png) + +## Что генерируется + +* Класс UI-независимой формы редактирования, наследующийся от ICSSoft.STORMNET.UI.BaseIndpdEdit. +* .Net-интерфейс для зависимой формы редактирования. +* UI-зависимая форма редактирования (если необходимо). +* Атрибуты формы генерируются следующим образом: + + * Если включена генерация UI-зависимой формы, то генерируется .Net-интерфейс UI-зависимой формы редактирования с определением свойства, но только, если этот атрибут публичный. + * В код UI-зависимой формы генерируется реализующее вышеуказанное интерфейсное определение виртуального свойства, а также приватный член и в обоих аксессорах код по установке/получению значения приватного члена, сопровождаемый скобками программиста. + * В код UI-независимой формы генерируется определение виртуального свойства с указанным модификатором. Если генерация UI-зависимой формы включена, то в код свойства генерируется вызов того же свойства UI-зависимой формы через интерфейс. + * Методы формы генерируются следующим образом: + + * Если включена генерация UI-зависимой формы, то генерируется .Net-интерфейс UI-зависимой формы редактирования с определением метода, но только, если этот метод публичный. + * В код UI-зависимой формы генерируется реализующий вышеуказанное интерфейсное определение виртуальный метод и в нём скобка программиста (подобно тому, как описано в статье [Методы классов и параметры методов](fd_methods-parameters.html)). + * В код UI-независимой формы генерируется определение виртуального метода с указанным модификатором. Если генерация UI-зависимой формы включена, то в код метода генерируется вызов того же метода UI-зависимой формы через интерфейс. + +## Дополнительно редактируемые свойства и что как генерируется + +Самое главное в дополнительно редактируемых свойствах - выбор класса и представления, в котором должен редактироваться объект этого класса. Указание этого производится на закладке "Составные представления": + +![Представления для формы редактирования](/images/pages/products/flexberry-winforms/forms/editformviews.jpg) + +В `Flexberry Plugins` можно указать только один класс и одно представление, в котором должен редактироваться объект на этой форме. Если указать несколько классов и/или представлений, все, кроме первого, будут проигнорированы. + +Итак, для того, чтобы выбрать класс и представление, нужно нажать на кнопку "...": + +![Выбор представления](/images/pages/products/flexberry-winforms/forms/view-sel.jpg) + +### Закладка "Форма" + +![Свойства формы редактирования](/images/pages/products/flexberry-winforms/forms/editformprops.jpg) + +| Свойство-Описание | Генерация в .Net-язык | +|--|--| +| `Name` - имя UML-класса | Имя .Net-класса независимой формы и производное от него для зависимой (например, ```winform[Name]```). +| `Description` - некоторое описание класса.| `DocComment` перед определением класса независимой формы +| `Caption` - некоторое пользовательское имя (отображается в пользовательском интерфейсе)| Заголовок на форме +| `GenerateDependedForm`| Если галочка установлена, - генерируется UI-зависимая (WinForm) форма пользовательского интерфейса в исходном коде, что позволяет "вручную" разместить на форме элементы управления. Если галочка не установлена, используется универсальная UI-независимая форма редактирования, на которой элементы управления, соответствующие атрибутам в представлении размещаются автоматически. +| `FixDependedForm`| Если галочка установлена, - UI-зависимая (WinForm) форма не перегенерируется. Это сделано для уверенности в том, что внесённые в форму изменения в части состава и расположения элементов управления не будут потеряны, что иногда происходит из-за наличия (к сожалению) ошибок в среде `Visual Studio .Net`.
Если галочка не установлена генерация происходит следующим образом:
1. Если представление (его имя и атрибутный состав) не изменилось, тогда перегенерируется невизуальная часть формы (методы, свойства и т.д.);
2. Если полностью изменилось представление (его имя, т.е. после последней генерации было указано другое используемое представление), то визуальная часть перегенерируется полностью, все элементы управления удаляются и размещаются новые в соответствии с новым представлением.
3. Если изменился атрибутный состав представления, то на форму добавляются элементы управления, соответствующие добавленным в представление атрибутам. Эл-ты управления, соотв. удалённым атрибутам не уничтожаются на форме. +| `Packet, NamespacePostfix` - позволяют настроить сборку и пространство имен | см. [Расположение сборок после генерации кода](fo_location-assembly.html). +| `PBCustomAttributes` - позволяет указать, необходима ли скобка программиста непосредственно перед описанием класса для "ручного" внесения атрибутов | Если галочка указана - генерируется скобка программиста для "ручного" внесения .Net атрибутов перед классом независимой формы. +| `PBMembers`| Если галочка указана - генерируется скобка программиста для "ручного" внесения членов класса независимой формы. +| `PropertyLookup`| Позволяет на отдельной форме настроить, какие списковые формы должны открываться с этой формы для выбора соответствующих связанных объектов (мастеров). +| `EditFormOperations`| Настройка доступных на форме операций. +| `PrintContainer` - имя класса со стереотипом `printform`, являющегося печатной формой, которая используется при печати с формы редактирования.| В коде независимой формы генерируется перегрузка метода GetPrinter, в котором:
* Если `PrintContainer` не указан, возвращается ошибка `NoSuchContainerException`;
* Если `PrintContainer` указан, возвращается тип контейнера;
В этом методе перед возвратом значения располагается неотключаемая скобка программиста, в которой можно закодировать "вручную" возвращаемый тип в случае наличия логики, которая, например, возвращает печатную форму в зависимости от свойств объекта. +| `ScriptName` - имя сценария, который должен использоваться этой формой. Соответствует имени EBSD-диаграммы, использующейся для описания сценария.| Метод `GetScript` в классе независимой формы перегружается таким образом, что возвращает из провайдера сценариев сценарий с указанным именем. +| `PublishToEBSD`| Если галочка указана - перед классом независимой формы генерируется указание атрибута `PublishToEBSDAttribute`, который указывает доступность данного класса для использования в редакторе диаграмм сценариев.| + +#### PropertyLookup + +`PropertyLookup` генерируется в код метода `GetEditor` UI-независимой формы редактирования, который и возвращает тип списковой формы в зависимости от имени мастерового свойства. + +![PropertyLookup](/images/pages/products/flexberry-winforms/forms/propertylookup.jpg) + +В верхнем списке расположены мастеровые свойства, в нижнем выпадающем списке следует выбрать форму, которая должна открываться для выбора пользователем соотв. связанного объекта. + +#### EditFormOperations + +Позволяет указать, какие операции доступны на этой форме (соответственно, какие кнопки появляются на панели управления): + +* `Save` - сохранение; +* `Save and Close` - сохранение с последующим закрытием формы; +* `Print` - печать; +* `Print preview` - предварительный просмотр. + +![EditFormOperations](/images/pages/products/flexberry-winforms/forms/editformoperations.jpg) + +Генерируется: + +* Если используется универсальная форма (галочка `GenerateDependedForm` не установлена), генерируется параметром при вызове конструктора зависимой формы в методе `GetDpdForm()` независимой формы; +* Если используется генерируемая форма, генерируется напрямую в зависимой форме установкой видимости кнопок панели инструментов. + +### Свойства атрибутов + +Свойства атрибутов аналогичны указанным в статье [Атрибуты классов данных](fo_attributes-class-data.html), с учётом вышеуказанных (в п 4 "Что генерируется") замечаний. + +### Свойства методов + +Свойства методов аналогичны указанным в статье [Методы классов и параметры методов](fd_methods-parameters.html), с учётом вышеуказанных (в п 5"Что генерируется") замечаний. + +## Универсальная форма редактирования + +Конечно, можно «вручную» размещать контролы и связывать их через `EditManager` с объектами данных, однако, для облегчения этого труда, существует универсальная форма редактирования, которая автоматически, по указанию типа объекта данных, представлений, размещает элементы управления и обеспечивает пользователя интерфейсом по редактированию объекта данных (панель инструментов, строка статуса). + +Для того чтобы использовать универсальную форму редактирования, необходимо: + +* Конструировать универсальную форму редактирования, передав в конструктор параметром представления, в которых должно осуществляться редактирование: + +```csharp +StormNetUI.IDpdEditForm editcont = new StormNetUI.UniWinEdit(new StormNet.View[]{viewforedit}); +``` + +* Установить обработчики на события (как минимум, на `CloseEvent`, чтобы можно было закрыть форму и `SaveEvent`, чтобы «отловить» вызов пользователем сохранения). +* Вызвать метод Edit, передавая объект данных. + +Следует понимать, что форма реализует абсолютно «голый» пользовательский интерфейс, вся реакция от пользователя транслируется «наружу» формы через события, соответственно, эта управление формой производится через набор методов. Так, когда пользователь просто закрывает форму редактирования, посылается сообщение `CloseEvent`, но сама форма не закрывается. Чтобы закрыть форму, необходимо вызвать метод `Close`. + +_Пример обработчика события `CloseEvent`:_ + +```csharp +private void ContainerCloseHandler (object sender, StormNetUI.CloseEventArgs args) + { + ((StormNetUI.IDpdForm)sender).CloseForm(); + } +``` + +{% include note.html content="Если необходимо выполнить переход на генерируемую форму с универсальной с контролами ICustomizable, метод Customize необходимо вызвать вручную в перегруженном методе Edit." %} + +## Фокус ввода и «Ctrl+S» + +При сохранении формы редактирования по комбинации __«Ctrl+S»__ фокус остается на активном контроле, текущее значение попадает в объект данных с помощью вызова `EditManager.ApplyDataFromControl(ActiveControl)`. + +## Интерфейсы форм редактирования + +Нижеприведённая диаграмма показывает интерфейсы для инициатора, для редактора: +![Интерфейсы формы редактирования](/images/pages/products/flexberry-winforms/forms/primer10.jpg) + +## Создание формы редактирования с иерархическим списком + +Бывают случаи, когда на форме редактирования необходимо создать иерархический список. + +Например, в модели иерархический список выглядит так: + +![Пример иерархического списка](/images/pages/products/flexberry-winforms/controls/olv/object-hierarchical-view.png) + +Однако по-умолчанию генерируется отдельная форма для отображения иерархии (в данном случае, "Территория)". Для того чтобы иерархический список был отображен на форме редактирования, на форму необходимо добавить контрол `ObjectHierarchicalView`. Чтобы это сделать следует выполнить ряд действий: + +* Сгенерировать форму редактирования. +* Добавить на форму в `Form Designer Fields`: + +```csharp +// *** Start programmer edit section *** (Form Designer Fields) + + //... + private ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView objectHierarchicalView1; + +// *** End programmer edit section *** (Form Designer Fields) +``` + +* Далее следует внести дополнения в `InitializeComponent`. + + * Дополнения InitializeComponent + +Для корректного отображения `ObjectHierarchicalView` необходимо правильно прописать все свойства контрола. + +```csharp + private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WinformTestHierarchicalForm)); + //... + this.objectHierarchicalView1 = new ICSSoft.STORMNET.Windows.Forms.ObjectHierarchicalView(); + + // + // objectHierarchicalView1 + // + this.objectHierarchicalView1.AdvansedColumns = null; + this.objectHierarchicalView1.AdvansedMarks = false; + this.objectHierarchicalView1.AllowSorting = true; + this.objectHierarchicalView1.AutoRefreshSupport = false; + this.objectHierarchicalView1.DataObjectTypes = new System.Type[] { + ((System.Type)(typeof(IIS.TestStandWinforms.Территория)))}; + this.objectHierarchicalView1.DataService = null; + this.objectHierarchicalView1.Dock = System.Windows.Forms.DockStyle.None; + this.objectHierarchicalView1.DrawGrid = false; + this.objectHierarchicalView1.ExtendLastCol = true; + this.objectHierarchicalView1.FillDataOnLoad = true; + this.objectHierarchicalView1.FillDataOnLoadUserAllowed = true; + this.objectHierarchicalView1.GrayedOnLoad = true; + this.objectHierarchicalView1.HideToolBar = false; + this.objectHierarchicalView1.HierarchicalMasterName = "Иерархия"; //Имя мастерового объекта, указывается в поле HierarchicalMaster списковой формы*. + this.objectHierarchicalView1.Limit = null; + this.objectHierarchicalView1.LoadingPackageSize = 500; + this.objectHierarchicalView1.Location = new System.Drawing.Point(10, 100); + this.objectHierarchicalView1.MemoryTimeLoadLimit = ((long)(200)); + this.objectHierarchicalView1.Name = "objectHierarchicalView1"; + this.objectHierarchicalView1.NodesStyle = ((ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle)((ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle.Lines | ICSSoft.STORMNET.Windows.Forms.TreeNodesStyle.Symbols))); + this.objectHierarchicalView1.RowCountQuery = 12345; + this.objectHierarchicalView1.SaveExpandedRows = false; + this.objectHierarchicalView1.ShowCyclicalReferencedObjects = false; + this.objectHierarchicalView1.ShowStatusBar = true; + this.objectHierarchicalView1.ShowToolTip = false; + this.objectHierarchicalView1.ShowTreeColumnName = ""; + this.objectHierarchicalView1.Size = new System.Drawing.Size(600, 322); + this.objectHierarchicalView1.TabIndex = 6; + this.objectHierarchicalView1.TreeLeafImage = null; + this.objectHierarchicalView1.TreeLineColor = System.Drawing.Color.DarkGray; + this.objectHierarchicalView1.TreeLineStyle = System.Drawing.Drawing2D.DashStyle.Dot; + this.objectHierarchicalView1.TreeNodeImage = null; + this.objectHierarchicalView1.TreeNodeImageCollapsed = null; + this.objectHierarchicalView1.TreeNodeImageExpanded = null; + this.objectHierarchicalView1.UseAlternativeColoring = false; + this.objectHierarchicalView1.UseColumnOptimization = false; + this.objectHierarchicalView1.UseHotkeyForEdit = true; + this.objectHierarchicalView1.UseLimitFunctionExtension = false; + this.objectHierarchicalView1.UseToolBar = null; + this.objectHierarchicalView1.ViewName = "ТерриторияL";//Имя представления, которое используется на иерархическом списке. +``` + +## Рекомендации по доработке форм редактирования + +Важно понимать, что форма служит не только для редактирования данных, но и для просмотра данных, а также для управления данными - запуск операции экспорта, печати, работы с данными аудита и прочее. + +Поэтому проработку внешнего вида лучше начинать с того, что следует определить какие задачи пользователи будут выполнять с помощью формы. Основные - уже перечислены, это: редактирование, просмотр, выполенение операций над объектом, редактируемым на форме (экспорт, печать и прочее). + +Для того чтобы сделать форму удобной для ввода, следует обратить внимание на следующие моменты: + +* порядок обхода (переход по Tab), +* визуальное выделение фокуса - неопытные пользователи могут даже и не знать, что такое фокус ввода и что он отображется мигающей вертикальной чертой в поле ввода, +* [предиктивный ввод](fw_predict-input.html), +* отображение полей, обязательных для ввода.
Вариант реализации: через [DataObjectErrorProvider](fw_edit-form-validation.html). DataObjectErrorProvider позволит быстро и со вкусом прописать в коде перечень обязательных полей и пользователи приложения не смогут его менять. +* значения по умолчанию, +* автоматизация ввода пользовательских данных, например, ввод адреса или возможность ввести ключевые реквизиты другого объекта данных с возможностью автоматического поиска. + +Для облегчения просмотра и поиска глазами на форме нужных данных применяются следующие механизмы: + +* объединение элементов управления в логические группы (GroupBox) с указанием названия группы - общего признака всех атрибутов в этой группе, +* расположение контролов по сетке в несколько столбцов и строк. ширина полей ввода в одном столбце должна быть одинаковой, заголовки полей в столбцах начинаются с одной позиции в строке, +* увеличения шрифта. Бывают случаи, когда шрифт должен быть увеличен (например, когда большинство пользователей этой формы - пожилые люди с плохим зрением), +* реализация работы формы редактирования в режиме "[Только на чтение](fw_editmanager.html)" . Здесь работа заключается в проверке, что ненужные функции заблокированы, а нужные работают корректно. + +Для выполнения операций над данными зачастую используется панель инструментов, на которой по умолчанию есть кнопки "Сохранить" и "Сохранить и закрыть". Для каждой операции лучше создавать отдельную кнопку на этой панели с чёткой иконкой, лаконичной надписью и понятной всплывающей подсказкой (tooltip). Между кнопками используйте вертикальный разделитель. + +Расположение контролов на форме и группировка их в группы - комплексная задача, которая должна решаться совместно с аналитиком. + +Также формы редактирования могут предоставлять следующие универсальные сервисы: + +* аудирование изменений данных и предоставление доступа к данным аудита, +* проверка данных на соблюдение пользовательских условий, +* разграничение доступа к данным с помощью системы полномочий, +* хранение пользовательских настроек. + +## Принудительный вызов формы редактирования + +Вызов формы редактирования + +```csharp +Объект oОбъект = new Объект(); +oОбъект.__PrimaryKey = 'чего-то там'; +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей +ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); +ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); +cont.Edit(oОбъект, "", ""); +``` + +Если требуется функциональность по сохранению объекта при нажатию на кнопку "Сохранить" или "Сохранить и закрыть" на зависимой форме, то код будет выглядеть таким образом: + +```csharp +Объект oОбъект = new Объект(); +oОбъект.__PrimaryKey = 'чего-то там'; +ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObject(oОбъект); // DataServiceProvider устарел; вместо него используйте внедрение зависимостей +ICSSoft.STORMNET.UI.BaseIndpdEdit cont = (ICSSoft.STORMNET.UI.BaseIndpdEdit)Activator.CreateInstance(typeof(ОбъектE)); +ICSSoft.STORMNET.UI.ContRunner.RunEditForm(cont); +cont.SaveEvent += (sr, ea) => { new BusinessService().UpdateObject(ea.dataobject); }; +cont.Edit(oОбъект, "", ""); +``` + +## Передача параметров от ContRunner до формы редактирования + +### Передача параметров в DesktopCustomizer + +Для того чтобы передать параметр контейнеру запуска, необходимо использовать перегруженный метод создания `ContRunner`. + +```csharp +arr.Add(new ICSSoft.STORMNET.UI.ContRunner(typeof(IIS.LimitsTesting_Blog.LTB_БлогL), "MyTag1FromContRunner", "LimitsTesting_Blog", "Блог", "")); +``` + +### Приём параметра в списковой форме и передача на форму редактирования + +Параметр в списковую форму попадает в метод `Activate(object tag)`. Следует обращать внимание на количество параметров в перегруженном методе `OnNewEvent()`. Перегрузить следует метод с двумя параметрами, а вызвать в нём метод с тремя. По-умолчанию создание объектов происходит без передачи тега. + +```csharp +// *** Start programmer edit section *** (LTB_БлогL CustomMembers) +private object _tagFromRunner; + +public override void Activate(object tag) +{ + _tagFromRunner = tag; + // MessageBox.Show("Activate " + (tag??"<пусто>")); + base.Activate(tag); +} + +protected override void OnNewEvent(Type dataobjecttype, string contpath) +{ + // MessageBox.Show("OnNewEvent"); + base.OnNewEvent(dataobjecttype, contpath, _tagFromRunner); +} + +protected override void OnEditEvent(string propertyname, ICSSoft.STORMNET.DataObject dataobject, string contpath, object tag) +{ + // MessageBox.Show("OnEditEvent " + (tag ?? "<пусто>")); + base.OnEditEvent(propertyname, dataobject, contpath, _tagFromRunner); +} +// *** End programmer edit section *** (LTB_БлогL CustomMembers) +``` + +### Приём параметра на форме редактирования + +В метод `Edit` с самым большим числом параметров придёт тот самый тег. + +```csharp +// *** Start programmer edit section *** (WinformLTB_БлогE CustomMembers) +public override void Edit(ICSSoft.STORMNET.DataObject dataobject, string contpath, string propertyname, object tag) +{ + // MessageBox.Show("БлогE tag: " + (tag??"<пусто>")); + base.Edit(dataobject, contpath, propertyname, tag); +} +// *** End programmer edit section *** (WinformLTB_БлогE CustomMembers) +``` + +## Связанные статьи + +[E-представление](fd_e-view.html) diff --git a/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.en.md b/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.en.md index 23573872d..4b6d8c591 100644 --- a/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.en.md +++ b/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.en.md @@ -42,7 +42,7 @@ The logical architecture of the system can be physically implemented as: Data services can serve as local sources (files) and the DBMS, so the physical architecture can be implemented like this: * Stand-alone server, the data service is a local source (eg. XMLDataService). -* Independent business server, the service data DBMS source (eg. ODBCDataService). +* Independent business server, the service data DBMS source (eg. PostgresDataService). * Business server that COM , the service data DBMS source. * Business server for a Web Service, the data service DBMS source. diff --git a/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.ru.md b/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.ru.md index 2931adab5..9498d6771 100644 --- a/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.ru.md +++ b/pages/products/flexberry-winforms/fw_flexberry-winforms-architecture.ru.md @@ -1,110 +1,110 @@ ---- -title: Базовая системно-технологическая архитектура Flexberry Winforms -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, Ключевые понятия -summary: Логические и физические уровни системы, основные термины, метаданные, виды форм, бизнес-сервер, сценарии -toc: true -permalink: ru/fw_flexberry-winforms-architecture.html -lang: ru ---- - -Базовая системно-технологическая архитектура включает в себя архитектурные логические и физические уровни. - -## Архитектурные логические уровни системы на базе Flexberry Platform - -Любая прикладная система, создаваемая на базе `Flexberry Platform`, содержит три логических уровня: - -* Пользовательский интерфейс. -* Бизнес-логика. -* Данные, метаданные и доступ к данным. - -![Архитектурные логические уровни системы на базе Flexberry Platform](/images/pages/products/flexberry-winforms/primer4.jpg) - -Уровень III представлен объектами данных, с приписанными им декларативно метаданными и сервисами данных, обеспечивающими базовые функции по работе с хранилищами. - -Уровень II представлен [бизнес-сервером](fo_business-server.html), где содержится код общесистемных операций над объектами данных, а также операций, выполняющихся при работе сервисов данных (обработчиков). Бизнес-сервер может быть исполнен как самостоятельно, так и через некоторые обёртки (например, обёртка `COM+` позволяет выполнять бизнес-сервис под `COM+`). - -Уровень I представлен собственно пользовательским интерфейсом, зависящим от среды реализации (это может быть настольный клиент, браузер (UI-зависимая форма), пользовательским интерфейсом, не зависящим от среды реализации (UI-независимая форма) и сценаристом. Принципиально, пользовательская логика отделена от зависимого от реализации клиента. Так, например, логика наложения ограничения должна быть реализована в UI-независимой форме, что позволит использовать одну и ту же логику вне зависимости от UI-зависимой реализации пользовательского интерфейса. Таким образом, внутренняя реализация системы максимально независима от пользовательского интерфейса, обладая при этом повторной применимостью даже пользовательской логики. - -## Архитектурные физические уровни системы на базе Flexberry Platform - -Многоуровневая распределённая клиент-серверная архитектура с обособленными серверами приложений и её реализация. - -Логическая архитектура системы физически может быть реализована как: - -* Монолитная. -* Двухуровневая клиент-серверная. -* Распределённая многоуровневая. -* Распределённая многоуровневая в `WEB`. - -Сервисы данных могут обслуживать как локальные источники (файлы), так и СУБД, поэтому физические архитектуры могут быть реализованы так: - -* Самостоятельный бизнес-сервер, сервис данных локального источника (напр. XMLDataService). -* Самостоятельный бизнес-сервер, сервис данных СУБД-источника (напр. ODBCDataService). -* Бизнес-сервер под COM+, сервис данных СУБД-источника. -* Бизнес-сервер под Web Service, сервис данных СУБД-источника. - -Это основные типы, могут быть и «экзотические», типа, локального файла, но `Web`-сервиса. - -Очевидно, применение различных средств даёт различные возможности. Здесь всё остаётся на усмотрение разработчика. - -## Интеграция систем - -Физическое расположение кода (как исходного, так и двоичного в сборках) не имеет значения. Подключение частей какой-либо системы и чужой системы как подсистемы осуществляются подключением соответствующих сборок. - -Деление на сборки внутри системы относится к компетенции разработчика. - -## Метаданные объектной структуры - -Отдельно существующих метаданных не существует, вместо этого определение дополнительных свойств классов ([представлений](fd_view-definition.html), например), [атрибутов](fo_attributes-class-data.html) (например [`NotNull`](fo_attributes-class-data.html)), методов и т.п. осуществляется указанием атрибутов `.Net`. В сущности, все дополнительные метаданные определяются декларативно `.Net`-атрибутами непосредственно классам данных, их свойствам и т.п. - -Существует универсальный [информационный класс (`ICSSoft.STORMNET.DataObject.Information`) со статическими методами для получения метаданных](fo_methods-class-information.html). Доступ прикладного разработчика к декларативно определённым метаданным (`.Net`-атрибутам) не должен вестись напрямую (через `.NET Reflection`), а только через соответствующие методы этого [информационного класса](fo_methods-class-information.html). Исключение составляют только те атрибуты, которые вводятся непосредственно самим прикладным разработчиком. - -## Хранение данных и независимость от хранилища - -_Сервисом данных_ называется любая реализация абстрактного класса `ICSSoft.STORMNET.Business.DataService`, обеспечивающая сохранение/чтение любых объектов данных в какое-либо хранилище. -Подробности в статье [Сервис данных](fo_data-service.html). - -### Формы - -Формы предназначены для обеспечения взаимодействия с пользователем. - -_Формой_ называется способ предоставления пользовательского интерфейса для доступа к одному или нескольким объектам данных. Формы бывают _UI-зависимые_ (зависят от физической природы интерфейса – `WinForms, WebForms`) и _UI-независимые_. Пользовательская логика должна реализовываться в UI-независимых формах, что позволит вносить меньше изменений, а также избежать дублирования кода при реализации в системе других типов пользовательского интерфейса. - -_UI-зависимые формы_ могут быть _универсальными_, т.е. реализовывать некоторую стандартную функциональность без возможности какой-либо модификации. Как правило, это необходимо для очень простых объектов, для которых имеет смысл сэкономить на создании отдельных форм. _Неуниверсальные UI-зависимые формы_ могут быть сгенерированы (получены в исходном коде) и, затем, допрограммированы. - -_Формы редактирования_ позволяют пользователю редактировать собственные атрибуты объектов данных, связи с мастеровыми объектами данных, агрегированные объекты данных, в соответствии с одним или несколькими представлениями. Форма редактирования обеспечивает "полиморфное" редактирование: как объектов данных собственного класса, так и всех наследуемых классов, в представлении(ях) собственного класса. - -_Форма списка_ позволяет пользователю "полиморфно" работать со списком объектов данных как собственного класса, так и любых наследуемых классов. При этом, форме списка указываются классы данных потомков и имя совместимого представления. - -_Форма печати_ позволяет получить печатную копию объекта данных в соответствии с представлением(ями). - -## Бизнес-сервер - -[Бизнес-сервер](fo_business-server.html) предназначен для логического выделения операций, которые относятся к системе. В сущности: бизнес-сервер есть набор методов. Соответственно, бизнес-сервер не имеет состояния (общепринято — stateless). В CASE бизнес-сервер отрисовывается UML-классом с установленным атрибутом [businessserver](fd_business-servers.html). Система может содержать произвольное число бизнес-серверов. В общем, число бизнес-серверов и состав их методов определяется прикладным разработчиком. - -Бизнес-сервис также применяется в случаях, когда при работе сервиса данных с хранилищем (добавление, удаление и т.п. объекта), требуется выполнить какие-либо действия. - -При генерации кода для каждого бизнес-сервера создаётся: - -* Код бизнес-сервера с определениями методов; -* Код нужных заглушек («нужные» — определяются разработчиком в CASE в свойствах класса); - -## Сценарист - -Существует следующая проблема при создании многоуровневых систем: имеется по отдельности доступ к данным, бизнес-логика, пользовательский интерфейс. Однако как (чем) возможно объединить эти части в непосредственно работающую систему? Иначе говоря, как (где) должно быть записано, что при определённых манипуляциях пользовательским интерфейсом формы открываются в определённой последовательности и когда происходит вызов операций бизнес-сервера? - -Конечно, можно, как это обыкновенно и делается, «жёстко» прописать вызовы прямо в код, например, в пользовательский интерфейс, однако, это является плохой идеей по следующим причинам: - -* Части системы перестают быть «частями», поскольку начинают «знать» о существовании друг друга, что может сделать затруднительным повторное использование. -* Модификация этой самой объединяющей логики трудоёмка, поскольку та располагается во многих местах («разбросана» по частям, сборкам, классам). -* Модификация объединяющей логики требует вмешательства в исходный код системы (требует программиста). Если система сможет модифицироваться снаружи, можно дать возможность гибко настраивать логику из готовых частей непосредственно пользователю. -* Вообще затруднено создание логики, которая включает в себя процесс выполнения операций, который сильно ветвится в зависимости от каких-либо условий. Либо, различное выполнение логики в зависимости от полномочий пользователя. - -В то же время, эта самая объединяющая логика есть ничто иное, как некоторый сценарий работы для пользователя и может быть описана как самостоятельная сущность. - -Для решения этой проблемы, в `Flexberry Platform` предусмотрено создание событийно-ориентированных сценариев (`EBS — Event-Based Script`) и их интерпретации. - -Существует специальный графический язык, позволяющий описывать сценарии (`EBSD — Event-Based Script Diagram`, соответствующий диаграммный метод, реализованный в `Flexberry`). - -Существует специальный компонент — _Сценарист_ (`EBSI — Event-Based Script Interpreter`), обеспечивающий выполнение (интерпретацию) сценария в `RunTime`. +--- +title: Базовая системно-технологическая архитектура Flexberry Winforms +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, Ключевые понятия +summary: Логические и физические уровни системы, основные термины, метаданные, виды форм, бизнес-сервер, сценарии +toc: true +permalink: ru/fw_flexberry-winforms-architecture.html +lang: ru +--- + +Базовая системно-технологическая архитектура включает в себя архитектурные логические и физические уровни. + +## Архитектурные логические уровни системы на базе Flexberry Platform + +Любая прикладная система, создаваемая на базе `Flexberry Platform`, содержит три логических уровня: + +* Пользовательский интерфейс. +* Бизнес-логика. +* Данные, метаданные и доступ к данным. + +![Архитектурные логические уровни системы на базе Flexberry Platform](/images/pages/products/flexberry-winforms/primer4.jpg) + +Уровень III представлен объектами данных, с приписанными им декларативно метаданными и сервисами данных, обеспечивающими базовые функции по работе с хранилищами. + +Уровень II представлен [бизнес-сервером](fo_business-server.html), где содержится код общесистемных операций над объектами данных, а также операций, выполняющихся при работе сервисов данных (обработчиков). Бизнес-сервер может быть исполнен как самостоятельно, так и через некоторые обёртки (например, обёртка `COM+` позволяет выполнять бизнес-сервис под `COM+`). + +Уровень I представлен собственно пользовательским интерфейсом, зависящим от среды реализации (это может быть настольный клиент, браузер (UI-зависимая форма), пользовательским интерфейсом, не зависящим от среды реализации (UI-независимая форма) и сценаристом. Принципиально, пользовательская логика отделена от зависимого от реализации клиента. Так, например, логика наложения ограничения должна быть реализована в UI-независимой форме, что позволит использовать одну и ту же логику вне зависимости от UI-зависимой реализации пользовательского интерфейса. Таким образом, внутренняя реализация системы максимально независима от пользовательского интерфейса, обладая при этом повторной применимостью даже пользовательской логики. + +## Архитектурные физические уровни системы на базе Flexberry Platform + +Многоуровневая распределённая клиент-серверная архитектура с обособленными серверами приложений и её реализация. + +Логическая архитектура системы физически может быть реализована как: + +* Монолитная. +* Двухуровневая клиент-серверная. +* Распределённая многоуровневая. +* Распределённая многоуровневая в `WEB`. + +Сервисы данных могут обслуживать как локальные источники (файлы), так и СУБД, поэтому физические архитектуры могут быть реализованы так: + +* Самостоятельный бизнес-сервер, сервис данных локального источника (напр. XMLDataService). +* Самостоятельный бизнес-сервер, сервис данных СУБД-источника (напр. PostgresDataService). +* Бизнес-сервер под COM+, сервис данных СУБД-источника. +* Бизнес-сервер под Web Service, сервис данных СУБД-источника. + +Это основные типы, могут быть и «экзотические», типа, локального файла, но `Web`-сервиса. + +Очевидно, применение различных средств даёт различные возможности. Здесь всё остаётся на усмотрение разработчика. + +## Интеграция систем + +Физическое расположение кода (как исходного, так и двоичного в сборках) не имеет значения. Подключение частей какой-либо системы и чужой системы как подсистемы осуществляются подключением соответствующих сборок. + +Деление на сборки внутри системы относится к компетенции разработчика. + +## Метаданные объектной структуры + +Отдельно существующих метаданных не существует, вместо этого определение дополнительных свойств классов ([представлений](fd_view-definition.html), например), [атрибутов](fo_attributes-class-data.html) (например [`NotNull`](fo_attributes-class-data.html)), методов и т.п. осуществляется указанием атрибутов `.Net`. В сущности, все дополнительные метаданные определяются декларативно `.Net`-атрибутами непосредственно классам данных, их свойствам и т.п. + +Существует универсальный [информационный класс (`ICSSoft.STORMNET.DataObject.Information`) со статическими методами для получения метаданных](fo_methods-class-information.html). Доступ прикладного разработчика к декларативно определённым метаданным (`.Net`-атрибутам) не должен вестись напрямую (через `.NET Reflection`), а только через соответствующие методы этого [информационного класса](fo_methods-class-information.html). Исключение составляют только те атрибуты, которые вводятся непосредственно самим прикладным разработчиком. + +## Хранение данных и независимость от хранилища + +_Сервисом данных_ называется любая реализация абстрактного класса `ICSSoft.STORMNET.Business.DataService`, обеспечивающая сохранение/чтение любых объектов данных в какое-либо хранилище. +Подробности в статье [Сервис данных](fo_data-service.html). + +### Формы + +Формы предназначены для обеспечения взаимодействия с пользователем. + +_Формой_ называется способ предоставления пользовательского интерфейса для доступа к одному или нескольким объектам данных. Формы бывают _UI-зависимые_ (зависят от физической природы интерфейса – `WinForms, WebForms`) и _UI-независимые_. Пользовательская логика должна реализовываться в UI-независимых формах, что позволит вносить меньше изменений, а также избежать дублирования кода при реализации в системе других типов пользовательского интерфейса. + +_UI-зависимые формы_ могут быть _универсальными_, т.е. реализовывать некоторую стандартную функциональность без возможности какой-либо модификации. Как правило, это необходимо для очень простых объектов, для которых имеет смысл сэкономить на создании отдельных форм. _Неуниверсальные UI-зависимые формы_ могут быть сгенерированы (получены в исходном коде) и, затем, допрограммированы. + +_Формы редактирования_ позволяют пользователю редактировать собственные атрибуты объектов данных, связи с мастеровыми объектами данных, агрегированные объекты данных, в соответствии с одним или несколькими представлениями. Форма редактирования обеспечивает "полиморфное" редактирование: как объектов данных собственного класса, так и всех наследуемых классов, в представлении(ях) собственного класса. + +_Форма списка_ позволяет пользователю "полиморфно" работать со списком объектов данных как собственного класса, так и любых наследуемых классов. При этом, форме списка указываются классы данных потомков и имя совместимого представления. + +_Форма печати_ позволяет получить печатную копию объекта данных в соответствии с представлением(ями). + +## Бизнес-сервер + +[Бизнес-сервер](fo_business-server.html) предназначен для логического выделения операций, которые относятся к системе. В сущности: бизнес-сервер есть набор методов. Соответственно, бизнес-сервер не имеет состояния (общепринято — stateless). В CASE бизнес-сервер отрисовывается UML-классом с установленным атрибутом [businessserver](fd_business-servers.html). Система может содержать произвольное число бизнес-серверов. В общем, число бизнес-серверов и состав их методов определяется прикладным разработчиком. + +Бизнес-сервис также применяется в случаях, когда при работе сервиса данных с хранилищем (добавление, удаление и т.п. объекта), требуется выполнить какие-либо действия. + +При генерации кода для каждого бизнес-сервера создаётся: + +* Код бизнес-сервера с определениями методов; +* Код нужных заглушек («нужные» — определяются разработчиком в CASE в свойствах класса); + +## Сценарист + +Существует следующая проблема при создании многоуровневых систем: имеется по отдельности доступ к данным, бизнес-логика, пользовательский интерфейс. Однако как (чем) возможно объединить эти части в непосредственно работающую систему? Иначе говоря, как (где) должно быть записано, что при определённых манипуляциях пользовательским интерфейсом формы открываются в определённой последовательности и когда происходит вызов операций бизнес-сервера? + +Конечно, можно, как это обыкновенно и делается, «жёстко» прописать вызовы прямо в код, например, в пользовательский интерфейс, однако, это является плохой идеей по следующим причинам: + +* Части системы перестают быть «частями», поскольку начинают «знать» о существовании друг друга, что может сделать затруднительным повторное использование. +* Модификация этой самой объединяющей логики трудоёмка, поскольку та располагается во многих местах («разбросана» по частям, сборкам, классам). +* Модификация объединяющей логики требует вмешательства в исходный код системы (требует программиста). Если система сможет модифицироваться снаружи, можно дать возможность гибко настраивать логику из готовых частей непосредственно пользователю. +* Вообще затруднено создание логики, которая включает в себя процесс выполнения операций, который сильно ветвится в зависимости от каких-либо условий. Либо, различное выполнение логики в зависимости от полномочий пользователя. + +В то же время, эта самая объединяющая логика есть ничто иное, как некоторый сценарий работы для пользователя и может быть описана как самостоятельная сущность. + +Для решения этой проблемы, в `Flexberry Platform` предусмотрено создание событийно-ориентированных сценариев (`EBS — Event-Based Script`) и их интерпретации. + +Существует специальный графический язык, позволяющий описывать сценарии (`EBSD — Event-Based Script Diagram`, соответствующий диаграммный метод, реализованный в `Flexberry`). + +Существует специальный компонент — _Сценарист_ (`EBSI — Event-Based Script Interpreter`), обеспечивающий выполнение (интерпретацию) сценария в `RunTime`. diff --git a/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.en.md b/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.en.md index 07afa823c..a7419829d 100644 --- a/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.en.md +++ b/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.en.md @@ -129,7 +129,7 @@ This type of serialization is more productive and the rows get shorter. string fnStr = ""; string serializedFn; AdvansedLimit advlimit = new AdvansedLimit(); - ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; + ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). advlimit.FromSimpleValue(Utils.ObjectFromString(_serializedFunc), externalLangDef); Function fn = advlimit.Function; diff --git a/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.ru.md b/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.ru.md index 473ccd8f6..5725feec0 100644 --- a/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.ru.md +++ b/pages/products/flexberry-winforms/subsystems/limits/fw_advlimit-function-serialization.ru.md @@ -1,5 +1,5 @@ --- -title: Сохранение ограничений на форме задания ограничения +title: Сохранение ограничений на форме задания ограничения sidebar: flexberry-winforms_sidebar keywords: Flexberry Winforms, Windows UI (формы), Ограничения, Черновик статьи summary: Перечислены методы класса `ICSSoft.STORMNET.Windows.Forms.Utils` для сериализации-десериализации; указано какие из них применяются для функции ограничения, приведены примеры; описана проблема десериализации ограничений при использовании подписанных и неподписанных сборок, указан подход к решению @@ -9,14 +9,14 @@ folder: products/flexberry-winforms/ lang: ru --- -## Средства сериализации-десериализации в `ICSSoft.STORMNET.Windows.Forms.Utils` -В сборке `ICSSoft.STORMNET.Windows.Forms` реализован класс `ICSSoft.STORMNET.Windows.Forms.Utils`, предоставляющий, в частности, методы для сериализации-десериализации, которые применимы в т.ч. для [функции ограничения](fo_limit-function.html). Данные методы представляют собой обертку над соответствующими методами сборки [`ICSSoft.STORMNET.Tools`](fo_ics-soft-stormnet-tools.html), и выполняют обращение к ней. +## Средства сериализации-десериализации в `ICSSoft.STORMNET.Windows.Forms.Utils` +В сборке `ICSSoft.STORMNET.Windows.Forms` реализован класс `ICSSoft.STORMNET.Windows.Forms.Utils`, предоставляющий, в частности, методы для сериализации-десериализации, которые применимы в т.ч. для [функции ограничения](fo_limit-function.html). Данные методы представляют собой обертку над соответствующими методами сборки [`ICSSoft.STORMNET.Tools`](fo_ics-soft-stormnet-tools.html), и выполняют обращение к ней. ### Методы сериализации класса `ICSSoft.STORMNET.Windows.Forms.Utils`: #### `ObjectToString` - __Назначение__: Сериализация в строку при помощи `SoapFormatter`. + __Назначение__: Сериализация в строку при помощи `SoapFormatter`. __Параметры__: @@ -32,9 +32,9 @@ public static string ObjectToString(object o) return ICSSoft.STORMNET.Tools.ToolXML.ObjectToString(o); } ``` - + #### `ObjectFromString` - + __Назначение__: Десериализация из строки при помощи `SoapFormatter`. __Параметры__: @@ -102,14 +102,14 @@ public static object ObjectFromBinaryString(string s) ### Пример SOAP-сериализации LimitFunction -```csharp +```csharp Function fn = FunctionBuilder.BuildAnd( FunctionBuilder.BuildEquals("ПарамПамПам", "кто ходит в гости по утрам"), FunctionBuilder.BuildOr( FunctionBuilder.BuildEquals("ТотПоступаетМудро", Environment.UserName), FunctionBuilder.BuildIsNull("НаТоОноИУтро") ) - ); + ); string serializedFn = Utils.ObjectToString((new ExternalLangDef()).FunctionToSimpleStruct(fn)); Assert.IsNotNull(serializedFn); @@ -127,15 +127,15 @@ public static object ObjectFromBinaryString(string s) string fnStr = ""; string serializedFn; AdvansedLimit advlimit = new AdvansedLimit(); - ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; + ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). advlimit.FromSimpleValue(Utils.ObjectFromString(_serializedFunc), externalLangDef); Function fn = advlimit.Function; serializedFn = Utils.ObjectToBinaryString(externalLangDef.FunctionToSimpleStruct(fn)); Assert.IsNotNull(serializedFn); - + восставшийИзНебытия = - externalLangDef.FunctionFromSimpleStruct(Utils.ObjectFromBinaryString(serializedFn)); + externalLangDef.FunctionFromSimpleStruct(Utils.ObjectFromBinaryString(serializedFn)); Assert.IsNotNull(восставшийИзНебытия); ``` @@ -149,10 +149,10 @@ namespace ICSSoft.STORMNET.Windows.Forms { /// Делегат для получения типа по его имени в методе SimpleValueToDataObject public static TypeResolveDelegate ExtraTypeResolver = null; - + //... } - + /// /// Делегат для получения типа по его имени (используется в особых случаях, когда стандартные методы почему-то не помогают) /// @@ -185,4 +185,4 @@ private Type ExtraTypeResolver(string typeName) return null; } -``` \ No newline at end of file +``` diff --git a/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.en.md b/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.en.md index 21a3a713f..df73207d1 100644 --- a/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.en.md +++ b/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.en.md @@ -17,7 +17,7 @@ There limitFunction](fo_limit-function.html) (class `ICSSoft.STORMNET.Functional ## Response Let `limitFunction` set function with a parameter @date: ```csharp -ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; +ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Use of ExternalLangDef.LanguageDef is deprecated. Use constructor instead (new ExternalLangDef(dataService)). ICSSoft.STORMNET.FunctionalLanguage.Function limitFunction = externalLangDef.GetFunction( externalLangDef.funcEQ, diff --git a/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.ru.md b/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.ru.md index 37e96c140..70ba731d4 100644 --- a/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.ru.md +++ b/pages/products/flexberry-winforms/subsystems/limits/fw_limit-function-insert-parameters-values.ru.md @@ -1,72 +1,72 @@ ---- -title: Подстановка значений параметров в ограничивающую функцию -sidebar: flexberry-winforms_sidebar -keywords: Flexberry Winforms, Ограничения -summary: На примере показано как в limitFunction с параметром типа Дата вставить в качестве значения этого параметра текущую дату -toc: true -permalink: ru/fw_limit-function-insert-parameters-values.html -folder: products/flexberry-winforms/ -lang: ru ---- - -## Вопрос -Имеется [limitFunction](fo_limit-function.html) (класс `ICSSoft.STORMNET.FunctionalLanguage.Function`) с параметром @Дата. Как вместо этого параметра подставить текущую дату? - -## Ответ -Пусть задана функция `limitFunction` с параметром @Дата: -```csharp -ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; - - ICSSoft.STORMNET.FunctionalLanguage.Function limitFunction = externalLangDef.GetFunction( - externalLangDef.funcEQ, - new ParameterDef("Дата", externalLangDef.DateTimeType, false, ""), - new DateTime(2000, 01, 01)); -``` - -Подробнее о [ExternalLangDef](fo_external-lang-def.html). - -### Для Web -Для подстановки параметров в функцию в классе `ICSSoft.STORMNET.Web.Tools.AdvLimitUtils` есть метод: - -```csharp -/// -/// Подставить конкретные значения вместо параметров функции. -/// -/// Сама функция, в которой будут заменять параметры. -/// Справочник значений параметров (название параметра - значение). -/// Функция, в которой все параметры заменены на соответствующие значения. -public static Function SubstituteParameters(Function function, IDictionary paramValues) -``` - -### Пример - -```csharp - limitFunction = AdvLimitUtils.SubstituteParameters( - limitFunction, - new Dictionary() { {"Дата", DateTime.Now} }); -``` - -### Для Win -Для подстановки параметров в ограничивающую функцию в классе `ICSSoft.STORMNET.Windows.Forms.AdvansedLimitExtension` есть метод: -```csharp -/// - /// Получить ограничение с подставленными значениями параметров - /// - /// Само ограничение. - /// Словарь со значениями параметров. Ключ - имя параметра - /// Функция-ограничение с подставленными значениями параметров - public static Function GetCustomizedFunctionByParameters(this R advansedLimit, T parValues) - where T : IDictionary, IDictionary - where R : AdvansedLimit -``` - -Но для этого метода нужен экземпляр класса `ICSSoft.STORMNET.Windows.Forms.AdvansedLimit` (объектная модель ограничения, включает в себя как ограничивающую функцию, так и определения параметров). - -### Пример -```csharp - AdvansedLimit advlimit = new AdvansedLimit {Function = limitFunction}; - advlimit.Parameters = new ParameterDef[1] { (ParameterDef)advlimit.Function.Parameters[0] }; - limitFunction = AdvansedLimitExtension.GetCustomizedFunctionByParameters( - advlimit, - new Dictionary() { { "Дата", DateTime.Now } }); -``` +--- +title: Подстановка значений параметров в ограничивающую функцию +sidebar: flexberry-winforms_sidebar +keywords: Flexberry Winforms, Ограничения +summary: На примере показано как в limitFunction с параметром типа Дата вставить в качестве значения этого параметра текущую дату +toc: true +permalink: ru/fw_limit-function-insert-parameters-values.html +folder: products/flexberry-winforms/ +lang: ru +--- + +## Вопрос +Имеется [limitFunction](fo_limit-function.html) (класс `ICSSoft.STORMNET.FunctionalLanguage.Function`) с параметром @Дата. Как вместо этого параметра подставить текущую дату? + +## Ответ +Пусть задана функция `limitFunction` с параметром @Дата: +```csharp +ExternalLangDef externalLangDef = ExternalLangDef.LanguageDef; // Использование ExternalLangDef.LanguageDef является устаревшим. Вместо него используйте конструктор (new ExternalLangDef(dataService)). + + ICSSoft.STORMNET.FunctionalLanguage.Function limitFunction = externalLangDef.GetFunction( + externalLangDef.funcEQ, + new ParameterDef("Дата", externalLangDef.DateTimeType, false, ""), + new DateTime(2000, 01, 01)); +``` + +Подробнее о [ExternalLangDef](fo_external-lang-def.html). + +### Для Web +Для подстановки параметров в функцию в классе `ICSSoft.STORMNET.Web.Tools.AdvLimitUtils` есть метод: + +```csharp +/// +/// Подставить конкретные значения вместо параметров функции. +/// +/// Сама функция, в которой будут заменять параметры. +/// Справочник значений параметров (название параметра - значение). +/// Функция, в которой все параметры заменены на соответствующие значения. +public static Function SubstituteParameters(Function function, IDictionary paramValues) +``` + +### Пример + +```csharp + limitFunction = AdvLimitUtils.SubstituteParameters( + limitFunction, + new Dictionary() { {"Дата", DateTime.Now} }); +``` + +### Для Win +Для подстановки параметров в ограничивающую функцию в классе `ICSSoft.STORMNET.Windows.Forms.AdvansedLimitExtension` есть метод: +```csharp +/// + /// Получить ограничение с подставленными значениями параметров + /// + /// Само ограничение. + /// Словарь со значениями параметров. Ключ - имя параметра + /// Функция-ограничение с подставленными значениями параметров + public static Function GetCustomizedFunctionByParameters(this R advansedLimit, T parValues) + where T : IDictionary, IDictionary + where R : AdvansedLimit +``` + +Но для этого метода нужен экземпляр класса `ICSSoft.STORMNET.Windows.Forms.AdvansedLimit` (объектная модель ограничения, включает в себя как ограничивающую функцию, так и определения параметров). + +### Пример +```csharp + AdvansedLimit advlimit = new AdvansedLimit {Function = limitFunction}; + advlimit.Parameters = new ParameterDef[1] { (ParameterDef)advlimit.Function.Parameters[0] }; + limitFunction = AdvansedLimitExtension.GetCustomizedFunctionByParameters( + advlimit, + new Dictionary() { { "Дата", DateTime.Now } }); +```