RU2412461C2 - Systems and methods of interfacing application programs with article based storage platform - Google Patents

Systems and methods of interfacing application programs with article based storage platform Download PDF

Info

Publication number
RU2412461C2
RU2412461C2 RU2006105196/08A RU2006105196A RU2412461C2 RU 2412461 C2 RU2412461 C2 RU 2412461C2 RU 2006105196/08 A RU2006105196/08 A RU 2006105196/08A RU 2006105196 A RU2006105196 A RU 2006105196A RU 2412461 C2 RU2412461 C2 RU 2412461C2
Authority
RU
Russia
Prior art keywords
article
data
articles
type
relationship
Prior art date
Application number
RU2006105196/08A
Other languages
Russian (ru)
Other versions
RU2006105196A (en
Inventor
Уинни К. ВУ (US)
Уинни К. ВУ
Майкл Э. ДИМ (US)
Майкл Э. ДИМ
Эдвард Дж. ШЕППАРД (US)
Эдвард Дж. ШЕППАРД
Лицзянь ФАН (US)
Лицзянь ФАН
Дзянь ЛИ (US)
Дзянь ЛИ
Майкл Б. ТЭЙЛОР (US)
Майкл Б. ТЭЙЛОР
Original Assignee
Майкрософт Корпорейшн
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Майкрософт Корпорейшн filed Critical Майкрософт Корпорейшн
Priority to RU2006105196/08A priority Critical patent/RU2412461C2/en
Publication of RU2006105196A publication Critical patent/RU2006105196A/en
Application granted granted Critical
Publication of RU2412461C2 publication Critical patent/RU2412461C2/en

Links

Images

Abstract

FIELD: information technology.
SUBSTANCE: storage platform includes: a processor and computer-readable data medium on which instructions are recorded, computer-executed operating system functions having a kernel which includes data base management apparatus, generation of elements which include metadata and storage of elements, where the database management apparatus contain a base scheme and a mechanism which is configured to expand said base scheme for determining the data scheme and separation of data into program-defined alteration elements based on the data scheme. The alteration element is the smallest part of the scheme which can be separately controlled by database management apparatus.
EFFECT: fast access to data storage.
16 cl, 35 dwg

Description

Перекрестная ссылкаCross reference

Изобретение связано по тематике с изобретениями, раскрыми в следующих заявках общего присвоения: патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-1748), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHODS FOR REPRESENTING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE/SOFTWARE INTERFACE SYSTEM BUT INDEPENDENT OF PHYSICAL REPRESENTATION"; патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-1749), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHODS FOR SEPARATING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE/SOFTWARE INTERFACE SYSTEM FROM THEIR PHYSICAL ORGANIZATION"; патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-1750), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHODS FOR THE IMPLEMENTATION OF A BASE SCHEMA FOR ORGANIZING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE/SOFTWARE INTERFACE SYSTEM"; патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-1751), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHODS FOR THE IMPLEMENTATION OF A CORE SCHEMA FOR PROVIDING A TOP-LEVEL STRUCTURE FOR ORGANIZING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE/SOFTWARE INTERFACE SYSTEM"; патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-1752), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHOD FOR REPRESENTING RELATIONSHIPS BETWEEN UNITS OF INFORMATION MANAGEABLE BY A HARDWARE/SOFTWARE INTERFACE SYSTEM"; патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-2734), поданной одновременно с данной заявкой, под названием "STORAGE PLATFORM FOR ORGANIZING, SEARCHING, AND SHARING DATA"; и патентной заявке США № (еще не присвоенной) (Реестр поверенного № MSFT-2735), поданной одновременно с данной заявкой, под названием "SYSTEMS AND METHODS FOR DATA MODELING IN AN ITEM-BASED STORAGE PLATFORM".The invention is related to the inventions disclosed in the following general assignment applications: US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-1748) filed simultaneously with this application, entitled "SYSTEMS AND METHODS FOR REPRESENTING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE / SOFTWARE INTERFACE SYSTEM BUT INDEPENDENT OF PHYSICAL REPRESENTATION "; US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-1749), filed simultaneously with this application, entitled "SYSTEMS AND METHODS FOR SEPARATING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE / SOFTWARE INTERFACE SYSTEM FROM THEIR PHYSICAL ORGANIZATION"; US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-1750), filed simultaneously with this application, entitled "SYSTEMS AND METHODS FOR THE IMPLEMENTATION OF A BASE SCHEMA FOR ORGANIZING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE / SOFTWARE INTERFACE SYSTEM "; U.S. Patent Application No. (not yet assigned) (Attorney Register No. MSFT-1751), filed simultaneously with this application, entitled "SYSTEMS AND METHODS FOR THE IMPLEMENTATION OF A CORE SCHEMA FOR PROVIDING A TOP-LEVEL STRUCTURE FOR ORGANIZING UNITS OF INFORMATION MANAGEABLE BY A HARDWARE / SOFTWARE INTERFACE SYSTEM "; US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-1752), filed simultaneously with this application, entitled "SYSTEMS AND METHOD FOR REPRESENTING RELATIONSHIPS BETWEEN UNITS OF INFORMATION MANAGEABLE BY A HARDWARE / SOFTWARE INTERFACE SYSTEM"; US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-2734) filed simultaneously with this application, entitled "STORAGE PLATFORM FOR ORGANIZING, SEARCHING, AND SHARING DATA"; and US Patent Application No. (not yet assigned) (Attorney Register No. MSFT-2735), filed simultaneously with this application, entitled "SYSTEMS AND METHODS FOR DATA MODELING IN AN ITEM-BASED STORAGE PLATFORM".

Область техники, к которой относится изобретениеFIELD OF THE INVENTION

Настоящее изобретение относится в целом к области хранения и извлечения информации и, в частности, к активной платформе хранения для организации, поиска и совместного использования различных типов данных в компьютерной системе.The present invention relates generally to the field of storage and retrieval of information and, in particular, to an active storage platform for organizing, searching and sharing various types of data in a computer system.

Уровень техникиState of the art

В течение последнего десятилетия наблюдался рост емкости индивидуального диска примерно на семьдесят процентов (70%) в год. Закон Мура точно предсказал существенный рост вычислительной мощности центральных процессоров (ЦП), произошедший за эти годы. Технологии проводной и беспроводной связи обеспечили большие возможности соединения и пропускную способность. При условии, что современные тенденции сохранятся, через несколько лет средний портативный компьютер будет иметь емкость хранения около одного терабайта (ТБ), и будет содержать миллионы файлов, и жесткие диски емкостью 500 гигабайт (ГБ) получат широкое распространение.Over the past decade, there has been an increase in individual disk capacity by about seventy percent (70%) per year. Moore's law accurately predicted a significant increase in the processing power of central processing units (CPUs) over the years. Wired and wireless technologies provide great connectivity and bandwidth. Provided that current trends continue, in a few years the average portable computer will have a storage capacity of about one terabyte (TB), and will contain millions of files, and hard drives with a capacity of 500 gigabytes (GB) will become widespread.

Потребители используют свои компьютеры, в основном, для связи и для организации личной информации, будь то данные в традиционном стиле личной информационной системы (PIM) или мультимедийные данные, например цифровая музыка или фотографии. Объем цифрового контента и возможность хранения необработанных байтов значительно возросли; однако доступные потребителям способы организации и унификации этих данных не получили адекватного развития. Специалисты в области информационных технологий тратят очень много времени на организацию и совместное использование информации и, согласно некоторым исследованиям, специалисты в области информационных технологий тратят 15-25% своего времени на непродуктивную деятельность, связанную с информацией. Согласно другим исследованиям типичный специалист в области информационных технологий тратит ежедневно около 2,5 часов на поиск информации.Consumers use their computers mainly for communication and for organizing personal information, whether it be data in the traditional style of a personal information system (PIM) or multimedia data, such as digital music or photographs. The volume of digital content and the ability to store raw bytes have increased significantly; however, ways of organizing and unifying these data available to consumers have not been adequately developed. Information technology specialists spend a lot of time organizing and sharing information, and according to some studies, information technology experts spend 15-25% of their time on non-productive activities related to information. According to other studies, a typical IT specialist spends about 2.5 hours daily searching for information.

Разработчики и департаменты по информационным технологиям (IT) тратят много времени и денег на построение своих собственных хранилищ данных для обычных абстракций хранения для представления личностей, мест, времен и событий. Это приводит не только к дублированию работы, но и к созданию островов общих данных без каких-либо механизмов общего поиска или совместного использования этих данных. Только представьте, сколько адресных книжек может сегодня существовать на компьютере, на котором установлена операционная система Microsoft Windows. Многие приложения, например клиенты электронной почты и персональные финансовые программы, поддерживают отдельные адресные книжки, и приложения в незначительной степени могут совместно пользоваться данными адресных книжек, которые по отдельности поддерживаются каждой такой программой. Следовательно, финансовая программа (наподобие Microsoft Money) не может совместно использовать адреса получателей денег с адресами, поддерживаемыми в папке контактов электронной почты (например, в Microsoft Outlook). Действительно, многие пользователи имеют несколько устройств, и было бы логично, если бы они синхронизировали свои личные данные между ними и по обширной совокупности дополнительных устройств, включая сотовые телефоны, для таких коммерческих услуг как MSN и AOL; тем не менее, для совместной работы с документами общего пользования в основном приходится присоединять документы к сообщениям электронной почты, т.е. действовать вручную и малоэффективно.Developers and information technology (IT) departments spend a lot of time and money building their own data warehouses for common storage abstractions to represent personalities, places, times and events. This leads not only to duplication of work, but also to the creation of islands of common data without any mechanisms for a common search or sharing of this data. Just imagine how many address books can exist today on the computer on which the Microsoft Windows operating system is installed. Many applications, such as email clients and personal financial programs, support separate address books, and applications can only slightly share the address book data that is individually supported by each such program. Consequently, a financial program (like Microsoft Money) cannot share the addresses of money recipients with the addresses supported in the email contacts folder (for example, Microsoft Outlook). Indeed, many users have several devices, and it would be logical if they synchronized their personal data between them and through an extensive set of additional devices, including cell phones, for such commercial services as MSN and AOL; However, to work with public documents, you basically have to attach documents to e-mail messages, i.e. act manually and ineffectively.

Одна из причин такого недостатка сотрудничества, свойственного традиционным подходам к организации информации в компьютерных системах, сводится к использованию систем на основе файлов, папок и директорий ("файловых систем") для организации совокупностей файлов в директорные иерархические структуры папок на основании абстракции физической организации среды хранения, используемой для хранения файлов. Операционная система Multics, разработанная в 60-х годах, впервые использовала файлы, папки и директории для манипулирования сохраняемыми единицами данных на уровне операционной системы. В частности, Multics использовала символические адреса в иерархии файлов (тем самым введя идею пути к файлу), где физические адреса файлов не были прозрачны для пользователя (приложений и конечных пользователей). Эта файловая система никаким образом не была связана с форматом файла для какого-либо отдельного файла, и отношения между файлами не рассматривались на уровне операционной системы (т.е. не относились к положению файла в иерархии). С появлением Multics сохраняемые данные стали организовывать в файлы, папки и директории на уровне операционной системы. Эти файлы, в общем случае, включают в себя саму иерархию файлов («директорию»), воплощенную в особом файле, поддерживаемом файловой системой. Эта директория, в свою очередь, поддерживает список записей, соответствующих всем остальным файлам в директории и положению узла таких файлов в иерархии (именуемых здесь папками). Таким было состояние техники в течение приблизительно сорока лет.One of the reasons for this lack of cooperation, which is typical of traditional approaches to organizing information in computer systems, is to use file-based systems, folders and directories (“file systems”) to organize sets of files into director hierarchical folder structures based on the abstraction of the physical organization of the storage environment used to store files. The Multics operating system, developed in the 60s, first used files, folders, and directories to manipulate stored data units at the operating system level. In particular, Multics used symbolic addresses in the file hierarchy (thereby introducing the idea of a file path), where the physical addresses of the files were not transparent to the user (applications and end users). This file system was in no way associated with the file format for any single file, and the relationship between the files was not considered at the operating system level (i.e., did not relate to the position of the file in the hierarchy). With the advent of Multics, the stored data began to be organized into files, folders and directories at the operating system level. These files, in general, include the file hierarchy itself (the “directory”) embodied in a special file supported by the file system. This directory, in turn, maintains a list of entries corresponding to all other files in the directory and the node position of such files in the hierarchy (referred to as folders here). This has been the state of the art for about forty years.

Хотя файловая система обеспечивает разумное представление информации, размещенной в физической системе хранения компьютера, она, тем не менее, является абстракцией этой физической системы хранения, вследствие чего для использования файлов требуется уровень опосредования (интерпретации) между тем, чем манипулирует пользователь (единицы, имеющие контекст, признаки и отношения к другим единицам), и тем, что обеспечивает операционная система (файлами, папками и директориями). Поэтому пользователям (приложениям и/или конечным пользователям) ничего не остается, как вводить единицы информации в структуру файловой системы, даже если это неэффективно, неадекватно или нежелательно по какой-либо причине. Кроме того, существующим файловым системам мало что известно о структуре данных, хранящихся в отдельных файлах и, в результате, большая часть информации остается запертой в файлах, доступных (и понятных) только для приложений, которые их записали. Таким образом, недостаток схематического описания информации и механизмов манипулирования информацией приводит к созданию бункеров данных с очень малой возможностью совместного использования данных между отдельными бункерами. Например, многие пользователи персональных компьютеров (ПК) имеют более пяти различных хранилищ, в которых содержится информация о людях, с которыми они общаются на некотором уровне, например Outlook Contacts, адреса онлайнового эккаунта, Windows Address Book, Quicken Payees, и списки друзей службы мгновенного обмена сообщениями (IM), поскольку организация файлов представляет значительную трудность для этих пользователей ПК. Поскольку в большинстве существующих файловых систем используется модель вложенных папок для организации файлов и папок, по мере возрастания количества файлов, усилия, необходимые для поддержания гибкой и эффективной схемы организации, многократно возрастают. При этом было бы весьма полезно иметь несколько классификаций одного файла; однако использование жестких или мягких связей в существующих файловых системах весьма неудобно и трудно осуществимо.Although the file system provides a reasonable representation of the information stored in the physical storage system of the computer, it is nevertheless an abstraction of this physical storage system, as a result of which the use of files requires a level of mediation (interpretation) between what the user manipulates (units having context , signs and relationships to other units), and what the operating system provides (files, folders, and directories). Therefore, users (applications and / or end users) have no choice but to enter units of information into the file system structure, even if it is inefficient, inadequate, or undesirable for any reason. In addition, the existing file systems know little about the structure of data stored in separate files and, as a result, most of the information remains locked in files that are accessible (and understandable) only for the applications that recorded them. Thus, the lack of a schematic description of information and information manipulation mechanisms leads to the creation of data silos with very little possibility of sharing data between individual silos. For example, many personal computer (PC) users have more than five different repositories that contain information about the people they chat with at some level, such as Outlook Contacts, online account addresses, Windows Address Book, Quicken Payees, and instant messenger friends lists messaging (IM), since organizing files is a significant challenge for these PC users. Since most existing file systems use a subfolder model to organize files and folders, as the number of files increases, the effort required to maintain a flexible and efficient organization scheme increases many times over. In this case, it would be very useful to have several classifications of one file; however, using hard or soft links in existing file systems is very inconvenient and difficult to implement.

Ранее было предпринято несколько неудачных попыток исправить недостатки файловых систем. Некоторые из этих предыдущих попыток предполагали использование контентно-адресуемой памяти для обеспечения механизма, позволяющего обращаться к данным по контенту, а не по физическому адресу. Однако эти усилия оказались безуспешными, поскольку, хотя контентно-адресуемая память оказалась полезной для маломасштабного использования такими устройствами, как блоки кэш-памяти и блоки управления памятью, крупномасштабное использование для таких устройств как физические среды хранения, все же было невозможно по ряду причин и, следовательно, такого решения просто не существует. Были предприняты попытки использовать системы объектно-ориентированной базы данных (OODB), но эти попытки, несмотря на сильные стороны базы данных и хорошие нефайловые представления, оказались неэффективными при обработке файловых представлений и не смогли сравниться по скорости, эффективности и простоте с иерархической структурой на основе папок на уровне системы программно-аппаратного интерфейса. Другие попытки, например попытки использовать SmallTalk (и другие производные), оказались весьма эффективными при обработке файловых и нефайловых представлений, но им не хватало признаков баз данных, необходимых, чтобы эффективно организовывать и использовать отношения, существующие между различными файлами данных, вследствие чего общая эффективность таких систем оказалась неприемлемой. Были попытки использовать BeOS (и другие подобные разработки операционных систем), которые оказались неадекватными при обработке нефайловых представлений - страдали теми же недостатками, что и традиционные файловые системы - несмотря на способность адекватно представлять файлы, обеспечивая в то же время некоторые необходимые признаки баз данных.Earlier, several unsuccessful attempts were made to fix file system flaws. Some of these previous attempts have involved the use of content-addressable memory to provide a mechanism for accessing data by content rather than by physical address. However, these efforts were unsuccessful because, although the content-addressable memory was useful for small-scale use by devices such as cache blocks and memory management blocks, large-scale use for devices such as physical storage media was still impossible for a number of reasons and, therefore, such a solution simply does not exist. Attempts were made to use object-oriented database systems (OODB), but these attempts, despite the strengths of the database and good non-file representations, were ineffective in processing file representations and could not be compared in speed, efficiency, and simplicity with a hierarchical structure based on folders at the system level of the hardware-software interface. Other attempts, such as attempts to use SmallTalk (and other derivatives), proved to be very effective in processing file and non-file representations, but they lacked the database features needed to efficiently organize and use the relationships existing between different data files, resulting in overall efficiency such systems proved to be unacceptable. There were attempts to use BeOS (and other similar development of operating systems) that turned out to be inadequate when processing non-file representations - they suffered the same drawbacks as traditional file systems - despite the ability to adequately represent files, while providing some necessary database features.

Технология баз данных - это другая область техники, в которой существуют сходные трудности. Например, хотя модель реляционной базы данных получила большой коммерческий успех, в действительности, независимые поставщики программного обеспечения (ISV) обычно используют незначительную часть функциональных возможностей программных продуктов реляционной базы банных (например, Microsoft SQL Server). Напротив, большинство приложений взаимодействует с таким продуктом посредством таких простых команд, как "gets" и "puts". Хотя для этого существует ряд очевидных причин, например недоверие к платформе или базе данных, одна ключевая причина, которая часто остается незамеченной, состоит в том, что база данных не всегда обеспечивает именно те абстракции, которые нужны большинству поставщиков коммерческих приложений. Например, тогда как реальный мир оперирует понятием «статей», например, «потребителей» или «порядками» (совместно с внедренными «строчными статьями» порядка в качестве статей в или их самих), реляционные базы данных оперируют только терминами таблиц и строк. Поэтому, в то время как приложению могут потребоваться аспекты согласованности, блокировки, безопасности и/или триггеров на уровне статей (и пр.), в общем случае базы данных обеспечивают эти признаки только на уровне таблиц/строк. Хотя это может хорошо работать, если каждая статья отображается в одну строку в некоторой таблице базы данных, в случае порядка с множественными строчными статьями, по той или иной причине статья в действительности отображается на множественные таблицы и, при этом, простая система реляционной базы данных не вполне обеспечивает правильные абстракции. Поэтому приложение должно построить логику над базой данных для обеспечения этих основных абстракций. Другими словами, основная реляционная модель не обеспечивает достаточной платформы для хранения данных, на которой можно легко разрабатывать приложения более высокого уровня, поскольку основная реляционная модель требует уровня опосредования между приложением и системой хранения, где семантическая структура данных может быть видна в приложении в определенных случаях. Хотя некоторые поставщики баз данных встраивают в свои продукты функциональные возможности более высокого уровня, например, обеспечивая реляционные возможности объектов, новые организационные модели и т.п., ни один из них до сих пор не обеспечил необходимого исчерпывающего решения, причем истинно исчерпывающее решение это то, которое обеспечивает как полезные абстракции модели данных (например, «статьи», «расширения», «отношения» и т.д.) для полезных абстракций домена (например, «личности», «места», «события» и т.д.).Database technology is another area of technology in which similar difficulties exist. For example, although the relational database model has gained great commercial success, in reality, independent software vendors (ISVs) typically use a small fraction of the functionality of relational database software products (for example, Microsoft SQL Server). On the contrary, most applications interact with such a product through simple commands such as “gets” and “puts”. Although there are a number of obvious reasons for this, such as a lack of confidence in a platform or database, one key reason that often goes unnoticed is that the database does not always provide exactly the abstractions that most commercial application providers need. For example, while the real world uses the concept of “articles”, for example, “consumers” or “orders” (together with the introduced “lowercase articles” of order as articles in or themselves), relational databases operate only in terms of tables and rows. Therefore, while an application may require aspects of consistency, blocking, security, and / or triggers at the article level (etc.), in the general case, databases provide these attributes only at the table / row level. Although this may work well if each entry is displayed on a single row in some database table, in the case of an order with multiple lowercase entries, for one reason or another the entry is actually displayed on multiple tables and, at the same time, a simple relational database system does not fully provides the correct abstraction. Therefore, the application must build logic over the database to provide these basic abstractions. In other words, the basic relational model does not provide a sufficient platform for storing data on which it is easy to develop higher-level applications, since the basic relational model requires a mediation level between the application and the storage system, where the semantic data structure can be seen in the application in certain cases. Although some database vendors integrate higher-level functionality into their products, for example, providing relational capabilities of objects, new organizational models, etc., none of them has yet provided the necessary comprehensive solution, and a true comprehensive solution is which provides useful data model abstractions (for example, “articles”, “extensions”, “relationships”, etc.) for useful domain abstractions (for example, “persons”, “places”, “events”, etc. .).

Ввиду вышеуказанных недостатков существующих технологий хранения и баз данных необходима новая платформа хранения, обеспечивающая улучшенную способность к организации, поиску и совместному использованию всех типов данных в компьютерной системе - платформа хранения, которая расширяет платформу данных за пределы существующих файловых систем и систем баз данных и которая призвана быть хранилищем для всех типов данных. Настоящее изобретение удовлетворяет эту потребность.In view of the above-mentioned shortcomings of existing storage technologies and databases, a new storage platform is needed that provides improved ability to organize, search and share all types of data in a computer system - a storage platform that extends the data platform beyond existing file systems and database systems and which is designed to be a repository for all data types. The present invention satisfies this need.

Сущность изобретенияSUMMARY OF THE INVENTION

В нижеследующем разделе «сущность изобретения» предусмотрен обзор различных аспектов изобретения. Он не призван обеспечивать исчерпывающего описания всех важных аспектов изобретения, а также определять объем изобретения. Напротив, этот раздел служит введением в нижеследующие подробное описание и чертежи.The following Summary of the Invention provides an overview of various aspects of the invention. It is not intended to provide an exhaustive description of all important aspects of the invention, nor to determine the scope of the invention. On the contrary, this section serves as an introduction to the following detailed description and drawings.

Настоящее изобретение относится к платформе хранения для организации, поиска и совместного использования данных. Платформа хранения согласно настоящему изобретению расширяет понятие хранения данных за пределы существующих файловых систем и систем баз данных и призвана быть хранилищем для всех типов данных, включая структурированные, неструктурированные или частично структурированные данные.The present invention relates to a storage platform for organizing, searching and sharing data. The storage platform according to the present invention extends the concept of data storage beyond existing file systems and database systems and is intended to be a storage for all types of data, including structured, unstructured or partially structured data.

Согласно одному аспекту настоящего изобретения платформа хранения настоящего изобретения содержит хранилище данных, реализованное на машине базы данных. Согласно различным вариантам осуществления настоящего изобретения машина базы данных содержит машину реляционной базы данных с реляционными расширениями объекта. Хранилище данных реализует модель данных, которая поддерживает организацию, поиск, совместное использование, синхронизацию и защиту данных. Конкретные типы данных описаны в схемах, и платформа обеспечивает механизм для расширения множества схем для задания новых типов данных (в сущности подтипы основных типов обеспечиваются схемами). Возможность синхронизации способствует совместному использованию данных между пользователями или системами. Обеспечены возможности, аналогичные файловой системе, которые позволяют хранилищу данных взаимодействовать с существующими файловыми системами, но без ограничения такими традиционными файловыми системами. Механизм отслеживания изменений обеспечивает возможность отслеживать изменения в хранилище данных. Платформа хранения дополнительно содержит набор программных интерфейсов приложения, которые позволяют приложениям осуществлять доступ ко всем вышеупомянутым возможностям платформы хранения и доступ к данным, описанным в схемах.According to one aspect of the present invention, the storage platform of the present invention comprises a data warehouse implemented on a database machine. According to various embodiments of the present invention, the database engine comprises a relational database machine with relational object extensions. The data warehouse implements a data model that supports the organization, search, sharing, synchronization and data protection. Specific data types are described in the diagrams, and the platform provides a mechanism for expanding a plurality of diagrams to define new data types (in essence, subtypes of the main types are provided by diagrams). The ability to synchronize facilitates the sharing of data between users or systems. Features similar to the file system are provided that allow the data warehouse to interact with existing file systems, but without being limited to such traditional file systems. The change tracking mechanism provides the ability to track changes to the data warehouse. The storage platform additionally contains a set of application programming interfaces that allow applications to access all of the aforementioned storage platform capabilities and access the data described in the diagrams.

Согласно другому аспекту изобретения модель данных, реализованная посредством хранилища данных, задает единицы хранения данных в терминах статей, элементов и отношений. Статья является единицей данных, сохраняемой в хранилище данных, и может содержать один или более элементов и отношений. Элемент - это экземпляр типа, содержащий одно или более полей (также именуемых здесь свойствами). Отношение - это связь между двумя статьями (используемые здесь эти и другие конкретные термины могут писаться с заглавной буквы, чтобы их можно было отличить от других терминов, используемых в непосредственной близости; однако нет никакого намерения делать различия между термином, написанным с заглавной буквы, например «Статья», и тем же термином, написанным со строчной буквы, например «статья», и никакие такие различия не предполагаются и не подразумеваются).According to another aspect of the invention, a data model implemented through a data warehouse defines storage units in terms of articles, elements, and relationships. An article is a unit of data stored in a data warehouse and may contain one or more elements and relationships. An element is an instance of a type containing one or more fields (also referred to as properties here). A relationship is the relationship between two articles (these and other specific terms used here can be capitalized so that they can be distinguished from other terms used in the immediate vicinity; however, there is no intention to distinguish between a capitalized term, for example “Article”, and the same term written in lowercase, for example “article”, and no such differences are implied or implied).

Согласно другому аспекту изобретения компьютерная система содержит совокупность Статей, причем каждая Статья содержит дискретную сохраняемую единицу информации, которой может манипулировать система программно-аппаратного интерфейса; совокупность Папок статей, которые образуют организационную структуру упомянутых Статей; и систему программно-аппаратного интерфейса для манипулирования совокупностью Статей, причем каждая Статья принадлежит, по меньшей мере, одной Папке статей и может принадлежать более, чем одной Папке статей.According to another aspect of the invention, a computer system comprises a plurality of Articles, each Article containing a discrete, stored unit of information that can be manipulated by a hardware-software interface system; the totality of the Folders of articles that form the organizational structure of the said Articles; and a software and hardware interface system for manipulating a set of Articles, each Article belonging to at least one Article Folder and may belong to more than one Article Folder.

Согласно другому аспекту изобретения компьютерная система содержит совокупность Статей, причем каждая Статья содержит дискретную сохраняемую единицу информации, которой может манипулировать система программно-аппаратного интерфейса, и Статья или некоторые из значений свойства Статьи вычисляются динамически, а не выводятся из постоянного хранилища. Другими словами, система программно-аппаратного интерфейса не требует сохранения Статьи, и поддерживаются определенные операции, например, способность перечислять текущее множество Статей или способность извлекать Статью по ее идентификатору (который более полно описан в разделах, где описан программный интерфейс приложения или API) платформы хранения - например, Статьей может быть текущее местоположение сотового телефона или температура, считанная датчиком температуры.According to another aspect of the invention, a computer system comprises a collection of Articles, each Article containing a discrete, stored unit of information that can be manipulated by a hardware-software interface system, and an Article or some of the property values of an Article are dynamically calculated and not removed from the persistent storage. In other words, the system of the hardware-software interface does not require saving the Article, and certain operations are supported, for example, the ability to list the current set of Articles or the ability to retrieve an Article by its identifier (which is more fully described in the sections where the application programming interface or API is described) of the storage platform - for example, the Article may be the current location of the cell-phone or the temperature read by the temperature sensor.

Согласно другому аспекту изобретения система программно-аппаратного интерфейса для компьютерной системы, причем упомянутая система программно-аппаратного интерфейса манипулирует совокупностью Статей, дополнительно содержит Статьи, связанные между собой совокупностью Отношений, которыми управляет система программно-аппаратного интерфейса. Согласно другому аспекту изобретения предоставляется система программно-аппаратного интерфейса для компьютерной системы, причем упомянутая система программно-аппаратного интерфейса манипулирует совокупностью дискретных единиц информации, имеющих свойства, понимаемые системой программно-аппаратного интерфейса. Согласно другому аспекту изобретения система программно-аппаратного интерфейса для компьютерной системы содержит схему ядра для задания множества Статей ядра, которые упомянутая система программно-аппаратного интерфейса понимает и может непосредственно обрабатывать в заранее определенном и предсказуемом порядке. Согласно другому аспекту изобретения раскрыт способ манипулирования совокупностью дискретных единиц информации («Статей») в системе программно-аппаратного интерфейса для компьютерной системы, причем способ содержит взаимосвязывание упомянутых Статей посредством совокупности Отношений и управление этими Отношениями на уровне системы программно-аппаратного интерфейса.According to another aspect of the invention, a hardware-software interface system for a computer system, said software-hardware interface system manipulating a plurality of Articles, further comprises Articles related to each other by a plurality of Relationships controlled by a software-hardware interface system. According to another aspect of the invention, a software-hardware interface system for a computer system is provided, said software-hardware interface system manipulating a plurality of discrete units of information having properties understood by a software-hardware interface system. According to another aspect of the invention, a software-hardware interface system for a computer system comprises a kernel circuit for defining a plurality of Core Articles that the software-hardware interface system understands and can directly process in a predetermined and predictable order. According to another aspect of the invention, a method is disclosed for manipulating a collection of discrete information units (“Articles”) in a software-hardware interface system for a computer system, the method comprising interconnecting said Articles through a set of Relations and managing these Relations at the level of a software-hardware interface system.

Согласно другому признаку изобретения API платформы хранения обеспечивает классы данных для каждой статьи, расширения статьи и отношения, заданных в множестве схем платформы хранения. Кроме того, программный интерфейс приложения обеспечивает множество классов структур, которые задают общее множество поведений для классов данных и которые, совместно с классами данных, обеспечивают основную модель программирования для API платформы хранения. Согласно другому признаку изобретения API платформы хранения обеспечивает упрощенную модель запроса, которая позволяет разработчикам прикладных программ формировать запросы на основании различных свойств статей в хранилище данных, при этом разработчик прикладной программы изолирован от подробностей языка запроса нижележащей машины базы данных. Согласно еще одному аспекту API платформы хранения согласно настоящему изобретению API собирает изменения в статье, внесенные прикладной программой, после чего организует их в правильные обновления, необходимые машине базы данных (или машине хранения любого вида), на которой реализовано хранилище данных. Это позволяет разработчикам прикладных программ производить изменения статьи в памяти, оставляя API сложные аспекты обновлений хранилища данных.According to another feature of the invention, the storage platform API provides data classes for each article, article extension, and relationship defined in a variety of storage platform schemas. In addition, the application programming interface provides many structure classes that define a common set of behaviors for data classes and which, together with data classes, provide a basic programming model for the storage platform API. According to another feature of the invention, the storage platform API provides a simplified query model that allows application developers to generate queries based on various properties of articles in a data warehouse, while the application developer is isolated from the details of the query language of the underlying database machine. According to another aspect of the storage platform API according to the present invention, the API collects the changes to the article made by the application program, and then organizes them into the correct updates required by the database machine (or storage machine of any kind) on which the data warehouse is implemented. This allows application developers to make changes to the article in memory, leaving the API complex aspects of data warehouse updates.

Благодаря своей общей основе хранения и схематизированным данным платформа хранения согласно настоящему изобретению позволяет более эффективно разрабатывать приложение для потребителей, специалистов в области информационных технологий и предприятий. Она обеспечивает богатый и расширяемый программный интерфейс приложения, который не только делает доступными возможности, свойственные этой модели данных, но также охватывает и расширяет существующие файловую систему и методы доступа к базе данных.Due to its common storage foundation and schematized data, the storage platform according to the present invention allows more efficiently developing an application for consumers, IT professionals and enterprises. It provides a rich and extensible application programming interface that not only makes available the features inherent in this data model, but also extends and extends the existing file system and database access methods.

Другие признаки и преимущества изобретения следуют из нижеследующего подробного описания изобретения и прилагаемых чертежей.Other features and advantages of the invention follow from the following detailed description of the invention and the accompanying drawings.

Краткое описание чертежейBrief Description of the Drawings

Вышеизложенную сущность изобретения, а также нижеследующее подробное описание изобретения можно лучше понять совместно с прилагаемыми чертежами. В целях иллюстрации изобретения на чертежах показаны иллюстративные варианты осуществления различных аспектов изобретения; однако изобретение не ограничивается раскрытыми конкретными способами и инструментариями. На чертежах:The foregoing summary of the invention, as well as the following detailed description of the invention, can be better understood in conjunction with the accompanying drawings. To illustrate the invention, illustrative embodiments of various aspects of the invention are shown in the drawings; however, the invention is not limited to the specific methods and tools disclosed. In the drawings:

фиг.1 - блок-схема компьютерной системы, в которую можно включить аспекты настоящего изобретения;figure 1 is a block diagram of a computer system in which you can include aspects of the present invention;

фиг.2 - блок-схема компьютерной системы, разделенной на три компонента: аппаратный компонент, компонент системы программно-аппаратного интерфейса и компонент прикладных программ;figure 2 is a block diagram of a computer system divided into three components: a hardware component, a component of a software-hardware interface system and a component of application programs;

фиг.2А - традиционная древовидная иерархическая структура файлов, сгруппированных в папки в директории в операционной системе на основе файлов;figa is a traditional tree-like hierarchical structure of files grouped into folders in a directory in a file-based operating system;

фиг.3 - блок-схема платформы хранения согласно настоящему изобретению;figure 3 is a block diagram of a storage platform according to the present invention;

фиг.4 - структурное соотношение между Статьями, Папками статей и Категориями согласно различным вариантам осуществления настоящего изобретения;4 is a structural relationship between Articles, Article Folders, and Categories according to various embodiments of the present invention;

фиг.5А - блок-схема структуры Статьи;figa is a block diagram of the structure of the Article;

фиг.5В - блок-схема сложных типов свойств Статьи, показанной на фиг.5А;figv is a block diagram of complex types of properties of the Article shown in figa;

фиг.5С - блок-схема Статьи «положение», в которой дополнительно описаны ее сложные типы (перечисленные в явном виде);figs is a block diagram of the Article "position", which further describes its complex types (listed explicitly);

фиг.6А - иллюстрирует Статью как подтип Статья в Базовой схеме;figa - illustrates the Article as a subtype of the Article in the Basic scheme;

фиг.6В - блок-схема подтипа Статья, показанного в фиг.6А, в которой в явном виде перечислены его собственные типы (помимо его прямых свойств);figv is a block diagram of a subtype of the Article shown in figa, which explicitly lists its own types (in addition to its direct properties);

фиг.7 - блок-схема Базовой схемы, включающей в себя два ее типа классов верхнего уровня, Item и PropertyBase, и выведенные из них дополнительные типы Базовой схемы;7 is a block diagram of the Basic scheme, including its two types of top-level classes, Item and PropertyBase, and additional types of the Basic scheme derived from them;

фиг.8А - блок-схема, иллюстрирующая Статьи в Схеме ядра;figa is a block diagram illustrating Articles in the kernel;

фиг.8В - блок-схема, иллюстрирующая типы свойств в Схеме ядра;Fig. 8B is a block diagram illustrating property types in a kernel diagram;

фиг.9 - блок-схема, иллюстрирующая Папку статей, входящие в нее статьи и отношения взаимосвязи между Папкой статей и входящими в нее статьями;Fig.9 is a block diagram illustrating the Folder of articles, its articles and the relationship between the Folder of articles and its articles;

фиг.10 - блок-схема, иллюстрирующая Категорию (которая, в свою очередь, сама является статьей), входящие в нее статьи и отношения взаимосвязи между Категорией и входящими в нее статьями;10 is a block diagram illustrating a Category (which, in turn, is an article itself), the articles included in it, and the relationship between the Category and the articles included in it;

фиг.11 - диаграмма, иллюстрирующая иерархию типов ссылки модели данных платформы хранения, согласно настоящему изобретению;11 is a diagram illustrating a hierarchy of link types of a data model of a storage platform according to the present invention;

фиг.12 - диаграмма, иллюстрирующая, как классифицирующая отношения, согласно варианту осуществления настоящего изобретения;12 is a diagram illustrating how classifying relationships according to an embodiment of the present invention;

фиг.13 - диаграмма, иллюстрирующая механизм извещения, согласно варианту осуществления настоящего изобретения;13 is a diagram illustrating a notification mechanism according to an embodiment of the present invention;

фиг.14 - диаграмма, иллюстрирующая пример, в котором две транзакции вставляют новую запись в одно и то же бинарное дерево;Fig. 14 is a diagram illustrating an example in which two transactions insert a new record into the same binary tree;

фиг.15 - иллюстрирует процесс обнаружения изменения данных согласно варианту осуществления настоящего изобретения;FIG. 15 illustrates a data change detection process according to an embodiment of the present invention; FIG.

фиг.16 - пример дерева директории;Fig. 16 is an example of a directory tree;

фиг.17 - пример, в котором существующая папка файловой системы на основе директории перемещается в хранилище данных платформы хранения согласно аспекту настоящего изобретения;17 is an example in which an existing directory-based file system folder is moved to a storage platform data store in accordance with an aspect of the present invention;

фиг.18 - иллюстрирует понятие Папок включения согласно варианту осуществления настоящего изобретения;Fig. 18 illustrates the concept of Enable Folders according to an embodiment of the present invention;

фиг.19 - иллюстрирует основную архитектуру API платформы хранения;FIG. 19 illustrates a basic architecture of a storage platform API; FIG.

фиг.20 - схематически представляет различные компоненты стека API платформы хранения;FIG. 20 schematically represents various components of a storage platform API stack;

фиг.21A и 21B - графическое представление иллюстративной Схемы контактов (Статей и Элементов);figa and 21B is a graphical representation of an illustrative Scheme of contacts (Articles and Elements);

фиг.22 - структура среды выполнения API платформы хранения согласно аспекту настоящего изобретения;FIG. 22 is a structure of a storage platform API runtime in accordance with an aspect of the present invention; FIG.

фиг.23 - иллюстрирует выполнение операции FindAll согласно варианту осуществления настоящего изобретения;Fig. 23 illustrates the execution of a FindAll operation according to an embodiment of the present invention;

фиг.24 - иллюстрирует процесс генерации классов API платформы хранения из схемы платформы хранения согласно аспекту настоящего изобретения;24 illustrates a process for generating storage platform API classes from a storage platform diagram in accordance with an aspect of the present invention;

фиг.25 - схема, на которой основана File API, согласно другому аспекту настоящего изобретения;25 is a diagram on which the File API is based, according to another aspect of the present invention;

фиг.26 - диаграмма формата маски доступа, используемой в целях защиты данных, согласно варианту осуществления настоящего изобретения;FIG. 26 is a diagram of a format of an access mask used to protect data according to an embodiment of the present invention; FIG.

фиг.27 (a), (b), и (c) - изображают новые одинаково защищенные области безопасности, вырезанные из существующей области безопасности, согласно варианту осуществления одного аспекта настоящего изобретения;27 (a), (b), and (c) depict new equally protected security areas cut from an existing security area according to an embodiment of one aspect of the present invention;

фиг.28 - диаграмма, иллюстрирующая понятие вида поиска Статьи, согласно варианту осуществления одного аспекта настоящего изобретения;28 is a diagram illustrating a concept of a search type of an Article according to an embodiment of one aspect of the present invention;

фиг.29 - диаграмма иллюстративной иерархии статей согласно варианту осуществления настоящего изобретения.Подробное описание изобретения29 is a diagram of an illustrative article hierarchy according to an embodiment of the present invention. Detailed Description of the Invention

СодержаниеContent

I. ВведениеI. Introduction

А. Иллюстративная вычислительная средаA. Illustrative computing environment

В. Традиционное хранение на основе файловB. Traditional file-based storage

II. НОВАЯ ПЛАТФОРМА ХРАНЕНИЯ ДЛЯ ОРГАНИЗАЦИИ, ПОИСКА И СОВМЕСТНОГО ИСПОЛЬЗОВАНИЯ ДАННЫХII. NEW STORAGE PLATFORM FOR ORGANIZING, SEARCHING AND JOINT USE OF DATA

А. ГлоссарийA. Glossary

В. Обзор платформы храненияB. Storage platform overview

С. МОДЕЛЬ ДАННЫХC. DATA MODEL

1. Статьи1. Articles

2. Идентификация статьи2. Article identification

а) Ссылки на статьюa) Links to the article

(1) ItemIDReference(1) ItemIDReference

(2) ItemPathReference(2) ItemPathReference

b) Иерархия типов ссылкиb) Link type hierarchy

3. Папки статей и Категории3. Article folders and Categories

4. Схемы4. Schemes

a) Базовая схемаa) Basic scheme

b) Схема ядраb) Kernel layout

5. Отношения5. Relations

a) Декларация отношенияa) Declaration of relationship

b) Отношение поддержкиb) Support attitude

с) Отношения внедренияc) Implementation Relations

е) Правила и ограниченияe) Rules and restrictions

f) Упорядочение отношенийf) Streamlining relationships

6. Расширяемость6. Extensibility

a) Расширения статьиa) Article extensions

b) Расширение типов вложенных элементовb) Extension of types of nested elements

D. МАШИНА БАЗЫ ДАННЫХD. DATABASE MACHINE

1. Реализация хранилища данных с использованием UDT1. Implementing a data warehouse using UDT

2. Отображение статей2. Display articles

3. Отображение расширений3. Display extensions

4. Отображение вложенных элементов4. Display of nested elements

5. Идентификация объекта5. Object identification

6. Именование объектов SQL6. Naming SQL objects

7. Именование столбцов7. Naming columns

8. Виды поиска8. Types of search

а) Статьяa) Article

(1) Главный вид поиска статьи(1) The main type of article search

(2) Типизированные виды поиска статьи(2) Typed Article Search Types

b) Расширения статьиb) Article extensions

(1) Главный вид поиска расширения(1) Main view of extension search

(2) Типизированные виды поиска расширения(2) Typed extension search types

c) Вложенные элементыc) Nested elements

d) Отношенияd) Relationships

(1) Главный вид поиска отношения(1) The main type of relationship search

(2) Виды поиска экземпляра отношения(2) Types of relationship instance search

9. Обновления9. Updates

10. Отслеживание изменений и надгробия10. Track changes and gravestones

а) Отслеживание измененийa) Change tracking

(1) Отслеживание изменений в «главных» видах поиска(1) Track changes in the “main” types of searches

(2) Отслеживание изменений в «типизированных» видах поиска(2) Tracking changes in typed search types

b) Надгробияb) Tombstones

(1) Надгробия статей(1) Tombstones articles

(2) Надгробия расширений(2) Gravestone extensions

(3) Надгробия отношений(3) Tombstones of a relationship

(4) Очистка надгробий(4) Tombstone Cleaning

11. API и функции помощника11. API and helper functions

а) Функция [System.Storage].GetItema) Function [System.Storage] .GetItem

b) Функция [System.Storage].GetExtensionb) Function [System.Storage] .GetExtension

с) Функция [System.Storage].GetRelationshipc) Function [System.Storage] .GetRelationship

12. Метаданные12. Metadata

а) Метаданные схемыa) Schema metadata

b) Метаданные экземпляраb) Instance metadata

Е. БезопасностьE. Security

1. Обзор1. Overview

2. Подробное описание модели безопасности2. Detailed description of the security model

a) Структура описателя безопасностиa) Security descriptor structure

(1) Формат маски доступа(1) Access mask format

(2) Общие права доступа(2) General permissions

(3) Стандартные права доступа(3) Standard access rights

b) Права, зависящие от статьиb) Article-specific rights

(1) Права, зависящие от объекта «файл» и «директория»(1) Rights depending on the object “file” and “directory”

(2) WinFSItemRead(2) WinFSItemRead

(3) WinFSItemReadAttributes(3) WinFSItemReadAttributes

(4) WinFSItemWriteAttributes(4) WinFSItemWriteAttributes

(5) WinFSItemWrite(5) WinFSItemWrite

(6) WinFSItemAddLink(6) WinFSItemAddLink

(7) WinFSItemDeleteLink(7) WinFSItemDeleteLink

(8) Права на удаление статьи(8) Rights to delete an article

(9) Права на копирование статьи(9) Rights to copy an article

(10) Права на перемещение статьи(10) Rights to Move Articles

(11) Права на просмотр политики безопасности на статье(11) Rights to view security policy on an article

(12) Права на изменение политики безопасности на статье(12) Rights to change security policy on the article

(13) Права, не имеющие прямого эквивалента(13) Rights not directly equivalent

3. Реализация3. Implementation

а) Создание новой статьи в контейнереa) Create a new article in the container

b) Добавление к статье явного ACLb) Adding an explicit ACL to the article

с) Добавление к статье отношения поддержкиc) Adding a support relationship to an article

d) Удаление отношения поддержки из статьиd) Removing a support relationship from an article

е) Удаление явного ACL из статьиf) Removing an explicit ACL from an article

f) Изменение ACL, связанного со статьейf) Change in ACL associated with an article

F. Извещения и отслеживание измененийF. Notification and Change Tracking

1. Сохранение событий изменения1. Saving change events

а) Событияa) Events

b) Наблюдателиb) Observers

2. Механизм отслеживания изменений и генерации извещений2. Change tracking and notification mechanism

а) Отслеживание измененийa) Change tracking

b) Управление метками времениb) Time stamp management

с) Обнаружение изменения данных - обнаружение событийc) Data change detection - event detection

G. СинхронизацияG. Sync

1. Синхронизация между платформами хранения1. Synchronization between storage platforms

а) Приложения управления синхронизациейa) Synchronization management applications

b) Аннотация схемыb) Annotation of the scheme

с) Конфигурация синхронизацииc) Sync configuration

(1) Папка сообщества - отображения(1) Community Folder - Mappings

(2) Профили(2) Profiles

(3) Расписания(3) Schedules

d) Обработка конфликтовd) Conflict handling

(1) Обнаружение конфликта(1) Conflict Detection

(а) Конфликты на основе знания(a) Knowledge-based conflicts

(b) Конфликты на основе ограничений(b) Conflict based conflicts

(2) Обработка конфликтов(2) Conflict Handling

(а) Автоматическое разрешение конфликтов(a) Automatic conflict resolution

(b) Регистрация конфликтов(b) Conflict Records

(с) Инспектирование и разрешения конфликтов(c) Inspection and resolution of conflicts

(d) Сходимость копий и распространение разрешений конфликтов(d) Convergence of copies and distribution of conflict resolution

2. Синхронизация с хранилищами данных, не связанными с платформой хранения2. Synchronization with data warehouses not related to the storage platform

а) Службы синхронизацииa) Sync services

(1) Перечисление изменений(1) Listing Changes

(2) Применение изменений(2) Application of changes

(3) Разрешение конфликтов(3) Conflict Resolution

b) Реализация адаптераb) adapter implementation

3. Безопасность3. Security

4. Управляемость4. Manageability

Н. Возможность взаимодействия с традиционными файловыми системамиH. Interoperability with traditional file systems

1. Модель возможности взаимодействия1. Interaction model

2. Особенности хранилища данных2. Data Warehouse Features

а) Не томa) Not that

b) Структура хранилищаb) Storage structure

с) Не все файлы мигрируютc) Not all files migrate

d) Доступ из пространства имен NTFS к файлам платформы храненияd) Access from the NTFS namespace to storage platform files

е) Ожидаемые буквы пространства имен/приводаe) The expected namespace / drive letters

I. API ПЛАТФОРМЫ ХРАНЕНИЯI. STORAGE PLATFORM API

1. Обзор1. Overview

2. Именование и области действия2. Naming and scopes

3. Компоненты API платформы хранения3. Storage Platform API Components

4. Классы данных4. Data classes

5. Структура среды выполнения5. The structure of the runtime environment

а) Классы структуры среды выполненияa) Runtime structure classes

(1) ItemContext(1) ItemContext

(2) ItemSearcher(2) ItemSearcher

(a) Целевой тип(a) Target type

(b) Фильтры(b) Filters

(с) Подготовка поисков(c) Preparing searches

(d) Опции Find(d) Find options

b) Структура среды выполнения в процессе работыb) Runtime structure during work

(1) Открытие и закрытие объектов ItemContext(1) Opening and closing ItemContext objects

(2) Поиск объектов(2) Object Search

(а) Опции поиска(a) Search options

(b) FindOne и FindOnly(b) FindOne and FindOnly

(с) Короткие вызовы поиска на ItemContext(c) Short search calls on ItemContext

(d) Нахождение по ИД или пути(d) Finding by ID or path

(е) Шаблон GetSearcher(f) GetSearcher Template

6. Безопасность6. Security

7. Поддержка отношений7. Relationship support

а) Базовые типы отношенийa) Basic types of relationships

(1) Класс Relationship(1) Relationship class

(2) Класс ItemReference(2) ItemReference Class

(3) Класс ItemIdReference(3) Class ItemIdReference

(4) Класс ItemPathReference(4) Class ItemPathReference

(5) Структура RelationshipId(5) RelationshipId Structure

(6) Класс VirtualRelationshipCollection(6) VirtualRelationshipCollection class

b) Сгенерированные типы отношенийb) Generated relationship types

(1) Сгенерированные типы отношений(1) Generated Relationship Types

(2) Класс RelationshipPrototype(2) RelationshipPrototype class

(3) Класс RelationshipPrototypeCollection(3) RelationshipPrototypeCollection Class

c) Поддержка отношений в классе Itemc) Relationship support in the class Item

(1) Класс Item(1) Item class

(2) Класс RelationshipCollection(2) RelationshipCollection class

d) Поддержка отношений в выражениях поискаd) Relationship support in search expressions

(1) Переход от статей к отношениям(1) Transition from articles to relationships

(2) Переход от отношений к статьям(2) Transition from relationship to articles

(3) Комбинирование обхода отношений(3) Combination of circumvention

е) Примеры использования поддержки отношенийe) Examples of using relationship support

(1) Поиск отношений(1) Relationship search

(2) Навигация от отношения к исходной и целевой статьям(2) Navigation from relationship to source and target articles

(3) Навигация от исходных статей к отношениям(3) Navigation from source articles to relationships

(4) Создание отношений (и статей)(4) Creating relationships (and articles)

(5) Удаление отношений (и статей)(5) Deleting relationships (and articles)

8. «Расширение» API платформы хранения8. "Extension" of the storage platform API

a) Поведения доменаa) Domain Behaviors

b) Поведения добавления значенийb) Add Value Behaviors

с) Поведения добавления значения как поставщики услугc) Value-adding behaviors as service providers

9. Структура среды разработки9. The structure of the development environment

10. Формализм запросов10. Request formalism

а) Основы фильтрацииa) Basics of filtration

b) Приведения типовb) Type casts

11. Удаленные операции11. Remote operations

а) Локальная/удаленная прозрачность в APIa) Local / remote transparency in the API

b) Реализация удаленных операций в платформе храненияb) Implementing remote operations on the storage platform

с) Доступ к хранилищам, не относящимся к платформе храненияc) Access to non-storage vaults

d) Отношение к DFSd) Relation to DFS

е) Отношение к GXA/Indigof) Attitude towards GXA / Indigo

12. Ограничения12. Limitations

13. Совместное использование13. Sharing

а) Представление совместно используемого ресурсаa) Presentation of a shared resource

b) Управление совместно используемыми ресурсамиb) Shared Resource Management

с) Доступ к совместно используемым ресурсамc) Access to shared resources

d) Обнаружимостьd) Detectability

14. Семантика Find14. Semantics of Find

15. API Contacts платформы хранения15. Storage platform Contacts API

а) Обзор System.Storage.Contacta) System.Storage.Contact Overview

b) Поведения доменаb) Domain Behavior

16. API File платформы хранения16. Storage Platform API File

а) Введениеa) Introduction

(1) Отражение тома NTFS в платформе хранения(1) Reflection of an NTFS volume on a storage platform

(2) Создание файлов и директорий в пространстве имен платформы хранения(2) Creating files and directories in the storage platform namespace

b) Схема файловb) File schema

с) Обзор System.Storage.Filesc) System.Storage.Files Overview

d) Примеры кодаd) Code examples

(1) Открытие файла и запись в него(1) Opening a file and writing to it

(2) Использование запросов(2) Using queries

e) Поведения доменаe) Domain Behaviors

J. ЗаключениеJ. Conclusion

I. ВведениеI. Introduction

Предмет настоящего изобретения описан конкретно, чтобы удовлетворять установленным требованиям. Однако само по себе описание не призвано ограничивать объем этого патента. Напротив, изобретатели предусматривают, что заявленный предмет можно воплощать и другими способами, включающими в себя другие этапы или сочетания этапов, аналогичных описанным в этом документе, совместно с другими современными или будущими технологиями. Кроме того, хотя термин «этап» можно использовать здесь в значении различных элементов применяемых способов, термин не следует интерпретировать как подразумевающий какой-либо конкретный порядок среди или между различными раскрытыми здесь этапами, если и пока порядок отдельных этапов не описан в явном виде.The subject of the present invention is specifically described in order to satisfy the established requirements. However, the description itself is not intended to limit the scope of this patent. In contrast, the inventors contemplate that the claimed subject matter can be embodied in other ways, including other steps or combinations of steps similar to those described in this document, together with other current or future technologies. In addition, although the term “step” can be used here to mean various elements of the methods used, the term should not be interpreted as implying any particular order among or between the various steps disclosed here, unless and until the order of the individual steps has been explicitly described.

А. Иллюстративная вычислительная средаA. Illustrative computing environment

На компьютере могут выполняться многочисленные варианты осуществления настоящего изобретения. Фиг.1 и нижеследующее описание призваны обеспечивать краткое общее описание подходящей среды вычислительной системы, в которой можно реализовать изобретение. Хотя это не требуется, различные аспекты изобретения можно описать в общем контексте компьютерно-выполняемых команд, например, программных модулей, выполняемых компьютером, например, клиентской рабочей станцией или сервером. В общем случае, программные модули включают в себя процедуры, программы, объекты, компоненты, структуры данных и т.д., которые выполняют определенные задачи или реализуют определенные абстрактные типы данных. Кроме того, изобретение можно осуществлять на практике в других конфигурациях компьютерной системы, включая карманные устройства, многопроцессорные системы, микропроцессорную или программируемую бытовую электронику, сетевые ПК, миникомпьютеры, универсальные компьютеры, и т.п. Изобретение также можно применять на практике в распределенных вычислительных средах, где задачи выполняются удаленными устройствами обработки, связанными друг с другом посредством сети передачи данных. В распределенной вычислительной среде программные модули размещаются как на локальных, так и на удаленных компьютерных запоминающих устройствах.Numerous embodiments of the present invention may be performed on a computer. Figure 1 and the following description are intended to provide a brief, general description of a suitable computing system environment in which the invention may be implemented. Although not required, various aspects of the invention can be described in the general context of computer-executable instructions, for example, program modules, executed by a computer, for example, a client workstation or server. In general, program modules include procedures, programs, objects, components, data structures, etc. that perform specific tasks or implement specific abstract data types. In addition, the invention can be practiced in other computer system configurations, including handheld devices, multiprocessor systems, microprocessor or programmable consumer electronics, network PCs, minicomputers, universal computers, and the like. The invention can also be applied in practice in distributed computing environments where tasks are performed by remote processing devices connected to each other via a data network. In a distributed computing environment, program modules are located on both local and remote computer storage devices.

Согласно фиг.1 иллюстративная вычислительная система общего назначения включает в себя традиционный персональный компьютер 20 и т.п., включающий в себя процессор 21, системную память 22 и системную шину 23, которая подключает различные компоненты системы, в том числе системную память, к процессору 21. Системная шина 23 может относиться к любому из нескольких типов шинных структур, включая шину памяти или контроллер памяти, периферийную шину и локальную шину с использованием различных шинных архитектур. Системная память включает постоянную память (ПЗУ) 24 и оперативную память (ОЗУ) 25. Базовая система ввода/вывода (BIOS) 26, содержащая основные процедуры, которые помогают переносить информацию между элементами компьютера, например, при запуске, обычно хранятся в ПЗУ 24. Персональный компьютер 20 также может включать в себя привод 27 жесткого диска, который считывает с или записывает на стационарный жесткий диск, который не показан, привод 28 магнитного диска, который считывает с или записывает на сменный магнитный диск 29, и привод 30 оптического диска, который считывает с или записывает на сменный оптический диск 31, например, CD-ROM или другой оптический носитель. Привод 27 жесткого диска, привод 28 магнитного диска и привод 30 оптического диска подключены к системной шине 23 посредством интерфейса 32 привода жесткого диска, интерфейса 33 привода магнитного диска и интерфейса 34 привода оптического диска, соответственно. Приводы и соответствующие компьютерно-считываемые среды обеспечивают энергонезависимое хранение компьютерно-считываемых команд, структур данных, программных модулей и других данных для персонального компьютера 20. Хотя в описанном здесь иллюстративном варианте осуществления используется жесткий диск, сменный магнитный диск 29 и сменный оптический диск 31, специалистам в данной области очевидно, что в иллюстративной форме также можно использовать другие типы компьютерно-считываемых носителей, на которых могут храниться данные, к которым может осуществлять доступ компьютер, например, магнитные кассеты, карты флэш-памяти, цифровые видеодиски, картриджи Бернулли, блоки оперативной памяти (ОЗУ), блоки постоянной памяти (ПЗУ) и т.п. Аналогично, иллюстративная среда может также включать в себя многочисленные типы устройств слежения, например тепловые датчики и системы безопасности и пожарной сигнализации, и другие источники информации. На жестком диске, магнитном диске 29, оптическом диске 31, в ПЗУ 24 или ОЗУ 25 могут храниться различные программные модули, в том числе операционная система 35, одна или несколько прикладных программ 36, другие программные модули 37 и программные данные 38. Пользователь может вводить команды и информацию в персональный компьютер 20 через устройства ввода, например клавиатуру 40 и указательное устройство 42. Другие устройства ввода (не показаны) могут включать в себя микрофон, джойстик, игровую панель, спутниковую антенну, сканер и т.п. Эти и другие устройства ввода часто подключены к процессору 21 через интерфейс 46 последовательного порта, который подключен к системной шине, но могут подключаться посредством других интерфейсов, например параллельного порта, игрового порта или универсальной последовательной шины (USB). Монитор 47 или устройство отображения другого типа также подключен к системной шине 23 через интерфейс, например видеоадаптер 48. Помимо монитора 47, персональные компьютеры обычно включают в себя другие периферийные устройства вывода (не показаны), например громкоговорители и принтеры. Иллюстративная система, показанная на фиг.1, также включает в себя хост-адаптер 55, шину 56 интерфейса малых компьютерных систем (SCSI) и внешнее запоминающее устройство 62, подключенное к шине 56 SCSI.1, a general-purpose illustrative computing system includes a traditional personal computer 20 and the like, including a processor 21, a system memory 22, and a system bus 23 that connects various components of the system, including system memory, to the processor 21. The system bus 23 may refer to any of several types of bus structures, including a memory bus or memory controller, a peripheral bus, and a local bus using various bus architectures. System memory includes read-only memory (ROM) 24 and random access memory (RAM) 25. Basic input / output system (BIOS) 26, which contains basic procedures that help transfer information between computer elements, for example, at startup, are usually stored in ROM 24. The personal computer 20 may also include a hard disk drive 27 that reads from or writes to a stationary hard disk that is not shown, a magnetic disk drive 28 that reads from or writes to a removable magnetic disk 29, and an optical disk drive 30 that reads from or writes to a removable optical disc 31, for example, a CD-ROM or other optical medium. The hard disk drive 27, the magnetic disk drive 28, and the optical disk drive 30 are connected to the system bus 23 via the hard disk drive interface 32, the magnetic disk drive interface 33, and the optical disk drive interface 34, respectively. Drives and associated computer-readable media provide non-volatile storage of computer-readable instructions, data structures, program modules, and other data for personal computer 20. Although the illustrative embodiment described herein uses a hard disk, removable magnetic disk 29, and removable optical disk 31, those skilled in the art in this area it is obvious that in the illustrative form, you can also use other types of computer-readable media on which data can be stored, which m can be accessed by a computer, such as magnetic cassettes, flash memory cards, digital video disks, Bernoulli cartridges, random access memories (RAM), permanent memories (ROM), etc. Similarly, an illustrative environment may also include numerous types of tracking devices, such as thermal sensors and security and fire alarm systems, and other information sources. Various software modules can be stored on the hard disk, magnetic disk 29, optical disk 31, ROM 24 or RAM 25, including the operating system 35, one or more application programs 36, other program modules 37 and program data 38. The user can enter commands and information to the personal computer 20 through input devices, such as a keyboard 40 and pointing device 42. Other input devices (not shown) may include a microphone, joystick, game pad, satellite dish, scanner, and the like. These and other input devices are often connected to the processor 21 via a serial port interface 46, which is connected to the system bus, but can be connected via other interfaces, for example a parallel port, a game port, or a universal serial bus (USB). A monitor 47 or other type of display device is also connected to the system bus 23 through an interface, such as a video adapter 48. In addition to the monitor 47, personal computers typically include other peripheral output devices (not shown), such as speakers and printers. The illustrative system shown in FIG. 1 also includes a host adapter 55, a small computer system interface (SCSI) bus 56, and an external storage device 62 connected to the SCSI bus 56.

Персональный компьютер 20 может работать в сетевой среде с использованием логических соединений с одним или несколькими удаленными компьютерами, например удаленным компьютером 49. Удаленный компьютер 49 может представлять собой другой персональный компьютер, сервер, маршрутизатор, сетевой ПК, равноправное устройство или другой общий сетевой узел, и обычно включает в себя многие или все элементы, описанные выше применительно к персональному компьютеру 20, хотя на фиг.1 показано только запоминающее устройство 50. Логические соединения, описанные на фиг.1, включают в себя локальную сеть (ЛС) 51 и глобальную сеть (ГС) 52. Такие сетевые среды обычно применяются в учреждениях, компьютерных сетях в масштабе предприятия, интрасетях и Интернете.The personal computer 20 may operate in a network environment using logical connections with one or more remote computers, such as a remote computer 49. The remote computer 49 may be another personal computer, server, router, network PC, peer device, or other common network node, and typically includes many or all of the elements described above with respect to the personal computer 20, although only storage device 50 is shown in FIG. 1. Logical connections describing nye in Figure 1 include a local area network (LAN) 51 and a wide area network (WAN) 52. Such networking environments are commonplace in offices, computer networks, enterprise-wide intranets and the Internet.

При использовании в сетевой среде ЛС персональный компьютер 20 подключен к ЛС 51 через сетевой интерфейс или адаптер 53. При использовании в сетевой среде ГС, персональный компьютер 20 обычно включает в себя модем 54 или другое средство установления связи в глобальной сети 52, например Интернете. Модем 54, который может быть внутренним или внешним, может быть подключен к системной шине 23 через интерфейс 46 последовательного порта. В сетевой среде программные модули, описанные применительно к персональному компьютеру 20, или часть из них могут храниться в удаленном запоминающем устройстве. Заметим, что показанные сетевые соединения являются иллюстративными, и можно использовать другие средства установления линии связи между компьютерами.When used in a LAN network environment, the personal computer 20 is connected to the LAN 51 via a network interface or adapter 53. When used in a LAN network environment, the personal computer 20 typically includes a modem 54 or other means of establishing communication in a global network 52, such as the Internet. The modem 54, which may be internal or external, may be connected to the system bus 23 via the serial port interface 46. In a networked environment, program modules described with respect to personal computer 20, or some of them, may be stored in a remote storage device. Note that the network connections shown are illustrative, and other means of establishing a communication link between computers can be used.

Согласно фиг.2 компьютерную систему 200 можно грубо разделить на три компонента: аппаратный компонент 202, компонент 204 системы программно-аппаратного интерфейса и компонент 206 прикладных программ (также именуемый здесь в некоторых контекстах «пользовательским компонентом» или «программным компонентом»).2, a computer system 200 can be roughly divided into three components: a hardware component 202, a software-hardware interface system component 204, and an application program component 206 (also referred to herein as a “user component” or “software component” here).

В различных вариантах осуществления компьютерной системы 200, согласно фиг.1, аппаратный компонент 202 может содержать центральный процессор (ЦП) 21, память (ПЗУ 24 и ОЗУ 25), базовую систему ввода/вывода (BIOS) 26 и различные устройства ввода/вывода (I/O), например клавиатуру 40, мышь 42, монитор 47 и/или принтер (не показан) и пр. Аппаратный компонент 202 содержит основную физическую инфраструктуру для компьютерной системы 200.In various embodiments of the computer system 200 of FIG. 1, the hardware component 202 may comprise a central processing unit (CPU) 21, memory (ROM 24 and RAM 25), a basic input / output system (BIOS) 26, and various input / output devices ( I / O), for example, a keyboard 40, a mouse 42, a monitor 47 and / or a printer (not shown), etc. The hardware component 202 contains the basic physical infrastructure for the computer system 200.

Компонент 206 прикладных программ содержит различные прикладные программы, включая, но без ограничения, компиляторы, системы баз данных, текстовые редакторы, коммерческие программы, видеоигры и т.д. Прикладные программы обеспечивают средства, позволяющие использовать компьютерные ресурсы для решения проблем, обеспечения решений и обработки данных для различных пользователей (машин, других компьютерных систем и/или конечных пользователей).The application component 206 contains various application programs, including but not limited to compilers, database systems, text editors, commercial programs, video games, etc. Application programs provide tools to use computer resources to solve problems, provide solutions and process data for various users (machines, other computer systems and / or end users).

Компонент системы программно-аппаратного интерфейса 204 содержит (и, в некоторых вариантах осуществления, может содержать исключительно) операционную систему, которая сама по себе содержит, в большинстве случаев, оболочку и ядро. "Операционная система" (ОС) это особая программа, которая выступает в качестве посредника между прикладными программами и компьютерным оборудованием. Компонент 204 системы программно-аппаратного интерфейса также может содержать менеджер виртуальной машины (VMM), общую среду выполнения языка (CLR) или ее функциональный эквивалент, виртуальную машину Java (JVM), или ее функциональный эквивалент, или другие программные компоненты вместо или помимо операционной системы в компьютерной системе. Целью системы программно-аппаратного интерфейса является обеспечение среды, в которой пользователь может выполнять прикладные программы. Цель любой системы программно-аппаратного интерфейса состоит в том, чтобы сделать компьютерную систему удобной для использования, а также эффективно использовать компьютерное оборудование.The system component of the hardware-software interface 204 contains (and, in some embodiments, may contain exclusively) an operating system, which itself contains, in most cases, a shell and a kernel. An "operating system" (OS) is a special program that acts as an intermediary between application programs and computer hardware. The hardware / software interface system component 204 may also include a virtual machine manager (VMM), a common language runtime (CLR) or its functional equivalent, a Java virtual machine (JVM), or its functional equivalent, or other software components instead of or in addition to the operating system in a computer system. The purpose of a hardware-software interface system is to provide an environment in which a user can execute application programs. The goal of any software-hardware interface system is to make the computer system user-friendly and to use computer equipment efficiently.

Система программно-аппаратного интерфейса обычно загружается в компьютерную систему при запуске, после чего управляет всеми прикладными программами в компьютерной системе. Прикладные программы взаимодействуют с системой программно-аппаратного интерфейса, запрашивая услуги через программный интерфейс приложения (API). Некоторые прикладные программы позволяют конечным пользователям взаимодействовать с системой программно-аппаратного интерфейса через пользовательский интерфейс, например командный язык или графический интерфейс пользователя (ГИП).A hardware-software interface system is usually loaded into a computer system at startup, after which it controls all application programs in a computer system. Application programs interact with the hardware-software interface system, requesting services through the application programming interface (API). Some application programs allow end users to interact with a hardware-software interface system through a user interface, such as a command language or graphical user interface (GUI).

Система программно-аппаратного интерфейса традиционно осуществляет различные услуги для приложений. В многозадачной системе программно-аппаратного интерфейса, где могут одновременно выполняться несколько программ, система программно-аппаратного интерфейса определяет, какие приложения должны действовать в каком порядке и сколько времени отпущено на каждое приложение до переключения на другое приложение в порядке очереди. Система программно-аппаратного интерфейса также управляет совместным использованием внутренней памяти среди множественных приложений и оперирует вводом и выводом в и из подключенных аппаратных устройств, например жестких дисков, принтеров и портов коммутируемого доступа. Система программно-аппаратного интерфейса также направляет каждому приложению (и, в определенном случае, конечному пользователю) сообщения относительно статуса операций и о любых ошибках, которые могут произойти. Система программно-аппаратного интерфейса также может брать на себя управление пакетными заданиями (например, печати), благодаря чему инициирующее приложение освобождается от этой работы и может возобновлять другую обработку и/или операции. На компьютерах, которые могут обеспечивать параллельную обработку, система программно-аппаратного интерфейса также управляет делением программы, чтобы она одновременно выполнялась на более чем одном процессоре.The hardware-software interface system traditionally provides various services for applications. In a multi-tasking system of a hardware-software interface, where several programs can be executed simultaneously, the system of a hardware-software interface determines which applications should act in what order and how much time is allotted to each application before switching to another application in a queue order. The hardware-software interface system also manages the sharing of internal memory among multiple applications and operates input and output to and from connected hardware devices, such as hard drives, printers, and dial-up ports. The hardware-software interface system also sends messages to each application (and, in a specific case, to the end user) regarding the status of operations and any errors that may occur. The hardware-software interface system can also take control of batch jobs (for example, printing), so that the initiating application is freed from this work and can resume other processing and / or operations. On computers that can provide parallel processing, the hardware-software interface system also controls the division of the program so that it runs simultaneously on more than one processor.

Оболочка системы программно-аппаратного интерфейса (именуемая здесь просто «оболочка») это интерактивный интерфейс конечного пользователя к системе программно-аппаратного интерфейса (оболочку также можно именовать «интерпретатором команд» или, в операционной системе, «оболочкой операционной системы»). Оболочка является внешним слоем системы программно-аппаратного интерфейса, к которому могут непосредственно обращаться прикладные программы и/или конечные пользователи. В отличие от оболочки ядро - это наиболее глубокий слой системы программно-аппаратного интерфейса, который непосредственно взаимодействует с аппаратными компонентами.A shell of a software-hardware interface system (referred to simply as a “shell”) is an interactive end-user interface to a system of a software-hardware interface (a shell can also be called a “command interpreter” or, in the operating system, “an operating system shell”). A shell is an external layer of a hardware-software interface system that can be directly accessed by application programs and / or end users. Unlike the shell, the kernel is the deepest layer of the system of the hardware-software interface, which directly interacts with hardware components.

Хотя предполагается, что многочисленные варианты осуществления настоящего изобретения особенно пригодны для компьютерных систем, ничто в этом документе не призвано ограничивать изобретение такими вариантами осуществления. Напротив, используемый здесь термин "компьютерная система" призван охватывать любые и все устройства, способные хранить и обрабатывать информацию и/или способные использовать сохраненную информацию для управления поведением или выполнением самого устройства, независимо от того, являются ли такие устройства по своей природе электронными, механическими, логическими или виртуальными.Although it is contemplated that numerous embodiments of the present invention are particularly suitable for computer systems, nothing in this document is intended to limit the invention to such embodiments. In contrast, the term "computer system" as used herein is intended to encompass any and all devices capable of storing and processing information and / or capable of using stored information to control the behavior or performance of the device itself, regardless of whether such devices are inherently electronic, mechanical logical or virtual.

В. Традиционное хранение на основе файловB. Traditional file-based storage

В большинстве современных компьютерных систем «файлы» - это единицы сохраняемой информации, которые могут включать в себя систему программно-аппаратного интерфейса, а также прикладные программы, наборы данных и пр. Во всех современных системах программно-аппаратного интерфейса (Windows, Unix, Linux, Mac OS, системах виртуальных машин и т.п.) файлы являются основными дискретными (сохраняемыми и извлекаемыми) единицами информации (например, данных, программ и т.п.), которыми может манипулировать система программно-аппаратного интерфейса. Группы файлов обычно организуются в «папки». В Microsoft Windows, Macintosh OS и других системах программно-аппаратного интерфейса папка представляет собой коллекцию файлов, которые можно извлекать, перемещать и иначе манипулировать как отдельными единицами информации. Эти папки, в свою очередь, организуются в древовидную иерархическую структуру, именуемую «директорией» (более подробно рассмотренную ниже). В некоторых других системах программно-аппаратного интерфейса, например DOS, z/OS и большинстве операционных систем на базе Unix, термины «директория» и/или «папка» взаимозаменяемы, и в ранних компьютерных системах Apple (например, Apple IIe) вместо термина «директория» используется термин «каталог»; однако здесь все эти термины взаимозаменяемы и рассматриваются как синонимы и призваны дополнительно включать в себя все остальные эквивалентные термины и ссылки на иерархические структуры хранения информации и их компоненты папок и файлов.In most modern computer systems, “files” are units of stored information that can include a hardware-software interface system, as well as application programs, data sets, etc. In all modern hardware-software interface systems (Windows, Unix, Linux, Mac OS, virtual machine systems, etc.) files are the main discrete (stored and retrieved) units of information (for example, data, programs, etc.) that can be manipulated by a hardware-software interface system. File groups are usually organized in “folders”. On Microsoft Windows, Macintosh OS, and other hardware-software interface systems, a folder is a collection of files that can be retrieved, moved, and otherwise manipulated as separate pieces of information. These folders, in turn, are organized into a tree-like hierarchical structure called the “directory” (discussed in more detail below). On some other hardware-software interface systems, such as DOS, z / OS and most Unix-based operating systems, the terms “directory” and / or “folder” are used interchangeably, and in earlier Apple computer systems (such as Apple IIe) instead of “ directory "uses the term" directory "; however, here all these terms are used interchangeably and are regarded as synonyms and are intended to additionally include all other equivalent terms and links to hierarchical information storage structures and their components of folders and files.

Традиционно директория (именуемая также директорией файлов) представляет собой иерархическую структуру, в которой файлы сгруппированы в папки, и папки, в свою очередь, организованы согласно относительным узловым положениям, которые образуют дерево директории. Например, согласно фиг.2А, базовая папка файловой системы на основе DOS (или «корневая директория») 212 может содержать совокупность папок 214, каждая из которых может дополнительно содержать дополнительные папки (в качестве «подпапок» конкретной папки) 216, и каждая из них также может содержать дополнительные папки 218, и так до бесконечности. Каждая из этих папок может иметь один или более файлов 220, хотя, на уровне системы программно-аппаратного интерфейса, отдельные файлы в папке не имеют ничего общего кроме их положения в древовидной иерархии. Неудивительно, что этот подход к организации файлов в иерархии папок косвенно отражает физическую организацию типичных сред хранения, используемых для хранения этих файлов (например, жестких дисков, флоппи-дисков, CD-ROM и т.д.).Traditionally, a directory (also called a file directory) is a hierarchical structure in which files are grouped into folders, and folders, in turn, are organized according to the relative nodal positions that make up the directory tree. For example, according to FIG. 2A, the base folder of a DOS-based file system (or “root directory”) 212 may comprise a plurality of folders 214, each of which may further comprise additional folders (as “subfolders” of a particular folder) 216, and each of they may also contain additional folders 218, and so on ad infinitum. Each of these folders can have one or more files 220, although, at the system-level hardware-software interface, the individual files in the folder have nothing in common except their position in the tree hierarchy. Not surprisingly, this approach to organizing files in a folder hierarchy indirectly reflects the physical organization of the typical storage environments used to store these files (for example, hard drives, floppy disks, CD-ROMs, etc.).

Помимо вышеизложенного, каждая папка является контейнером для своих подпапок и своих файлов, т.е. каждая папка имеет свои подпапки и файлы. Например, когда система программно-аппаратного интерфейса удаляет папку, подпапки и файлы этой папки также удаляются (которые, в случае каждой подпапки, дополнительно включает в себя свои собственные подпапки и файлы рекурсивно). Аналогично, каждый файл обычно принадлежит только одной папке, и, хотя файл можно копировать, и копия может находиться в другой папке, копия файла сама по себе является отличной и отдельной единицей, которая не имеет прямой связи с оригиналом (например, изменения исходного файла не отражаются в файле-копии на уровне системы программно-аппаратного интерфейса). В этой связи файлы и папки имеют характерную «физическую» природу, поскольку папки рассматриваются как физические контейнеры, и файлы рассматриваются как дискретные и отдельные физические элементы в этих контейнерах.In addition to the above, each folder is a container for its subfolders and its files, i.e. Each folder has its own subfolders and files. For example, when the firmware system deletes a folder, the subfolders and files of that folder are also deleted (which, in the case of each subfolder, additionally includes its own subfolders and files recursively). Similarly, each file usually belongs to only one folder, and although the file can be copied and the copy can be in another folder, the copy of the file itself is a distinct and separate unit that does not have a direct connection with the original (for example, changing the original file does not are reflected in the copy file at the system-level hardware-software interface). In this regard, files and folders have a characteristic “physical” nature, since folders are considered as physical containers, and files are considered as discrete and separate physical elements in these containers.

II. НОВАЯ ПЛАТФОРМА ХРАНЕНИЯ ДЛЯ ОРГАНИЗАЦИИ, ПОИСКА И СОВМЕСТНОГО ИСПОЛЬЗОВАНИЯ ДАННЫХII. NEW STORAGE PLATFORM FOR ORGANIZING, SEARCHING AND JOINT USE OF DATA

Настоящее изобретение относится к платформе хранения для организации, поиска и совместного использования данных. Платформа хранения настоящего изобретения расширяет платформу данных за пределы всех видов рассмотренных выше существующих файловых систем и систем баз данных и предназначена быть хранилищем для всех типов данных, включая новую форму данных, так называемых Статей.The present invention relates to a storage platform for organizing, searching and sharing data. The storage platform of the present invention extends the data platform beyond all types of existing file systems and database systems discussed above and is intended to be a repository for all types of data, including a new form of data, the so-called Articles.

А. ГлоссарийA. Glossary

Следующие термины, используемые здесь и в формуле изобретения, имеют следующие значения:The following terms used here and in the claims have the following meanings:

«Статья» - это единица сохраняемой информации, доступная системе программно-аппаратного интерфейса, которая, в отличие от простого файла, является объектом, имеющим основной набор свойств, которые в целом поддерживаются по всем объектам, которые оболочка системы программно-аппаратного интерфейса представляет конечному пользователю. Статьи также имеют свойства и отношения, которые в целом поддерживаются по всем типам статей, включая признаки, которые позволяют вводить новые свойства и отношения (и рассмотренные более подробно ниже).An “article” is a unit of stored information available to a system of a hardware-software interface, which, unlike a simple file, is an object having a basic set of properties that are generally supported for all objects that the shell of a system of a hardware-software interface represents to the end user . Articles also have properties and relationships that are generally supported across all types of articles, including features that allow you to introduce new properties and relationships (and discussed in more detail below).

"Операционная система" (ОС) - это особая программа, которая выступает в качестве посредника между прикладными программами и компьютерным оборудованием. Операционная система содержит, в большинстве случаев, оболочку и ядро.An "operating system" (OS) is a special program that acts as an intermediary between application programs and computer equipment. The operating system contains, in most cases, a shell and a kernel.

"Система программно-аппаратного интерфейса" - это программное обеспечение или объединение оборудования и программного обеспечения, которое служит интерфейсом между нижележащими аппаратными компонентами компьютерной системы и приложениями, которые выполняются на компьютерной системе. Система программно-аппаратного интерфейса обычно содержит (и, в некоторых вариантах осуществления, может содержать исключительно) операционную систему. Система программно-аппаратного интерфейса также может содержать менеджер виртуальной машины (VMM), общую среду выполнения языка (CLR) или ее функциональный эквивалент, виртуальную машину Java (JVM), или ее функциональный эквивалент, или другие программные компоненты вместо или помимо операционной системы в компьютерной системе. Целью системы программно-аппаратного интерфейса является обеспечение среды, в которой пользователь может выполнять прикладные программы. Цель любой системы программно-аппаратного интерфейса состоит в том, чтобы сделать компьютерную систему удобной для использования, а также эффективно использовать компьютерное оборудование.A “hardware-software interface system” is software or a combination of hardware and software that serves as an interface between underlying hardware components of a computer system and applications that run on a computer system. A hardware-software interface system typically comprises (and, in some embodiments, may exclusively comprise) an operating system. A hardware-software interface system may also include a virtual machine manager (VMM), a common language runtime (CLR) or its functional equivalent, a Java virtual machine (JVM), or its functional equivalent, or other software components instead of or in addition to the operating system in a computer system. The purpose of a hardware-software interface system is to provide an environment in which a user can execute application programs. The goal of any software-hardware interface system is to make the computer system user-friendly and to use computer equipment efficiently.

В. Обзор платформы храненияB. Storage platform overview

Согласно фиг.3, платформа хранения 300 согласно настоящему изобретению содержит хранилище данных 302, реализованное на машине базы данных 314. Согласно одному варианту осуществления машина базы данных содержит машину реляционной базы данных с реляционными расширениями объекта. Согласно одному варианту осуществления машина реляционной базы данных 314 содержит машину реляционной базы данных Microsoft SQL Server.3, a storage platform 300 according to the present invention comprises a data warehouse 302 implemented on a database engine 314. According to one embodiment, the database machine comprises a relational database machine with relational object extensions. In one embodiment, the relational database engine 314 comprises a Microsoft SQL Server relational database machine.

Хранилище данных 302 реализует модель данных 304, которая поддерживает организацию, поиск, совместное использование, синхронизацию и защиту данных. Конкретные типы данных описаны в схемах, например схемах 340, и платформа хранения 300 обеспечивает инструменты 346 для развертывания этих схем, а также для расширения этих схем, что более полно описано ниже.Data warehouse 302 implements a data model 304 that supports the organization, search, sharing, synchronization, and data protection. Specific data types are described in diagrams, for example diagrams 340, and the storage platform 300 provides tools 346 for deploying these schemes as well as for expanding these schemes, which are more fully described below.

Механизм 306 отслеживания изменений, реализованный в хранилище данных 302, обеспечивает возможность отслеживания изменений в хранилище данных. Хранилище данных 302 также обеспечивает защитные возможности 308 и возможность 310 выдвижения/задвигания, более подробно рассмотренные ниже. Хранилище данных 302 также обеспечивает набор программных интерфейсов приложения 312, которые открывают возможности хранилища данных 302 другим компонентам платформы хранения и прикладным программам (например, прикладным программам 350a, 350b и 350c), которые используют платформу хранения.The change tracking engine 306 implemented in the data warehouse 302 provides the ability to track changes in the data warehouse. The data warehouse 302 also provides the protective capabilities 308 and the extension / retraction capability 310, discussed in more detail below. Data warehouse 302 also provides a set of application programming interfaces 312 that open data warehouse capabilities 302 to other storage platform components and applications (e.g., application programs 350a, 350b, and 350c) that use the storage platform.

Платформа хранения согласно настоящему изобретению дополнительно содержит программные интерфейсы приложений (API) 322, которые позволяют прикладным программам, например прикладным программам 350a, 350b и 350c, осуществлять доступ ко всем вышеупомянутым возможностям платформы хранения и осуществлять доступ к данным, описанным в схемах. API 322 платформы хранения могут использоваться прикладными программами совместно с другими API, например, API 324 DB OLE и API 326 Win32 Microsoft Windows.The storage platform according to the present invention further comprises application programming interfaces (APIs) 322 that allow application programs, such as application programs 350a, 350b, and 350c, to access all of the aforementioned storage platform capabilities and access the data described in the diagrams. Storage platform API 322 can be used by applications in conjunction with other APIs, such as API 324 DB OLE and API 326 Win32 Microsoft Windows.

Платформа хранения 300 согласно настоящему изобретению может предоставлять разнообразные услуги 328 прикладным программам, включая услугу синхронизации 330, которая облегчает совместное использование данных между пользователями или системами. Например, услуга синхронизации 330 может обеспечивать возможность взаимодействия с другими хранилищами данных 340, имеющими тот же формат, что и хранилище данных 302, а также доступа к хранилищам данных 342, имеющим другие форматы. Платформа хранения 300 также обеспечивает возможности файловой системы, которые допускают возможность взаимодействия хранилища данных 302 с существующими файловыми системами, например, файловой системой 318 NTFS Windows.The storage platform 300 according to the present invention can provide a variety of services 328 to application programs, including a synchronization service 330, which facilitates the sharing of data between users or systems. For example, synchronization service 330 may provide the ability to interact with other data stores 340 having the same format as data store 302, as well as access to data stores 342 having other formats. Storage platform 300 also provides file system capabilities that allow data warehouse 302 to interact with existing file systems, such as Windows NTFS file system 318.

В, по меньшей мере, некоторых вариантах осуществления платформа хранения 320 может также обеспечивать прикладные программы с дополнительными возможностями, позволяющими оперировать данными и обеспечивающими взаимодействие с другими системами. Эти возможности могут быть воплощены в виде дополнительных услуг 328, например, услуги 334 Info Agent и услуги 332 извещения, а также в виде других утилит 336.In at least some embodiments, the storage platform 320 may also provide applications with additional capabilities that allow data to be operated on and interoperable with other systems. These features can be implemented as additional services 328, for example, services 334 Info Agent and services 332 notification, as well as other utilities 336.

В, по меньшей мере, некоторых вариантах осуществления платформа хранения воплощена в системе программно-аппаратного интерфейса компьютерной системы или составляет ее неотъемлемую часть. Например, и без ограничения, платформа хранения согласно настоящему изобретению может быть воплощена в операционной системе, менеджере виртуальной машины (VMM), общей среды выполнения языка (CLR), или ее функционального эквивалента, или виртуальной машины Java (JVM), или ее функционального эквивалента, или составлять их неотъемлемую часть.In at least some embodiments, the storage platform is embodied in or forms an integral part of the hardware-software interface of a computer system. For example, and without limitation, the storage platform according to the present invention can be embodied in the operating system, virtual machine manager (VMM), common language runtime (CLR), or its functional equivalent, or Java virtual machine (JVM), or its functional equivalent , or be an integral part of them.

Благодаря своей общей основе хранения и схематизированным данным платформа хранения согласно настоящему изобретению позволяет более эффективно разрабатывать приложение для потребителей, специалистов в области информационных технологий и предприятий. Она обеспечивает богатую и расширяемую область программирования, которая не только делает доступными возможности, свойственные этой модели данных, но также охватывает и расширяет существующие файловую систему и методы доступа к базе данных.Due to its common storage foundation and schematized data, the storage platform according to the present invention allows more efficiently developing an application for consumers, IT professionals and enterprises. It provides a rich and extensible programming area that not only makes available the features inherent in this data model, but also extends and extends the existing file system and database access methods.

В нижеследующем описании и согласно различным фигурам платформа хранения 300 настоящего изобретения может именоваться "WinFS." Однако это название платформы хранения используется только для удобства описания и не предполагает никакого ограничения.In the following description and according to various figures, the storage platform 300 of the present invention may be referred to as "WinFS." However, this storage platform name is used for convenience of description only and does not imply any limitation.

С. МОДЕЛЬ ДАННЫХC. DATA MODEL

Хранилище данных 302 платформы хранения 300 настоящего изобретения реализует модель данных, которая поддерживает организацию, поиск, совместное использование, синхронизацию и защиту данных, находящихся в хранилище. В модели данных согласно настоящему изобретению, «статья» является основной единицей хранения информации. Модель данных обеспечивает механизм декларирования Статей и Расширений статьи и для задания отношений между Статьями и для организации Статей в Папках статей и в Категориях, что более подробно описано ниже.The data warehouse 302 of the storage platform 300 of the present invention implements a data model that supports the organization, retrieval, sharing, synchronization and protection of data in the warehouse. In the data model of the present invention, an “article” is the basic unit of information storage. The data model provides a mechanism for declaring Articles and Extensions of an article both for setting relations between Articles and for organizing Articles in Article Folders and Categories, which is described in more detail below.

Модель данных опирается на два примитивных механизма, Типы и Отношения. Типы - это структуры, которые обеспечивают формат, определяющий форму экземпляра Типа. Формат выражается в виде упорядоченного множества Свойств. Свойство - это имя для значения или множества значений данного Типа. Например, тип USPostalAddress (почтовый адрес США) может иметь свойства Street (улица), City (город), Zip (индекс), State (штат), причем значения Street, City и State имеют тип String (строка), а значение Zip имеет тип Int32. Street может быть многозначным (т.е. иметь множество значений), благодаря чему свойство Street может иметь больше одного значения. Система задает определенные примитивные типы, которые можно использовать совместно с другими типами, которые включают в себя String, Binary, Boolean, Int16, Int32, Int64, Single, Double, Byte, DateTime, Decimal and GUID. Свойства Типа можно задавать с использованием любого из примитивных типов или (с некоторыми ограничениями, указанными ниже) любого из построенных типов. Например, можно задать Тип Location (положение), который имеет Свойства Coordinate (координаты) и Address (адрес), где Свойство Address имеет вышеописанный тип USPostalAddress. Свойства также могут быть обязательными или необязательными.The data model relies on two primitive mechanisms, Types and Relations. Types are structures that provide a format that defines the shape of an instance of a Type. The format is expressed as an ordered set of Properties. A property is a name for a value or set of values of a given Type. For example, the type USPostalAddress (US mailing address) can have the properties Street (street), City (city), Zip (zip code), State (state), and the values Street, City and State are of type String (string), and the value Zip has type Int32. Street can be multi-valued (i.e. have multiple values), so the Street property can have more than one value. The system defines certain primitive types that can be used in conjunction with other types, which include String, Binary, Boolean, Int16, Int32, Int64, Single, Double, Byte, DateTime, Decimal and GUID. Type properties can be set using any of the primitive types or (with some restrictions listed below) any of the constructed types. For example, you can specify the Location Type, which has the Coordinate Properties and Address, where the Address Property has the USPostalAddress type described above. Properties may also be required or optional.

Можно задавать отношения, представляющие отображение между множествами экземпляров двух типов. Например, можно задать Отношение между Типом Person (личность) и Типом Location (место), именуемое LivesAt (живет в), которое указывает, кто где живет. Отношение имеет имя, две концевые точки, а именно: исходная концевая точка и целевая концевая точка. Отношения могут также иметь упорядоченное множество свойств. Исходная и целевая концевые точки имеют Имя и Тип. Например, Отношение LivesAt имеет Источник, именуемый Жилец (Occupant) типа Person и Цель, именуемый Местожительством (Dwelling) типа Location и, кроме того, имеет свойства StartDate (начальная дата) и EndDate (конечная дата), указывающие период времени, в течение которого жилец проживает по данному месту жительства. Заметим, что человек может проживать по нескольким местам жительства в течение времени, и местожительство может иметь нескольких жильцов, поэтому, наиболее вероятно, место для помещения информации StartDate и EndDate находится на самом отношении.You can define relationships that represent the mapping between sets of instances of two types. For example, you can specify the Relationship between the Person Type and the Location Type, called LivesAt (lives in), which indicates who lives where. The relationship has a name, two endpoints, namely, the source endpoint and the target endpoint. Relations can also have an ordered set of properties. Source and destination endpoints have Name and Type. For example, a LivesAt relationship has a Source named Occupant of type Person and a Target called Dwelling of type Location and also has properties StartDate (start date) and EndDate (end date) that indicate the period of time during which the tenant lives in this place of residence. Note that a person can live in several places of residence over time, and a place of residence can have several residents, so, most likely, the place to put information StartDate and EndDate is in the relationship.

Отношения задают отношение между экземплярами, которое ограничивается типами, заданными как типы концевых точек. Например, отношение LivesAt не может быть отношением, в котором Жильцом является Автомобиль, поскольку Автомобиль не является Личностью.Relationships define a relationship between instances that is limited to types defined as endpoint types. For example, a LivesAt relationship cannot be a relationship in which the Tenant is a Car, since the Car is not a Person.

Модель данных позволяет задавать отношение подтип-супертип между типами. Отношение подтип-супертип, также известное как отношение BaseType (базовый тип), задается таким образом, что, если Тип А является базовым типом для Типа В, справедливо утверждение, что каждый экземпляр В также является экземпляром А. Это можно выразить и так, что каждый экземпляр, который соответствует В, также должен соответствовать А. Если, например, A имеет свойство Name (имя) типа String, а В имеет свойство Age (возраст) типа Int16, то экземпляр В должен иметь как Name, так и Age. Иерархию типов можно предусмотреть как дерево, в качестве корня которого выступает один супертип. Ветви от корня обеспечивают подтипы первого уровня, ветви на этом уровне обеспечивают подтипы второго уровня и т.д. до краевых подтипов, которые сами не имеют подтипов. Дерево не обязано быть однородным по глубине, но не может содержать циклов. Данный Тип может иметь нуль или много подтипов и нуль или один супертип. Данный экземпляр может соответствовать, самое большее, одному типу совместно с супертипами данного типа. Другими словами, для данного экземпляра на любом уровне в дереве экземпляр может соответствовать, самое большее, одному подтипу на этом уровне.The data model allows you to specify a subtype-supertype relationship between types. The subtype-supertype relation, also known as the BaseType relation (base type), is defined in such a way that if Type A is the base type for Type B, it is true that each instance of B is also an instance of A. This can also be expressed so that each instance that matches B must also match A. If, for example, A has the Name property of type String and B has the Age property of type Int16, then instance B must have both Name and Age. A hierarchy of types can be envisaged as a tree, the root of which is a single supertype. Branches from the root provide subtypes of the first level, branches at this level provide subtypes of the second level, etc. to edge subtypes that themselves do not have subtypes. A tree does not have to be uniform in depth, but cannot contain cycles. This Type can have zero or many subtypes and zero or one supertype. This instance can correspond, at most, to one type together with supertypes of this type. In other words, for a given instance at any level in the tree, an instance can correspond to at most one subtype at that level.

Тип называется абстрактным, если экземпляры типа также должны быть экземпляром подтипа типа.A type is called abstract if the type instances must also be an instance of the type subtype.

1. Статьи1. Articles

Статья это единица сохраняемой информации, доступная системе программно-аппаратного интерфейса, которая, в отличие от простого файла, является объектом, имеющим основной набор свойств, которые в целом поддерживаются по всем объектам, которые платформа хранения представляет конечному пользователю или прикладной программе. Статьи также имеют свойства и отношения, которые в целом поддерживаются по всем типам статей, включая признаки, которые позволяют вводить новые свойства и отношения, что рассмотрено ниже.An article is a unit of stored information available to a system of a hardware-software interface, which, unlike a simple file, is an object that has a basic set of properties that are generally supported for all objects that the storage platform presents to the end user or application program. Articles also have properties and relationships that are generally supported across all types of articles, including features that allow you to introduce new properties and relationships, as discussed below.

Статьи являются объектами общих операций, таких как копирование, удаление, перемещение, открытие, печать, резервное сохранение, дублирование и т.д. Статьи являются единицами, которые можно сохранять и извлекать, и все формы сохраняемой информации, которой манипулирует платформа хранения, существуют в виде Статей, свойств Статей или Отношений между Статьями, каждое из которых более подробно рассмотрено ниже.Articles are objects of common operations, such as copying, deleting, moving, opening, printing, backing up, duplicating, etc. Articles are units that can be stored and retrieved, and all forms of stored information that the storage platform manipulates exist in the form of Articles, properties of Articles or Relations between Articles, each of which is discussed in more detail below.

Статьи призваны представлять относящиеся к реальному миру и легко понимаемые единицы данных, как то: Контакты, Личности, Услуги, Места, Документы (всевозможных сортов) и т.д. На фиг.5А показана блок-схема структуры Статьи. Неспецифицированное имя Статьи это "Location". Специфицированное имя Статьи это "Core.Location", которое указывает, что структура этой Статьи задана как конкретный тип Статьи в Схеме ядра (схема ядра более подробно рассмотрена ниже.)Articles are intended to represent real-world and easily understood data units, such as: Contacts, Persons, Services, Places, Documents (of all kinds), etc. On figa shows a block diagram of the structure of the Article. The unspecified name of the Article is "Location". The specified name of the Article is “Core.Location”, which indicates that the structure of this Article is defined as a specific type of Article in the Kernel Scheme (the kernel schema is discussed in more detail below.)

Статья положения имеет свойство или свойства, включающие в себя EAddress, MetropolitanRegion, Neighborhood и PostalAddress. Конкретный тип свойства для каждого из них указан непосредственно после имени свойства и отделен от имени свойства двоеточием (":"). Справа от имени типа количество значений, разрешенных для этого типа свойства, указано в квадратных скобках ("[ ]"), причем звездочка ("*") справа от двоеточия (":") указывает неопределенное и/или неограниченное количество («много»). «1» справа от двоеточия указывает, что может быть, самое большее, одно значение. Нуль («0») слева от двоеточия указывает, что свойство является необязательным (может вовсе не иметь значения); «1» слева от двоеточия указывает, что должно быть, по меньшей мере, одно значение (свойство обязательное). Neighborhood и MetropolitanRegion имеют тип "nvarchar" (или эквивалентные), который является предпочтительным типом данных или «простым типом» (что указано здесь отсутствием заглавной буквы). Однако EAddresses и PostalAddresses являются свойствами заданных типов или "сложных типов" (что обозначено здесь заглавной буквой) типов EAddress и PostalAddress соответственно. Сложный тип - это тип, который выведен из одного или более простых типов данных и/или из других сложных типов. Сложные типы для свойств Статьи также образуют "вложенные элементы", поскольку детали сложного типа вложены в прямую статью для задания ее свойств, и информация, относящаяся к этим сложным типам, поддерживается посредством статьи, которая имеет эти свойства (в границах Статьи, которые описаны ниже). Эти понятия определения типов общеизвестны и очевидны специалистам в данной области.A provision article has a property or properties, including EAddress, Metropolitan Region, Neighborhood and PostalAddress. A specific property type for each of them is indicated immediately after the property name and is separated by a colon (":") from the property name. To the right of the type name, the number of values allowed for this type of property is indicated in square brackets ("[]"), and the asterisk ("*") to the right of the colon (":") indicates an indefinite and / or unlimited number ("many" ) A “1” to the right of the colon indicates that there can be at most one value. A zero (“0”) to the left of the colon indicates that the property is optional (it may not matter at all); A “1” to the left of the colon indicates that there must be at least one value (required property). Neighborhood and MetropolitanRegion are of type "nvarchar" (or equivalent), which is the preferred data type or "simple type" (as indicated by the absence of a capital letter). However, EAddresses and PostalAddresses are properties of the specified types or “complex types” (indicated by the capital letter) of the EAddress and PostalAddress types, respectively. A complex type is a type that is derived from one or more simple data types and / or from other complex types. Complex types for properties Articles also form “nested elements”, since complex type details are embedded in a direct article to set its properties, and information related to these complex types is supported through an article that has these properties (within the bounds of the Article, which are described below ) These concepts of type definition are well known and obvious to experts in this field.

На фиг.5В показана блок-схема, иллюстрирующая сложные типы свойств PostalAddress и EAddress. Тип свойства PostalAddress определяет, что Статья со свойством типа PostalAddress ожидаемо имеет нуль или одно значение City, нуль или одно значение CountryCode, нуль или одно значение MailStop и любое количество (от нуля до многих) PostalAddressType и т.д. и т.п. Таким образом, задается форма данных для конкретного свойства в Статье. Хотя в данной заявке это используется в необязательном порядке, другой способ представления сложных типов в Статье «положение» состоит в том, чтобы извлекать Статью с индивидуальными свойствами каждого сложного типа из перечисленных здесь. На фиг.5С показана блок-схема, иллюстрирующая Статью «положение», в которой ее сложные типы дополнительно описаны. Однако следует понимать, что это альтернативное представление Статьи «положение» на этой фиг.5С относится к именно той Статье, которая проиллюстрирована на фиг.5А. Платформа хранения согласно настоящему изобретению также позволяет определение подтипов, благодаря чему один тип свойства может быть подтипом другого (где один тип свойства наследует свойства другого, родительского типа свойства).5B is a block diagram illustrating the complex property types PostalAddress and EAddress. The property type PostalAddress determines that an Article with a property of type PostalAddress expectedly has zero or one City value, zero or one CountryCode value, zero or one MailStop value, and any number (from zero to many) PostalAddressType, etc. etc. Thus, the data form for a particular property is specified in the Article. Although this application is optionally used in this application, another way of representing complex types in the “clause” Article is to extract an Article with the individual properties of each complex type from those listed here. On figs shows a block diagram illustrating the Article "position", in which its complex types are further described. However, it should be understood that this alternative representation of the “Position” Article in this FIG. 5C refers to exactly that Article that is illustrated in FIG. 5A. The storage platform according to the present invention also allows the determination of subtypes, whereby one type of property can be a subtype of another (where one type of property inherits the properties of another, parent type of the property).

Аналогичные, но отличные от свойств и их типов свойств, Статьи внутренне представляют свои собственные Типы статьи, которые также могут подлежать определению подтипов. Другими словами, платформа хранения согласно нескольким вариантам осуществления настоящего изобретения позволяет Статье быть подтипом другой Статьи (благодаря чему одна статья наследует свойства другой, родительской статьи). Кроме того, для различных вариантов осуществления настоящего изобретения каждая статья является подтипом "Item" («статья») типа статьи, который является первым и основным типом статьи, найденным в Базовой схеме (базовая схема также будет подробно рассмотрена ниже), на фиг.6А показана Статья, в данном примере Статья «положение», как подтип типа статьи «Статья», найденного в Базовой схеме. На этом чертеже стрелка указывает, что Статья «положение» (как и все остальные Статьи) является подтипом типа статьи «Статья». Тип статьи «Статья», как основная Статья, из которой выводятся все остальные статьи, имеет ряд важных свойств, например, ItemId, и различные метки времени, благодаря чему задает стандартные свойства всех Статей в операционной системе. На фиг.6А, эти свойства типа статьи «Статья» наследуются статьей «положение» и, таким образом, становятся свойствами статьи «положение».Similar but different from properties and their property types, Articles internally present their own Article Types, which may also be subject to subtypes. In other words, the storage platform according to several embodiments of the present invention allows an Article to be a subtype of another Article (whereby one article inherits the properties of another, parent article). In addition, for various embodiments of the present invention, each article is a subtype of "Item" (article) of the type of article, which is the first and main type of article found in the Basic scheme (the basic scheme will also be discussed in detail below), in figa the Article is shown, in this example the Article “provision”, as a subtype of the type of the article “Article” found in the Basic Scheme. In this drawing, the arrow indicates that the Article “provision” (like all other Articles) is a subtype of the type of the article “Article”. The type of the article “Article”, as the main Article, from which all other articles are derived, has a number of important properties, for example, ItemId, and various time stamps, due to which it sets the standard properties of all Articles in the operating system. On figa, these properties of the type of article "Article" are inherited by the article "position" and, thus, become the properties of the article "position".

Хотя способ представления свойств в Статье «положение», унаследованных из типа статьи «Статья», состоит в извлечении статьи «Положение» с индивидуальными свойствами каждого типа свойства из указанной здесь родительской Статьи. На фиг.6В показана блок-схема, иллюстрирующая Статью «положение», в которой, помимо его прямых свойств, описаны унаследованные ей типы. Следует заметить и понимать, что эта Статья является той же Статьей, которая проиллюстрирована на фиг.5А, хотя в данной фигуре статья «положение» показана со всеми своими свойствами, как прямыми, показанными на этой фигуре и фиг.5А, так и унаследованными, показанными на этой фигуре, но не на фиг.5А (тогда как на фиг.5А эти свойства представлены посредством стрелки, указывающей, что Статья «положение» это подтип типа статьи «статья»).Although the way of representing properties in the “Clause” Article inherited from the type of the “Article” article is to extract the “Clause” article with individual properties of each type of property from the parent Article specified here. On figv shows a block diagram illustrating the Article "position", which, in addition to its direct properties, describes its inherited types. It should be noted and understood that this Article is the same Article that is illustrated in FIG. 5A, although in this figure the article “position” is shown with all its properties, both direct, shown in this figure and FIG. 5A, and inherited, shown in this figure, but not in FIG. 5A (whereas in FIG. 5A, these properties are represented by an arrow indicating that the Article “position” is a subtype of the type of the article “article”).

Статьи являются автономными объектами; таким образом, если Вы удаляете Статью, все прямые и унаследованные свойства также удаляются. Аналогично, при извлечении Статьи, получают Статью и все ее прямые и унаследованные свойства (включая информацию, относящуюся к ее сложным типам свойств). Определенные варианты осуществления настоящего изобретения позволяют запрашивать подмножество свойств при извлечении конкретной статьи; однако, по умолчанию, согласно многим таким вариантам осуществления при извлечении обеспечивают Статью со всеми ее прямыми и унаследованными свойствами. Кроме того, свойства Статей также можно расширить путем добавления новых свойств к существующим свойствам типа этой Статьи. Эти «расширения» после этого являются подлинными свойствами Статьи, и подтипы этого типа статьи могут включать в себя свойства расширения.Articles are autonomous objects; thus, if you delete an Article, all direct and inherited properties are also deleted. Similarly, when retrieving Articles, they receive the Article and all its direct and inherited properties (including information related to its complex types of properties). Certain embodiments of the present invention make it possible to request a subset of properties when retrieving a particular article; however, by default, in many such embodiments, upon retrieval, an Article is provided with all its direct and inherited properties. In addition, the properties of Articles can also be expanded by adding new properties to existing properties such as this Article. These “extensions” are then the true properties of the Article, and subtypes of this type of article may include the properties of the extension.

«Граница» Статьи представлена ее свойствами (включая сложные типы свойств, расширения и т.д.). Граница Статьи также представляет предел операции, осуществляемой на Статье, например, копирования, удаления, перемещения, создания и т.д. Например, в некоторых вариантах осуществления настоящего изобретения, при копировании статьи, все, что находится в границах статьи, также копируется. Для каждой статьи, граница охватывает следующее:The “border” of an Article is represented by its properties (including complex types of properties, extensions, etc.). The boundary of the Article also represents the limit of the operation carried out on the Article, for example, copying, deleting, moving, creating, etc. For example, in some embodiments of the present invention, when copying an article, everything within the article is also copied. For each article, the border covers the following:

- Тип статьи для Статьи и, если Статья является подтипом другой Статьи (что имеет место в нескольких вариантах осуществления настоящего изобретения, где все Статьи выводятся из одной Статьи и Типа статьи в Базовой схеме), любую применимую информацию подтипов (т.е. информацию, относящуюся к родительскому типу статьи). Если копируемая исходная Статья является подтипом другой Статьи, то копия также может быть подтипом той же Статьи.- The type of Article for the Article and, if the Article is a subtype of another Article (which is the case in several embodiments of the present invention, where all Articles are derived from the same Article and Article Type in the Basic Scheme), any applicable subtype information (i.e. information, related to the parent type of the article). If the source Article to be copied is a subtype of another Article, then the copy may also be a subtype of the same Article.

- Свойства и расширения сложного типа статьи, если таковые имеются. Если исходная Статья имеет свойства сложных типов (природных или расширенных), то копия также может иметь те же сложные типы.- Properties and extensions of a complex article type, if any. If the original Article has the properties of complex types (natural or advanced), then the copy can also have the same complex types.

- Записи статьи на «отношениях принадлежности», т.е. собственный список Статьи, где указано, какие другие Статьи ("Целевые статьи") принадлежат данной Статье («Статье-владельцу»). Это, в частности, относится к Папке статей, подробнее рассмотренной ниже, и к правилу, установленному ниже, согласно которому все Статьи должны принадлежать, по меньшей мере, одной Папке статей. Кроме того, в связи с внедренными статьями, более подробно описанными ниже, внедренная статья считается частью статьи, в которую она внедрена, для таких операций, как копирование, удаление и т.д.- Entries on an “affiliation relationship”, i.e. own list of Articles, which indicates which other Articles (“Target Articles”) belong to this Article (“Article Owner”). This applies in particular to the Article Folder discussed in more detail below, and to the rule established below, according to which all Articles must belong to at least one Article Folder. In addition, in connection with the embedded articles, described in more detail below, the embedded article is considered part of the article in which it is embedded for operations such as copying, deleting, etc.

2. Идентификация статьи2. Article identification

Статьи уникально идентифицируются в глобальном пространстве статей посредством ItemID. Тип Base.Item задает поле ItemID типа GUID, в котором хранится идентификация Статьи. Статья должна иметь в точности одну идентификацию в хранилище данных 302.Articles are uniquely identified in the global article space through ItemID. The Base.Item type specifies the ItemID field of the GUID type in which the identification of the Article is stored. An article must have exactly one identification in data warehouse 302.

а) Ссылки на статьюa) Links to the article

Ссылка на статью это структура данных, которая содержит информацию для нахождения и идентификации Статьи. В модели данных абстрактный тип задан под названием ItemReference, из которой выводятся все типы ссылки на статью. Тип ItemReference задает виртуальный метод под названием Resolve. Метод Resolve разрешает ItemReference и возвращает Статью. Этот метод подменяется конкретными подтипами ItemReference, которые реализуют функцию, которая извлекает Статью по ссылке. Метод Resolve вызывается как часть API платформы хранения 322.A link to an article is a data structure that contains information for finding and identifying an article. In the data model, an abstract type is specified under the name ItemReference, from which all types of article links are derived. The ItemReference type defines a virtual method called Resolve. The Resolve method resolves the ItemReference and returns the Article. This method is replaced by specific subtypes of ItemReference, which implement a function that retrieves an Article by reference. The Resolve method is called as part of the storage platform API 322.

(1) ItemIDReference(1) ItemIDReference

ItemIDReference - это подтип ItemReference. Он задает поля Locator (указатель) и ItemID. Поле Locator дает имя (т.е. идентифицирует) домен статьи. Оно обрабатывается методом разрешения указателей, который может разрешать значение поля Locator по отношению к домену статьи. Поле ItemID имеет тип ItemID.ItemIDReference is a subtype of ItemReference. It sets the Locator (pointer) and ItemID fields. The Locator field gives the name (i.e. identifies) the domain of the article. It is processed by the method of resolving pointers, which can resolve the value of the Locator field in relation to the domain of the article. The ItemID field is of type ItemID.

(2) ItemPathReference(2) ItemPathReference

ItemPathReference - это частный случай ItemReference, который задает поля Locator и Path (путь). Поле Locator идентифицирует домен статьи. Оно обрабатывается методом разрешения указателей, который может разрешать значение поля Locator по отношению к домену статьи. Поле Path содержит (относительный) путь в пространстве имен платформы хранения, имеющий корень в домене статьи, обеспеченном полем Locator.ItemPathReference is a special case of ItemReference, which sets the Locator and Path fields. The Locator field identifies the domain of the article. It is processed by the method of resolving pointers, which can resolve the value of the Locator field in relation to the domain of the article. The Path field contains a (relative) path in the storage platform namespace that has a root in the article domain provided by the Locator field.

Этот тип ссылки нельзя использовать в операции set. Ссылка должна, в общем случае, разрешаться посредством процесса разрешения пути. Метод Resolve API 322 платформы хранения обеспечивает эту функциональную возможность.This type of link cannot be used in the set operation. The link should, in general, be resolved through the path resolution process. The Resolve API 322 method of the storage platform provides this functionality.

b) Иерархия типов ссылкиb) Link type hierarchy

Рассмотренные выше формы ссылки представлены посредством иерархии типов ссылки, проиллюстрированной на фиг.11. Дополнительные типы ссылки, которые наследуют от этих типов, можно задать в схемах. Их можно использовать в декларации отношения как тип целевого поля.The link forms discussed above are represented by the link type hierarchy illustrated in FIG. Additional link types that inherit from these types can be specified in schemas. They can be used in the relationship declaration as a type of target field.

3. Папки статей и Категории3. Article folders and Categories

Согласно рассмотренному более подробно ниже, группы Статей можно организовать в особые Статьи, именуемые Папками статей (которые не следует путать с папками файлов). Однако в отличие от большинства файловых систем, статья может принадлежать более чем одной Папке статей, поэтому, при осуществлении доступа к Статье в одной Папке статей и ее ревизии, к этой ревизованной Статье можно осуществлять доступ непосредственно из другой Папки статей. В сущности, хотя доступ к Статье может осуществляться из разных Папок статей, то, к чему осуществляется доступ, является фактически той же самой Статьей. Однако Папка статей не обязательно владеет всеми входящими в нее статьями, или может просто совладеть статьями совместно с другими папками, так что удаление Папки статей не обязательно приводит к удалению Статьи. Тем не менее, согласно нескольким вариантам осуществления настоящего изобретения, Статья должна принадлежать, по меньшей мере, одной Папке статей, поэтому, при удалении единичной Папки статей для конкретной Статьи, то, для некоторых вариантов осуществления, статья автоматически удаляется или, в альтернативных вариантах осуществления, Статья автоматически становится элементом Папки статей, принятой по умолчанию (например, Папки статей "Trash Can" (корзина), концептуально аналогичной папкам, используемым в различных системах на основе файлов и папок).As discussed in more detail below, groups of Articles can be organized into special Articles called Article Folders (which should not be confused with file folders). However, unlike most file systems, an article can belong to more than one Article Folder, therefore, when accessing an Article in one Article Folder and its revision, this audited Article can be accessed directly from another Article Folder. In essence, although access to an Article can be from different Article Folders, what is accessed is actually the same Article. However, the Article Folder does not necessarily own all the articles included in it, or can simply share the articles with other folders, so deleting the Article Folder does not necessarily delete the Article. However, according to several embodiments of the present invention, the Article must belong to at least one Article Folder, therefore, when deleting a single Article Folder for a specific Article, then, for some embodiments, the article is automatically deleted or, in alternative embodiments, , The article automatically becomes the default Article Folder item (for example, Trash Can Article Folders (Recycle Bin), conceptually similar to the folders used in various file-based systems folders).

Согласно подробнее рассмотренному ниже, Папки также могут принадлежать Категориям, основанным на общей описанной характеристике, например, (а) типу (или типам) статей, b) конкретному прямому или унаследованному свойству (или свойствам) или с) конкретному значению (или значениям), соответствующему свойству статьи. Например, Статья, содержащая конкретные свойства для информации личных контактов, может автоматически принадлежать Категории Contact, и любая статья, имеющая свойства информации контактов, будет автоматически принадлежать этой категории. Аналогично, любая статья, имеющая свойство положения со значением "New York City", может автоматически принадлежать Категории NewYorkCity.As discussed in more detail below, Folders can also belong to Categories based on a common feature described, for example, (a) the type (or types) of articles, b) a specific direct or inherited property (or properties), or c) a specific value (or values), corresponding property of the article. For example, an Article containing specific properties for personal contact information may automatically belong to the Contact Category, and any article having contact information properties will automatically belong to this category. Similarly, any article that has a position property with the value "New York City" can automatically belong to the NewYorkCity Category.

Категории концептуально отличаются от Папок статей тем, что, в то время как Папки статей могут содержать Статьи, которые не связаны друг с другом (т.е. без общей описанной характеристики), каждая Статья в Категории имеет общий(ее) тип, свойство или значение («общность»), который(ое) описано для этой Категории, и это та общность, которая образует базис для ее отношения к другим Статьям в Категории. Кроме того, тогда как принадлежность Статьи к конкретной Папке не обязательно базируется на каком-либо конкретном аспекте этой Статьи, для определенных вариантов осуществления, все статьи, имеющие общность, категорически связанную с Категорией, могут автоматически становиться элементами Категории на уровне системы программно-аппаратного интерфейса. В принципе, Категории также можно рассматривать как виртуальные Папки статей, принадлежность к которым базируется на результатах конкретного запроса (например, в контексте базы данных), и, таким образом, Статьи, которые отвечают условиям этого запроса (заданным общностями Категории), будут содержать принадлежность к Категории.Categories are conceptually different from Article Folders in that, while Article Folders can contain Articles that are not related to each other (i.e., without a common characteristic described), each Article in the Category has a common type, property, or the meaning (“community”) that is described for this Category, and this is the community that forms the basis for its relationship to other Articles in the Category. In addition, while the membership of an Article in a particular Folder is not necessarily based on any particular aspect of this Article, for certain embodiments, all articles having a commonality categorically associated with the Category can automatically become Category elements at the system-hardware interface level . In principle, Categories can also be considered as virtual Article Folders, belonging to which is based on the results of a particular query (for example, in the context of a database), and thus Articles that meet the conditions of this query (specified by the Community of Categories) will contain membership to Category.

На фиг.4 показано структурное соотношение между Статьями, Папками статей и Категориями согласно различным вариантам осуществления настоящего изобретения. Статьи 402, 404, 406, 408, 410, 412, 414, 416, 418, и 420 принадлежат различным Папкам статей 422, 424, 426, 428, и 430. Некоторые Статьи могут принадлежать более чем одной Папке статей, например, Статья 402 принадлежит Папкам статей 422 и 424. Некоторые Статьи, например статья 402, 404, 406, 408, 410, и 412, также принадлежат одной или более Категориям 432, 434, и 436, тогда как другие статьи, например Статьи 414, 416, 418, и 420, могут не принадлежать ни одной Категории (хотя это весьма маловероятно в некоторых вариантах осуществления, где обладание каким-либо свойством автоматически влечет за собой принадлежность к Категории, и, таким образом, чтобы не принадлежать никакой категории в таком варианте осуществления, Статья не должна иметь никаких признаков). В отличие от иерархической структуры папок структуры Категорий и Папок статей больше походят на ориентированные графы. В любом случае Статьи, Папки статей и Категории являются Статьями (хотя и разных Типов статей).Figure 4 shows the structural relationship between Articles, Article Folders and Categories according to various embodiments of the present invention. Articles 402, 404, 406, 408, 410, 412, 414, 416, 418, and 420 belong to different Folders of Articles 422, 424, 426, 428, and 430. Some Articles may belong to more than one Article Folder, for example, Article 402 belongs to the Folders of Articles 422 and 424. Some Articles, such as Articles 402, 404, 406, 408, 410, and 412, also belong to one or more Categories 432, 434, and 436, while other articles, such as Articles 414, 416, 418 , and 420, may not belong to any Category (although this is highly unlikely in some embodiments where the possession of a property automatically entails the belonging to the Category, and so as not to belong to any category in such an embodiment, the Article should not have any signs). In contrast to the hierarchical structure of folders, the structure of Categories and Article Folders is more like directed graphs. In any case, Articles, Article Folders and Categories are Articles (albeit of different Article Types).

В отличие от файлов, папок и директорий, Статьи, Папки статей и Категории согласно настоящему изобретению не имеют характерной «физической» природы, поскольку они не имеют концептуально эквивалентных физических контейнеров, благодаря чему Статьи могут существовать в более чем одном таком месте. Возможность для статей существовать в более чем одной Папке статей, а также возможность объединения в Категории, обеспечивает расширенные и обогащенные возможности манипуляции данными и возможности структуры хранения на уровне программно-аппаратного интерфейса, превышающие возможности, доступные в современной технике.Unlike files, folders and directories, Articles, Article folders and Categories according to the present invention do not have a characteristic “physical” nature, since they do not have conceptually equivalent physical containers, so Articles can exist in more than one such place. The ability for articles to exist in more than one Article Folder, as well as the ability to be combined into Categories, provides advanced and enriched data manipulation capabilities and storage structure capabilities at the hardware-software interface level that exceed the capabilities available in modern technology.

4. Схемы4. Schemes

a) Базовая схемаa) Basic scheme

Для обеспечения универсальной основы для создания и использования Статей, различные варианты осуществления платформы хранения согласно настоящему изобретению содержат Базовую схему, которая устанавливает принципиальную структуру для создания и организации Статей и свойств. Базовая схема задает определенные специальные типы Статей и свойств и признаки этих специальных основных типов, из которых можно дополнительно выводить подтипы. Использование этой Базовой схемы позволяет программисту принципиально отличать Статьи (и их соответствующие типы) от свойств (и их соответствующих типов). Кроме того, Базовая схема задает основное множество свойств, которыми могут обладать все Статьи, поскольку все Статьи (и их соответствующие Типы статей) выводятся из этой основной Статьи в Базовой схеме (и ее соответствующего Типа статьи).To provide a universal basis for the creation and use of Articles, various embodiments of a storage platform according to the present invention comprise a Basic Scheme that establishes a basic structure for creating and organizing Articles and properties. The basic schema defines certain special types of Articles and properties and the characteristics of these special basic types from which subtypes can be additionally derived. Using this Basic Scheme allows a programmer to fundamentally distinguish Articles (and their respective types) from properties (and their respective types). In addition, the Basic Scheme defines the basic set of properties that all Articles may possess, since all Articles (and their respective Article Types) are derived from this main Article in the Basic Scheme (and its corresponding Article Type).

Согласно фиг.7 и в связи с несколькими вариантами осуществления настоящего изобретения базовая схема задает три типа верхнего уровня: Item, Extension и PropertyBase. Показано, что тип Item задан свойствами этого основного типа статьи "Item". Напротив, тип свойства верхнего уровня "PropertyBase" не имеет заранее заданных свойств и является лишь анкером, из которого выводятся все остальные типы свойств и посредством которого все производные типы свойств связаны между собой (будучи сообща выведены из единого типа свойства). Свойства типа Extension задают, какую Статью расширяет расширение, а также идентификацию, позволяющую отличить одно расширение от другого, поскольку Статья может иметь несколько расширений.7, and in connection with several embodiments of the present invention, the base schema defines three top-level types: Item, Extension, and PropertyBase. It is shown that the Item type is defined by the properties of this main type of the "Item" article. On the contrary, the top-level property type “PropertyBase” has no predefined properties and is only an anchor from which all other property types are derived and through which all derived property types are linked (being deduced together from a single property type). Properties of the Extension type specify which Article extends the extension, as well as identification, which distinguishes one extension from another, since an Article can have several extensions.

ItemFolder это подтип типа статьи «статья», который, помимо свойств, унаследованных от Статьи, определяет Отношение для установления связей с ее элементами (если таковые имеются), тогда как IdentityKey и Property являются подтипами PropertyBase. В свою очередь, CategoryRef является подтипом IdentityKey.An ItemFolder is a subtype of the type of the article “article”, which, in addition to the properties inherited from the Article, defines a Relationship for establishing links with its elements (if any), while IdentityKey and Property are subtypes of PropertyBase. CategoryRef, in turn, is a subtype of IdentityKey.

b) Схема ядраb) Kernel layout

Различные варианты осуществления платформы хранения согласно настоящему изобретению содержат Схему ядра, которая обеспечивает принципиальную структуру для структур типов Статей верхнего уровня. На фиг.8А показана блок-схема, иллюстрирующая Статьи в Схеме ядра, и на фиг.8В показана блок-схема, иллюстрирующая типы свойств в Схеме ядра. Различия между файлами с разными расширениями (*.com, *.exe, *.bat, *.sys, и т.д.) и другие подобные критерии в системах на основе файлов и папок аналогичны по функции Схема ядра. В системе программно-аппаратного интерфейса на основе Статей Схема ядра задает множество типов статей ядра, которые прямо (по типу статьи) или косвенно (по подтипу статьи) характеризуют все Статьи в один или более тип статьи Схемы ядра, которые система программно-аппаратного интерфейса на основе статей понимает и может непосредственно обрабатывать заранее определенным и предсказуемым способом. Заранее заданные типы статей отражают наиболее общеупотребительные Статьи в системе программно-аппаратного интерфейса на основе статей и, таким образом, повышается уровень эффективности системы программно-аппаратного интерфейса на основе статей, понимающей эти заранее заданные типы статей, которые содержат Схему ядра.Various embodiments of a storage platform according to the present invention comprise a Core Scheme that provides a principal structure for top-level Article type structures. On figa shows a block diagram illustrating the Articles in the kernel diagram, and figv shows a block diagram illustrating the types of properties in the kernel diagram. The differences between files with different extensions (* .com, * .exe, * .bat, * .sys, etc.) and other similar criteria in systems based on files and folders are similar in function to the kernel scheme. In a system of hardware-software interface based on Articles, the Kernel Scheme defines many types of kernel articles that directly (by type of article) or indirectly (by subtype of an article) characterize all Articles into one or more types of articles The basis of the articles is understood and can be directly processed in a predetermined and predictable way. The predefined article types reflect the most commonly used Articles in the article-based software and hardware interface system, and thus, the level of efficiency of the software-hardware interface system based on articles that understands these predefined article types that contain the kernel schema is increased.

В некоторых вариантах осуществления Схема ядра является нерасширяемой, т.е. никакие дополнительные типы статей нельзя непосредственно вывести в качестве подтипов из типа статьи в Базовой схеме за исключением конкретных заранее заданных производных типов статей, которые являются частью Схемы ядра. Препятствуя образованию расширений к Схеме ядра (т.е. препятствуя добавлению новых Статей к Схеме ядра), платформа хранения разрешает использовать типы статей Схемы ядра, поскольку каждый последующий тип статьи с необходимостью является подтипом типа статьи Схемы ядра. Эта структура допускает разумную степень гибкости при задании дополнительных типов статей, в то же время сохраняя преимущества наличия заранее заданного множества типов статей ядра.In some embodiments, the core design is non-extensible, i.e. no additional article types can be directly derived as subtypes of the article type in the Basic Scheme, except for specific predefined derived article types that are part of the Kernel Scheme. By inhibiting the formation of extensions to the Kernel Scheme (i.e., by preventing the addition of new Articles to the Kernel Scheme), the storage platform allows the use of article types of the Kernel Scheme, since each subsequent article type is necessarily a subtype of the type of the Kernel Scheme article. This structure allows a reasonable degree of flexibility when defining additional types of articles, while at the same time preserving the benefits of having a predefined set of types of core articles.

Для различных вариантов осуществления настоящего изобретения и согласно фиг.8А конкретные типы статей, поддерживаемые Схемой ядра, могут включать в себя одно или несколько из следующего:For various embodiments of the present invention and as shown in FIG. 8A, the specific article types supported by the Core Schema may include one or more of the following:

- Категории: Статьи данного типа статьи (выведенных из него подтипов) представляют пригодные Категории в системе программно-аппаратного интерфейса на основе статей.- Categories: Articles of this type of article (subtypes derived from it) represent suitable Categories in the system of hardware-software interface based on articles.

- Предметы потребления: Статьи, которые являются идентифицируемыми ценными вещами.- Commodities: Articles that are identifiable valuable items.

- Устройства: Статьи, имеющие логическую структуру, которая поддерживает возможности обработки информации.- Devices: Articles that have a logical structure that supports information processing capabilities.

- Документы: Статьи, содержимое которых не интерпретируется системой программно-аппаратного интерфейса на основе статей, но интерпретируется прикладной программой, соответствующей типу документа.- Documents: Articles whose contents are not interpreted by the system of hardware-software interface based on articles, but are interpreted by an application program corresponding to the type of document.

- События: Статьи, в которых записаны определенные события в среде.- Events: Articles in which certain events in the medium are recorded.

- Места: Статьи, представляющие физические положения (например, географические положения).- Locations: Articles representing physical locations (e.g. geographic locations).

- Сообщения: Статьи связи между двумя или более принципалами (определены ниже).- Communications: Articles of communication between two or more principals (defined below).

- Принципалы: Статьи, имеющие, по меньшей мере, одну однозначно доказуемую идентификацию помимо ItemId (например, идентификацию личности, организации, группы, домовладения, органа власти, службы и т.д.).- Principals: Articles that have at least one uniquely provable identification in addition to ItemId (for example, identification of an individual, organization, group, home ownership, authority, service, etc.).

- Утверждения: Статьи, имеющие особую информацию, касающуюся среды, включая, без ограничения, политики, подписки, мандаты и т.д.- Affirmations: Articles with specific information regarding the environment, including, without limitation, policies, subscriptions, mandates, etc.

Аналогично и согласно фиг.8В конкретные типы свойств, поддерживаемые Схемой ядра, могут включать в себя одно или несколько из следующего:Similarly, as shown in FIG. 8B, the specific types of properties supported by the Kernel Scheme may include one or more of the following:

- Сертификаты (выводимые из основного типа PropertyBase в Базовой схеме)- Certificates (derived from the main PropertyBase type in the Base Schema)

- Ключи идентификации принципалов (выводимые из типа IdentityKey в Базовой схеме)- Principal identification keys (derived from the IdentityKey type in the Base Schema)

- Почтовый адрес (выводимый из типа Property в Базовой схеме)- Mailing address (derived from the Property type in the Base Schema)

- Богатый текст (выводимый из типа Property в Базовой схеме)- Rich text (inferred from the Property type in the Base Schema)

- Электронный адрес (Eaddress) (выводимый из типа Property в Базовой схеме)- Email address (Eaddress) (derived from the Property type in the Base Schema)

- IdentitySecurityPackage (выводимый из типа Relationship в Базовой схеме)- IdentitySecurityPackage (inferred from the Relationship type in the Base Schema)

- RoleOccupancy (выводимый из типа Relationship в Базовой схеме)- RoleOccupancy (inferred from the Relationship type in the Base Schema)

Эти Статьи и Свойства описаны ниже согласно их соответствующим свойствам, показанным на фиг.8А и 8В.These Articles and Properties are described below according to their respective properties shown in FIGS. 8A and 8B.

5. Отношения5. Relations

Отношения являются бинарными отношениями, в которых одна Статья считается исходной (источником), а другая - целевой (целью). Исходная статья и целевая статья связаны отношением. Исходная статья, в общем случае, управляет временем жизни отношения. Таким образом, при удалении исходной статьи, удаляется также отношение между Статьями.Relations are binary relations in which one Article is considered the source (source) and the other is the target (target). The source article and the target article are related. The original article, in the general case, controls the relationship's lifetime. Thus, when deleting the original article, the relationship between the Articles is also deleted.

Отношения подразделяются на отношения включения и отношения ссылки. Отношения включения управляют временем жизни целевых статей, а отношения ссылки не обеспечивают никакой семантики управления временем жизни. На фиг.12 показано, каким образом классифицируются отношения.Relationships are divided into inclusion relationships and link relationships. Inclusion relationships control the lifetime of targeted articles, and linking relationships do not provide any semantics for managing lifetimes. 12 shows how relationships are classified.

Типы отношений включения далее подразделяются на отношения поддержки и внедрения. При удалении всех отношений поддержки Статьи статья удаляется. Отношение поддержки управляет временем жизни цели посредством ссылки на механизм отсчета. Отношения внедрения позволяют моделировать составные Статьи, и их можно рассматривать как исключающие отношения поддержки. Статья может быть целью одного или нескольких отношений поддержки; но Статья может быть целью только одного отношения внедрения. Статья, которая является целью отношения внедрения, не может быть целью никакого другого отношения поддержки или внедрения.The types of inclusion relationships are further subdivided into support and implementation relationships. If you delete all Article support relationships, the article is deleted. The support relationship controls the target's lifetime by reference to a reference mechanism. Implementation relationships allow you to model compound Articles, and they can be considered as exclusive support relationships. An article may be the goal of one or more support relationships; but an Article may be the goal of only one implementation relationship. An article that is the goal of an implementation relationship cannot be the goal of any other support or implementation relationship.

Отношения ссылки не управляют временем жизни целевой статьи. Они могут быть висящими, т.е. могут не иметь целевой статьи. Отношения ссылки можно использовать для моделирования ссылок на Статьи в любом месте глобального пространства имен статей (т.е., включая удаленные хранилища данных).Link relationships do not control the lifetime of the target article. They can be hanging, i.e. may not have a target article. Link relationships can be used to model links to Articles anywhere in the global article namespace (i.e., including remote data stores).

Выборка Статьи не предполагает автоматической выборки ее отношений. Приложения должны в явном виде запрашивать отношения Статьи. Кроме того, изменение отношения не приводит к изменению исходной или целевой статьи; аналогично, добавление отношения не влияет на исходную/целевую статью.Sampling an Article does not imply an automatic sampling of its relationship. Applications must explicitly request Article relations. In addition, a change in attitude does not change the source or target article; likewise, adding a relationship does not affect the source / target article.

a) Декларация отношенияa) Declaration of relationship

Явные типы отношений задаются следующими элементами:Explicit relationship types are defined by the following elements:

- Имя отношения задается в атрибуте Name.- The name of the relationship is specified in the Name attribute.

- Тип отношения, один из следующих: Holding, Embedding, Reference. Он задается в атрибуте Type.- Type of relationship, one of the following: Holding, Embedding, Reference. It is set in the Type attribute.

- Исходная и целевая концевые точки. Каждая концевая точка задает имя и тип Статьи, на которую идет ссылка.- Source and target endpoints. Each endpoint defines the name and type of the Article referred to.

- Поле исходной концевой точки, в общем случае, имеет тип ItemID (не декларируется) и должно ссылаться на Статью, находящуюся в том же хранилище данных, что и экземпляр отношения.- The field of the source endpoint, in general, is of the type ItemID (not declared) and should refer to the Article located in the same data warehouse as the instance of the relationship.

- Для отношений поддержки и внедрения, поле целевой концевой точки должно иметь тип ItemIDReference и должно ссылаться на Статью, находящуюся в том же хранилище, что и экземпляр отношения. Для отношения ссылки, целевая концевая точка может быть любой концевой точкой типа ItemReference и может ссылаться на Статьи в других хранилищах данных платформы хранения.- For support and implementation relationships, the target endpoint field must be of type ItemIDReference and must refer to an Article located in the same repository as the relationship instance. For a link relationship, the target endpoint can be any endpoint of type ItemReference and can link to Articles in other data warehouses of the storage platform.

- В необязательном порядке, можно декларировать одно или несколько полей скалярного типа или типа PropertyBase. Эти поля могут содержать данные, связанные с отношением.- Optionally, one or more fields of a scalar type or PropertyBase type can be declared. These fields may contain data related to the relationship.

- Экземпляры отношений хранятся в глобальной таблице отношений.- Relationship instances are stored in the global relationship table.

- Каждый экземпляр отношения уникально идентифицируется комбинацией (ИД исходной статьи, ИД отношения). ИД отношения уникален в данном ИД исходной статьи для всех отношений, источником которых является данная статья, независимо от их типов.- Each instance of a relationship is uniquely identified by a combination (ID of the source article, ID of the relationship). Relationship ID is unique in this ID of the source article for all relationships the source of this article is, regardless of their type.

Исходная статья является владельцем отношения. Хотя Статья, указанная как владелец, управляет временем жизни отношения, само по себе отношение отделено от статей, к которым оно относится. API 322 платформы хранения обеспечивает механизмы представления отношений, связанных со статьей.The original article is the owner of the relationship. Although the Article, indicated as the owner, controls the life time of the relationship, the relationship itself is separate from the articles to which it relates. Storage platform API 322 provides mechanisms for presenting relationship related to an article.

Приведем пример декларации отношения:Here is an example of a declaration of a relationship:

<Relationship Name="Employment" BaseType="Reference"><Relationship Name = "Employment" BaseType = "Reference">

<Source Name="Employee" ItemType="Contact.Person"/><Source Name = "Employee" ItemType = "Contact.Person" />

<Target Name='Employer" ItemType="Contact.Organization"<Target Name = 'Employer "ItemType =" Contact.Organization "

ReferenceType="ItemIDReference"/>ReferenceType = "ItemIDReference" />

<Property Name="StartDate" Type="the storage<Property Name = "StartDate" Type = "the storage

platformTypes.DateTime"/>platformTypes.DateTime "/>

<Property Name="EndDate" Type="the storage<Property Name = "EndDate" Type = "the storage

platformTypes.DateTime"/>platformTypes.DateTime "/>

<Property Name="Office" Type="the storage<Property Name = "Office" Type = "the storage

platformTypes.DateTime"/>platformTypes.DateTime "/>

</Relationship></Relationship>

Это пример отношения ссылки. Отношение нельзя создать, если статьи «лицо», на которую идет ссылка посредством исходной ссылки, не существует. Кроме того, при удалении статьи «лицо», экземпляры отношения между лицом и организацией удаляются. Однако при удалении статьи «организация», отношение не удаляется и зависает.This is an example of a link relationship. A relationship cannot be created if the “person” article referred to by the original link does not exist. In addition, when you delete the article "person", copies of the relationship between the person and the organization are deleted. However, when you delete the article "organization", the relationship is not deleted and freezes.

b) Отношение поддержкиb) Support attitude

Отношения поддержки используются для моделирования счетчика ссылок на основании управления временем жизни целевых статей.Support relationships are used to model the reference count based on the life span of the targeted articles.

Статья может быть исходной концевой точкой для нуля или более отношений со статьями. Статья, которая не внедрена в Статью, может быть целью для одного или более отношений поддержки.An article can be the starting point for zero or more relationships with articles. An article that is not embedded in the Article may be the target for one or more support relationships.

Тип ссылки целевой концевой точки должен быть ItemIDReference и он должен ссылаться на статью, находящуюся в том же хранилище, что и экземпляр отношения.The target endpoint link type must be ItemIDReference and it must refer to an article located in the same store as the relationship instance.

Отношения поддержки применяют управление временем жизни целевой концевой точки. Создание экземпляра отношения поддержки и статьи, которая является его целью, является элементарной операцией. Можно создавать дополнительные экземпляры отношения поддержки, нацеленные на ту же статью. При удалении последнего экземпляра отношения поддержки, имеющего целевой концевой точкой данную статью, целевая статья также удаляется.Support relationships apply target endpoint lifetime management. Creating an instance of a support relationship and an article that is its goal is an elementary operation. You can create additional instances of a support relationship that target the same article. When you delete the last instance of a support relationship that has a target endpoint of this article, the target article is also deleted.

Типы статей, являющихся концевыми точками, указанные в декларации отношения, обычно применяются при создании экземпляра отношения. Типы статей, являющихся концевыми точками, не могут изменяться после задания отношения.The types of endpoint articles specified in the relationship declaration are typically used when creating an instance of the relationship. The types of articles that are endpoints cannot change after defining a relationship.

Отношения поддержки играют ключевую роль при формировании пространства имен статей. Они содержат свойство "Name", которое задает имя целевой статьи относительно исходной статьи. Относительное имя уникально для всех отношений поддержки, имеющих источником данную статью. Упорядоченный список этих относительных имен, начинающийся с корневой статьи и оканчивающийся данной статьей, образует полное имя статьи.Support relationships play a key role in shaping the article namespace. They contain the "Name" property, which sets the name of the target article relative to the original article. The relative name is unique to all support relationships originating in this article. An ordered list of these relative names, starting with the root article and ending with this article, forms the full name of the article.

Отношения поддержки образуют ориентированный ациклический граф (DAG). При создании отношения поддержки система гарантирует, что цикл не создается, и, таким образом, гарантирует, что пространство имен статей образует DAG.Support relationships form a directed acyclic graph (DAG). When creating a support relationship, the system ensures that the loop is not created, and thus ensures that the article namespace forms a DAG.

Хотя отношение поддержки управляет временем жизни целевой статьи, оно не управляет операционной согласованностью статьи, являющейся целевой концевой точкой. Целевая статья операционно независима от статьи, которая владеет ею через отношение поддержки. Операции Copy, Move, Backup и пр. на статье, которая является источником отношения поддержки, не влияют на статью, которая является целью того же отношения, например, резервное копирование статьи «папка» не предполагает автоматического резервного копирования всех статей в этой папке (целей отношения FolderMember).Although the support relation controls the lifetime of the target article, it does not control the operational consistency of the article, which is the target endpoint. The target article is operationally independent of the article that owns it through a support relationship. Copy, Move, Backup, etc. operations on an article that is the source of the support relationship do not affect the article that is the target of the same relationship, for example, backing up the “folder” article does not automatically backup all the articles in this folder (goals relationship FolderMember).

Приведем пример отношения поддержки:Here is an example of a support relationship:

<Relationship Name="FolderMembers" BaseType="Holding"><Relationship Name = "FolderMembers" BaseType = "Holding">

<Source Name="Folder" ItemType="Base.Folder"/><Source Name = "Folder" ItemType = "Base.Folder" />

<Target Name="Item" ItemType="Base.Item"<Target Name = "Item" ItemType = "Base.Item"

ReferenceType="ItemIDReference"/>ReferenceType = "ItemIDReference" />

</Relationship></Relationship>

Отношение FolderMembers задает понятие Папки как общего вида коллекции Статей.The FolderMembers relationship defines the concept of a Folder as a general view of a collection of Articles.

с) Отношения внедренияc) Implementation Relations

Отношения внедрения моделируют концепцию исключительного управления временем жизни целевой статьи. Они задают понятие составных статей.Implementation relationships model the concept of exceptional time management of the target article. They define the concept of composite articles.

Создание экземпляра отношения внедрения и статьи, которая является его целью, является элементарной операцией. Статья может быть источником для нуля или более отношений внедрения. Однако статья может быть целью одного и только одного отношения внедрения. Статья, которая является целью отношения внедрения, не может быть целью отношения поддержки.Creating an instance of the implementation relationship and the article, which is its goal, is an elementary operation. An article can be a source for zero or more implementation relationships. However, an article may be the goal of one and only one implementation relationship. An article that is the goal of an implementation relationship cannot be the goal of a support relationship.

Тип ссылки целевой концевой точки должен быть ItemIDReference и должен ссылаться на статью, находящуюся в том же хранилище данных, что и экземпляр отношения.The target endpoint reference type must be ItemIDReference and must refer to an article located in the same data store as the relationship instance.

Типы статей, являющихся концевыми точками, указанные в декларации отношения, обычно применяются при создании экземпляра отношения. Типы статей, являющихся концевыми точками, не могут изменяться после задания отношения.The types of endpoint articles specified in the relationship declaration are typically used when creating an instance of the relationship. The types of articles that are endpoints cannot change after defining a relationship.

Отношения внедрения управляют операционной согласованностью целевой концевой точки. Например, операция преобразования статьи к последовательному виду может включать в себя преобразование к последовательному виду всех отношений внедрения, исходящих от данной статьи, а также всех их целей; копирование статьи также приводит к копированию всех внедренных в нее статей.Deployment relationships control the operational consistency of the target endpoint. For example, the operation of converting an article to a sequential view may include converting to a sequential view of all of the implementation relationships emanating from the article, as well as all of their goals; copying an article also leads to copying all articles embedded in it.

Приведем пример декларации:Here is an example declaration:

<Relationship Name="ArchiveMembers" BaseType="Embedding"><Relationship Name = "ArchiveMembers" BaseType = "Embedding">

<Source Name="Archive" ItemType="Zip.Archive"/><Source Name = "Archive" ItemType = "Zip.Archive" />

<Target Name="Member" ItemType="Base.Item "<Target Name = "Member" ItemType = "Base.Item"

ReferenceType="ItemIDReference"/>ReferenceType = "ItemIDReference" />

<Property Name="ZipSize" Type="the storage<Property Name = "ZipSize" Type = "the storage

platformTypes.bigint"/>platformTypes.bigint "/>

<Property Name="SizeReduction" Type="the storage<Property Name = "SizeReduction" Type = "the storage

platformTypes.float"/>platformTypes.float "/>

</Relationship></Relationship>

d) Отношения ссылкиd) Link relationships

Отношение ссылки не управляет временем жизни статьи, на которую оно ссылается. Более того, отношения ссылки не гарантируют существование цели, а также не гарантируют тип цели, указанной в декларации отношения. Это значит, что отношения ссылки могут зависать. Кроме того, отношение ссылки может ссылаться на статьи в других хранилищах данных. Отношения ссылки можно рассматривать как понятие, аналогичное ссылкам на веб-страницах.The link relation does not control the lifetime of the article to which it refers. Moreover, link relationships do not guarantee the existence of a goal, nor do they guarantee the type of goal specified in the relationship declaration. This means that the link relationship may freeze. In addition, the link relationship may link to articles in other data stores. Link relationships can be seen as a concept similar to links on web pages.

Приведем пример декларации отношения ссылки:Here is an example of a link relationship declaration:

<Relationship Name="DocumentAuthor" BaseType='Reference"><Relationship Name = "DocumentAuthor" BaseType = 'Reference ">

<Sourc ItemType="Document" ItemType="Base.Document"/><Sourc ItemType = "Document" ItemType = "Base.Document" />

<Target ItemType="Author" ItemType="Base.Author"<Target ItemType = "Author" ItemType = "Base.Author"

ReferenceType="ItemIDReference"/>ReferenceType = "ItemIDReference" />

<Property Type="Role" Type="Core.CategoryRef"/><Property Type = "Role" Type = "Core.CategoryRef" />

<Property Type="DisplayName" Type="the storage<Property Type = "DisplayName" Type = "the storage

platformTypes.nvarchar(256)"/>platformTypes.nvarchar (256) "/>

</Relationship></Relationship>

В целевой концевой точке разрешен любой тип ссылки. Статьи, которые участвуют в отношении ссылки, могут иметь любой тип статьи.Any type of link is allowed at the target endpoint. Articles that are involved in relation to a link can have any type of article.

Отношения ссылки используют для моделирования отношений между статьями, наименее связанных с управлением временем жизни. Поскольку существование цели не требуется, отношение ссылки удобно для моделирования слабосвязанных отношений. Целевые статьи отношения ссылки могут находиться в других хранилищах данных, включая хранилища на других компьютерах.Relationships are used to model relationships between articles that are least related to life time management. Since the existence of a goal is not required, the reference relationship is convenient for modeling loosely coupled relationships. Target link relationship articles may be located in other data stores, including stores on other computers.

е) Правила и ограниченияe) Rules and restrictions

К отношениям применяются следующие дополнительные правила и ограничения:The following additional rules and restrictions apply to relationships:

1. Статья должна быть целью (в точности одного отношения внедрения) или (одного или более отношений поддержки). Исключение составляет корневая статья. Статья может быть целью нуля или более отношений ссылки.1. The article should be the goal of (exactly one implementation relationship) or (one or more support relationships). The exception is the root article. An article may be the goal of a zero or more link relationship.

2. Статья, которая является целью отношения внедрения, не может быть источником отношений поддержки. Она может быть источником отношений ссылки.2. An article that is the goal of an implementation relationship cannot be a source of support relationships. It can be a source of link relationships.

3. Статья не может быть источником отношения поддержки, если она выдвинута из файла. Она может быть источником отношений внедрения и отношений ссылки.3. An article cannot be a source of a support relationship if it is pushed from a file. It can be a source of implementation relationships and link relationships.

4. Статья, которая может быть выдвинута из файла, не может быть целью отношения внедрения.4. An article that can be pushed from a file cannot be the goal of an embedding relationship.

f) Упорядочение отношенийf) Streamlining relationships

Согласно, по меньшей мере, одному варианту осуществления, платформа хранения согласно настоящему изобретению поддерживает упорядочение отношений. Упорядочение достигается посредством свойства под названием "Order" (порядок) в базовом определении отношения. На поле Order не накладывается никаких ограничений, связанных с уникальностью. Порядок отношений с одним и тем же значением свойства «порядок» не гарантируется, однако гарантируется, что они будут стоять после отношений с более низким значением «порядка» и перед отношениями с более высоким значением «порядка».According to at least one embodiment, a storage platform according to the present invention supports ordering of relationships. Ordering is achieved through a property called "Order" in the base definition of the relationship. The Order field is not subject to any restrictions related to uniqueness. The order of relations with the same value of the property “order” is not guaranteed, however, it is guaranteed that they will stand after relations with a lower value of “order” and before relations with a higher value of “order”.

Приложения могут получать отношения в порядке, принятом по умолчанию, благодаря упорядочению по комбинации (SourceItemID, RelationshipID, Order). Все экземпляры отношения, имеющие источником данную статью, упорядочены как единая коллекция независимо от типа отношений в коллекции. Однако это гарантирует, что все отношения данного типа (например, FolderMembers) являются упорядоченным подмножеством коллекции отношений для данной статьи.Applications can receive relationships in the default order, thanks to ordering by combination (SourceItemID, RelationshipID, Order). All instances of the relationship that have the source of this article are ordered as a single collection, regardless of the type of relationship in the collection. However, this ensures that all relationships of this type (for example, FolderMembers) are an ordered subset of the collection of relationships for this article.

API 312 хранилища данных для манипулирования отношениями реализует множество операций, которые поддерживают упорядочение отношений. Для облегчения объяснения этих операций, введем следующие термины:Relationship manipulation data warehouse API 312 implements many operations that support ordering of relationships. To facilitate the explanation of these operations, we introduce the following terms:

RelFirst это первое отношение в упорядоченной коллекции со значением порядка OrdFirst; RelFirst is the first relation in an ordered collection with an order value of OrdFirst ;

RelLast это последнее отношение в упорядоченной коллекции со значением порядка OrdLast; RelLast is the last relation in an ordered collection with an order value of OrdLast ;

RelX это данное отношение в упорядоченной коллекции со значением порядка OrdX; RelX is a given relation in an ordered collection with an order value of OrdX ;

RelPrev это ближайшее к RelX отношение в коллекции со значением порядка OrdPrev, меньшим чем OrdX; RelPrev is the closest relation to RelX in the collection with an OrdPrev order value less than OrdX ;

RelNext это ближайшее к RelX отношение в коллекции со значением порядка OrdNext, большим, чем OrdX. RelNext is the closest relation to RelX in the collection with an OrdNext order value greater than OrdX .

InsertBeforeFirst(SourceItemID, Relationship)InsertBeforeFirst (SourceItemID, Relationship)

Вставляет отношение как первое отношение в коллекции. Значение свойства «порядок» нового отношения может быть меньше, чем OrdFirst.Inserts a relation as the first relation in the collection. The value of the order property of a new relationship may be less than OrdFirst.

InsertAfterLast(SourceItemID, Relationship)InsertAfterLast (SourceItemID, Relationship)

Вставляет отношение как последнее отношение в коллекции. Значение свойства «порядок» нового отношения может быть больше, чем OrdLast.Inserts a relation as the last relation in the collection. The value of the “order” property of the new relationship may be greater than OrdLast.

InsertAt(SourceItemID, ord, Relationship)InsertAt (SourceItemID, ord, Relationship)

Вставляет отношение с указанным значением свойства «порядок».Inserts a relation with the specified value of the order property.

InsertBefore(SourceItemID, ord, Relationship)InsertBefore (SourceItemID, ord, Relationship)

Вставляет отношение перед отношением с данным значением порядка. Новому отношению можно присвоить значение «порядок», находящееся между OrdPrev и ord, неисключительно.Inserts a relation before a relation with a given order value. The new relation can be assigned the value “order” between OrdPrev and ord, non-exclusively.

InsertAfter(SourceItemID, ord, Relationship)InsertAfter (SourceItemID, ord, Relationship)

Вставляет отношение после отношения с данным значением порядка. Новому отношению можно присвоить значение «порядок», находящееся между ord и OrdNext, неисключительно.Inserts a relation after a relation with a given order value. The new relation can be assigned the value "order" between ord and OrdNext, non-exclusively.

MoveBefore(SourceItemID, ord, RelationshipID)MoveBefore (SourceItemID, ord, RelationshipID)

Перемещает отношение с данным ИД отношения перед отношением с указанным значением «порядок». Отношению можно присвоить новое значение «порядок», находящееся между OrdPrev и ord, неисключительно.Moves the relationship with the given relationship ID before the relationship with the specified order value. A relationship can be assigned a new value, “order,” between OrdPrev and ord, non-exclusively.

MoveAfter(SourceItemID, ord, RelationshipID)MoveAfter (SourceItemID, ord, RelationshipID)

Перемещает отношение с данным ИД отношения после отношения с указанным значением «порядок». Отношению можно присвоить новое значение «порядок», находящееся между ord и OrdNext, неисключительно.Moves the relationship with the given relationship ID after the relationship with the specified order value. A relationship can be assigned a new value, “order,” between ord and OrdNext, non-exclusively.

Как было отмечено выше, каждая статья должна быть элементом Папки статей. В терминах отношений каждая статья должна иметь отношение с Папкой статей. В некоторых вариантах осуществления настоящего изобретения, определенные отношения представляются Отношениями, существующими между Статьями.As noted above, each article must be an element of the Article Folder. In terms of relationships, each article should relate to the Article Folder. In some embodiments of the present invention, certain relationships are represented by Relations existing between the Articles.

Согласно реализации для различных вариантов осуществления настоящего изобретения Отношение обеспечивает направленное бинарное отношение, которое «расширяется» одной Статьей (исходной) до другой Статьи (целевой). Отношение принадлежит исходной статье (статье, которая расширяет его) и, таким образом, Отношение удаляется при удалении источника (например, Отношение удаляется при удалении исходной статьи). Кроме того, в некоторых случаях, Отношение может одновременно принадлежать (находиться в совместном владении) целевой статье, и такая принадлежность может отражаться в свойстве IsOwned (или эквивалентном ему) Отношения (согласно фиг.7 для типа свойства Отношения). В этих вариантах осуществления создание нового отношения IsOwned автоматически ведет к приращению счетчика ссылок на целевую статью, и удаление отношения IsOwned автоматически ведет к отрицательному приращению счетчика ссылок на целевую статью. Для этих конкретных вариантов осуществления статьи продолжают существовать, если они имеют счетчик ссылок больше нуля, и автоматически удаляются, если и когда счетчик достигает нуля. Опять же, Папка статей является Статьей, которая имеет (или способна иметь) множество отношений с другими Статьями, причем эти другие Статьи содержат принадлежность к Папке статей. Другие фактические реализации отношений возможны и предусмотрены настоящим изобретением для обеспечения описанных здесь функциональных возможностей.According to an implementation, for various embodiments of the present invention, the Relationship provides a directional binary relation that is “expanded” by one Article (source) to another Article (target). The relation belongs to the original article (the article that extends it) and, thus, the relation is deleted when the source is deleted (for example, the relation is deleted when the original article is deleted). In addition, in some cases, the Relationship may simultaneously belong to (be jointly owned) the target article, and such ownership may be reflected in the IsOwned property (or its equivalent) of the Relationship (according to Fig. 7 for the type of the Relationship property). In these embodiments, creating a new IsOwned relationship automatically leads to an increment in the reference count of the target article, and deleting an IsOwned relationship automatically leads to a negative increment of the reference count of the target article. For these specific embodiments, articles continue to exist if they have a reference count greater than zero, and are automatically deleted if and when the counter reaches zero. Again, the Article Folder is an Article that has (or is capable of having) many relationships with other Articles, and these other Articles contain affiliation with the Article Folder. Other actual relationship implementations are possible and contemplated by the present invention to provide the functionality described herein.

Независимо от фактической реализации отношение является выбираемым соединением от одного объекта к другому. Способность статьи принадлежать более чем одной Папке статей, а также одной или нескольким Категориям, и являются ли эти статьи, папки и категории публичными или частными, определяется значениями, приписываемыми наличию (или отсутствию) в структуре на основе статей. Эти логические отношения являются значениями, присвоенными множеству отношений, независимо от физической реализации, которые конкретно используются для обеспечения описанных здесь функциональных возможностей. Логические отношения устанавливаются между Статьей и ее Папкой(ами) статей или Категориями (и наоборот), поскольку, в сущности, Папки статей и Категории являются особыми типами статей. Следовательно, с Папками статей и Категориями можно обращаться таким же образом, как с любыми другими Статьями - копировать, добавлять в сообщение электронной почты, внедрять в документ и т.д. без ограничения - и Папки статей и Категории можно преобразовывать к последовательному виду и из последовательного вида (импортировать и экспортировать) с использованием тех же механизмов, что и для других статей (например, в XML все статьи могут иметь последовательный формат, и этот формат в равной мере применяется к Папкам статей, Категориям и Статьям.)Regardless of the actual implementation, the relation is a selectable connection from one object to another. The ability of an article to belong to more than one Article Folder, as well as one or more Categories, and whether these articles, folders and categories are public or private, is determined by the values attributed to the presence (or absence) of the article-based structure. These logical relationships are values assigned to a plurality of relationships, regardless of physical implementation, that are specifically used to provide the functionality described herein. Logical relationships are established between the Article and its Folder (s) of articles or Categories (and vice versa), since, in essence, Folders of articles and Categories are special types of articles. Consequently, Article Folders and Categories can be handled in the same way as with any other Articles - copy, add to an email message, embed in a document, etc. without limitation - both Article Folders and Categories can be converted to a sequential view and from a sequential view (import and export) using the same mechanisms as for other articles (for example, in XML all articles can have a sequential format, and this format is equal applies to Article Folders, Categories and Articles.)

Вышеупомянутые отношения, которые представляют отношение между Статьей и ее Папкой(ами) статей, можно логически расширить от Статьи на Папку статей, от Папки статей на Статью или на обе. Отношение, которое логически расширяется от Статьи на Папку статей, указывает, что Папка статей является публичной по отношению к этой Статье и совместно использует свою информацию принадлежности с этой Статьей; напротив, отсутствие логического отношения от Статьи к Папке статей указывает, что Папка статей является частной по отношению к этой Статье и не использует совместно свою информацию принадлежности с этой Статьей. Аналогично, отношение, которое логически расширяется от Папки статей на Статью, указывает, что Статья является публичной и совместно используемой по отношению к этой Папке статей, тогда как отсутствие логического отношения от Папки статей к Статье указывает, что статья является частной и не совместно используемой. Следовательно, когда Папка статей экспортируется в другую систему, именно «публичные» Статьи совместно используются в новом контексте, и, когда статья ищет свои папки статей для других, совместно используемых статей, именно «публичные» Папки статей снабжают статью информацией относительно совместно используемых статей, принадлежащих им.The above relationships, which represent the relationship between an Article and its Folder (s) of articles, can be logically expanded from an Article to a Folder of articles, from a Folder of articles to an Article, or both. A relationship that logically expands from an Article to an Article Folder indicates that the Article Folder is public in relation to this Article and shares its membership information with this Article; on the contrary, the absence of a logical relationship from an Article to an Article Folder indicates that the Article Folder is private with respect to this Article and does not share its membership information with this Article. Similarly, a relationship that logically expands from an Article Folder to an Article indicates that the Article is public and shared with respect to this Article Folder, while a lack of a logical relationship from the Article Folder to an Article indicates that the article is private and not shared. Therefore, when the Article Folder is exported to another system, it is the “public” Articles that are shared in a new context, and when the article searches for its article folders for other shared articles, it’s the “public” Article Folders that provide the article with information about the shared articles, belonging to them.

На фиг.9 показана блок-схема, иллюстрирующая Папку статей (которая, сама по себе, также является Статьей), входящие в нее статьи и отношения взаимосвязи между Папка статей и входящими в нее статьями. Папка 900 статей содержит совокупность Статей 902, 904 и 906. Папка 900 статей имеет Отношение 912 от себя к Статье 902, которое указывает, что Статья 902 является публичной и совместно используемой по отношению к Папке 900 статей, ее элементам 904 и 906 или любым другим Папкам статей, Категориям или Статьям (не показаны), которые могут осуществлять доступ к Папке 900 статей. Однако не существует Отношения от Статьи 902 к Папке 900 статей, которое указывает, что Папка 900 статей является частной по отношению к Статье 902 и не использует совместно свою информацию принадлежности со Статьей 902. С другой стороны, Статья 904 имеет Отношение 924 от себя к Папке 900 статей, которое указывает, что Папка 900 статей является публичной и совместно использует свою информацию принадлежности со Статьей 904. Однако не существует Отношения от Папки 900 статей к Статье 904, которое указывает, что Статья 904 является частной и не совместно используемой по отношению к Папке 900 статей, ее элементам 902 и 906 и любым другим Папкам статей, Категориям или Статьям (не показаны), которые могут осуществлять доступ к Папке 900 статей. В отличие от этих Отношений (или в их отсутствие) к Статьям 902 и 904, Папка 900 статей имеет Отношение 916 от себя к Статье 906, и Статья 906 имеет Отношение 926 обратно к Папке 900 статей, которые совместно указывают, что статья 906 является публичной и совместно используемой по отношению к Папке 900 статей, ее элементам 902 и 904 и любым другим Папкам статей, Категориям или Статьям (не показаны), которые могут осуществлять доступ к Папке 900 статей, и что Папка 900 статей является публичной и совместно использует свою информацию принадлежности со Статьей 906.Fig. 9 is a block diagram illustrating an Article Folder (which, by itself, is also an Article), its articles, and the relationship between the Article Folder and its articles. A folder of 900 articles contains a combination of Articles 902, 904 and 906. A folder of 900 articles has a Relationship of 912 from itself to Article 902, which indicates that Article 902 is public and shared with respect to the Folder 900 of articles, its elements 904 and 906, or any other Article Folders, Categories or Articles (not shown) that can access the Folder of 900 articles. However, there is no Relationship from Article 902 to the Folder of 900 articles, which indicates that the Folder of 900 articles is private with respect to Article 902 and does not share its membership information with Article 902. On the other hand, Article 904 has a ratio of 924 from itself to the Folder 900 articles, which indicates that the Folder of 900 articles is public and shares its ownership information with Article 904. However, there is no Relationship from the Folder of 900 articles to Article 904, which indicates that Article 904 is private and not shared mine in relation to the Folder of 900 articles, its elements 902 and 906 and any other Folders of articles, Categories or Articles (not shown) that can access the Folder of 900 articles. Unlike these Relationships (or in their absence) to Articles 902 and 904, the Folder of 900 articles has a Relationship of 916 from itself to Article 906, and Article 906 has a Relationship of 926 back to a Folder of 900 articles that together indicate that Article 906 is public and shared with respect to the Folder of 900 articles, its elements 902 and 904 and any other Folders of articles, Categories or Articles (not shown) that can access the Folder of 900 articles, and that the Folder of 900 articles is public and shares its information accessories with Article 906.

Согласно рассмотренному ранее, Статьи в Папке статей не нуждаются в совместном использовании общности, поскольку Папки статей не «описаны». С другой стороны, категории описаны общностью, которая является общей для всех входящих в нее статей. Поэтому принадлежность к Категории внутренне ограничена Статьями, имеющими описанную общность и, в определенных вариантах осуществления, все Статьи, отвечающие описанию Категории, автоматически становятся элементами Категории. Таким образом, в то время как Папки статей позволяют представлять структуры тривиальных типов на основании их принадлежности, Категории допускают принадлежность на основании заданной общности.As discussed previously, Articles in the Article Folder do not need to be shared with each other since the Article Folders are not “described”. On the other hand, categories are described by a commonality that is common to all articles included in it. Therefore, belonging to the Category is internally limited by Articles having the described generality and, in certain embodiments, all Articles meeting the Category description automatically become Category elements. Thus, while Article Folders allow you to represent structures of trivial types based on their affiliation, Categories allow affiliation on the basis of a given generality.

Конечно, описания Категории логичны по природе и поэтому Категорию можно описывать посредством любого логического представления типов, свойств и/или значений. Например, логическим представлением Категории может быть условие принадлежности к ней, согласно которому Статья должна иметь одно из двух свойств или оба. Если эти описанные свойства для Категории обозначить как "A" и "B", то принадлежность к Категории может предусматривать, что Статьи имеют свойство А, но не В, Статьи имеют свойство В, но не А, и Статьи имеют оба свойства А и В. Это логическое представление свойств описывается логическим оператором "OR", при этом множество элементов, описанных Категорией, представляет собой Статьи, имеющие свойство A OR B. Аналогичные логические операторы (включая без ограничения "AND", "XOR" и "NOT" по отдельности или в совокупности) также можно использовать для описания категории, что очевидно специалистам в данной области.Of course, the descriptions of the Category are logical in nature and therefore the Category can be described by any logical representation of types, properties and / or values. For example, a logical representation of a Category may be a condition of belonging to it, according to which an Article must have one of two properties, or both. If these described properties for the Category are designated as "A" and "B", then belonging to the Category may provide that Articles have property A, but not B, Articles have property B, but not A, and Articles have both properties A and B This logical representation of properties is described by the logical operator "OR", while the many elements described by the Category are Articles that have the property A OR B. Similar logical operators (including without limitation "AND", "XOR" and "NOT" individually or together) can also be used to describe categories that are obvious to experts in this field.

Несмотря на разницу между Папками статей (не описаны) и Категориями (описаны), отношение категорий к статьям и отношение статей к категориям, по существу, такие же, как описанные выше для папок статей и статей во многих вариантах осуществления настоящего изобретения.Despite the difference between Article Folders (not described) and Categories (described), the relation of categories to articles and the relation of articles to categories is essentially the same as described above for article folders and articles in many embodiments of the present invention.

На фиг.10 показана блок-схема, иллюстрирующая категорию (которая сама по себе является статьей), входящие в нее статьи и отношения взаимосвязи между категорией и входящими в нее статьями. Категории 1000 принадлежат статьи 1002, 1004, и 1006, которые все совместно используют комбинацию общих свойств, значений или типов 1008, описанных (описание общности 1008') категорией 1000. Категория 1000 имеет отношение 1012 от себя к статье 1002, которое указывает, что статья 1002 является публичной и совместно используемой по отношению к категории 1000, ее элементам 1004 и 1006 и любым другим категориям, папкам статей или статьям (не показаны), которые могут осуществлять доступ к категории 1000. Однако не существует отношения от статьи 1002 к категории 1000, которое указывает, что категория 1000 является частной по отношению к статье 1002 и не использует совместно свою информацию принадлежности со статьей 1002. С другой стороны, статья 1004 имеет отношение 1024 от себя к категории 1000, которое указывает, что категория 1000 является публичной и совместно использует свою информацию принадлежности со статьей 1004. Однако не существует отношения, расширенного от категории 1000 к статье 1004, которое указывает, что статья 1004 является частной и не совместно используемой по отношению к категории 1000, другим ее элементам 1002 и 1006 и любым другим категориям, папкам статей или статьям (не показаны), которые могут осуществлять доступ к категории 1000. В отличие от этого отношения (или в его отсутствие) со статьями 1002 и 1004, категория 1000 имеет отношение 1016 от себя к статье 1006, и статья 1006 имеет отношение 1026 обратно к категории 1000, которые совместно указывают, что статья 1006 является публичной и совместно используемой по отношению к категории 1000, входящим в нее статьям 1002 и 1004 и любым другим категориям, папкам статей или статьям (не показаны), которые могут осуществлять доступ к категории 1000, и что категория 1000 является публичной и совместно использует свою информацию принадлежности со статьей 1006.Figure 10 shows a block diagram illustrating a category (which is an article in itself), the articles included in it, and the relationship between the category and the articles included in it. Categories 1000 belong to articles 1002, 1004, and 1006, which all share a combination of common properties, values, or types 1008 described (generality description 1008 ') by category 1000. Category 1000 relates 1012 from itself to article 1002, which indicates that the article 1002 is public and shared with respect to category 1000, its elements 1004 and 1006 and any other categories, article folders or articles (not shown) that can access category 1000. However, there is no relationship from article 1002 to category 1000, which indicates t, that category 1000 is private with respect to article 1002 and does not share its membership information with article 1002. On the other hand, article 1004 relates 1024 from itself to category 1000, which indicates that category 1000 is public and shares its membership information with article 1004. However, there is no relationship extended from category 1000 to article 1004, which indicates that article 1004 is private and not shared with respect to category 1000, its other elements 1002 and 1006, and any other to other categories, article folders or articles (not shown) that can access category 1000. In contrast to this relationship (or in its absence) with articles 1002 and 1004, category 1000 has a relationship of 1016 from itself to article 1006, and article 1006 relates 1026 back to category 1000, which together indicate that article 1006 is public and shared with respect to category 1000, its articles 1002 and 1004, and any other categories, article folders, or articles (not shown) that may access category 10 00, and that category 1000 is public and shares its membership information with article 1006.

Наконец, поскольку Категории и Папки статей сами являются Статьями, и Статьи могут иметь Отношение друг к другу, Категории могут иметь Отношение к Папкам статей и наоборот, и Категории, Папки статей и Статьи могут иметь Отношение к другим Категориям, Папкам статей и Статьям, соответственно, согласно некоторым альтернативным вариантам осуществления. Однако в различных вариантах осуществления структурам Папки статей и/или структурам Категории запрещено, на уровне системы программно-аппаратного интерфейса, содержать циклы. Когда структуры Папки статей и Категории похожи на ориентированные графы, варианты осуществления, запрещающие циклы, напоминают ориентированные ациклические графы (DAG), которые, согласно математическому определению из теории графов, являются ориентированными графами, в которых ни один путь не может начинаться и заканчиваться в одной и той же вершине.Finally, since Categories and Article Folders themselves are Articles, and Articles can relate to each other, Categories can relate to Article folders and vice versa, and Categories, Article Folders and Articles can relate to other Categories, Article Folders and Articles, respectively , according to some alternative embodiments. However, in various embodiments, Article Folder structures and / or Category structures are prohibited from containing loops at the system-level hardware-software interface. When the structures of the Article Folder and Category are similar to oriented graphs, embodiments that prohibit loops resemble oriented acyclic graphs (DAGs), which, according to the mathematical definition of graph theory, are directed graphs in which no path can begin and end in one and the same peak.

6. Расширяемость6. Extensibility

Платформа хранения предназначена быть снабженной начальным множеством схем 340 согласно описанному выше. Кроме того, согласно, по меньшей мере, некоторым вариантам осуществления, платформа хранения позволяет потребителям, в том числе независимым поставщикам программного обеспечения (ISV), создавать новые схемы 344 (т.е. новые типы «статья» (Item) и «вложенный элемент» (Nested Element)). Этот раздел посвящен механизму создания таких схем путем расширения типов «статья» и типов «вложенный элемент» (или просто типов «элемент»), заданных в начальном множестве схем 340.The storage platform is intended to be provided with an initial set of circuits 340 as described above. In addition, according to at least some embodiments, the storage platform allows consumers, including independent software vendors (ISVs), to create new schemes 344 (i.e., new types of “Item” and “nested item” "(Nested Element)). This section is devoted to the mechanism for creating such schemes by expanding the types of "article" and the types of "nested element" (or simply types of "element") defined in the initial set of schemes 340.

Предпочтительно, расширение начального множества типов статей и вложенных элементов ограничивается следующим образом:Preferably, the expansion of the initial set of article types and nested elements is limited as follows:

ISV разрешено вводить новые типы Item, т.е. подтип Base.Item;ISV is allowed to introduce new types of Item, i.e. subtype of Base.Item;

ISV разрешено вводить новые типы Nested Element, т.е. подтип Base.NestedElement;ISVs are allowed to introduce new types of Nested Element, i.e. subtype of Base.NestedElement;

ISV разрешено вводить новые расширения, т.е. подтип Base.NestedElement; но,ISV is allowed to introduce new extensions, i.e. subtype of Base.NestedElement; but,

ISV не может определять подтипы любых типов (типов Item, Nested Element или Extension), заданных начальным множеством схем 340 платформы хранения.ISV cannot determine subtypes of any types (Item, Nested Element, or Extension types) defined by the initial set of storage platform circuits 340.

Поскольку тип статьи или тип вложенного элемента, заданные начальным множеством схем платформы хранения, могут не вполне отвечать потребностям ISV, необходимо позволить ISV видоизменять тип. Это возможно с помощью формализации расширений. Расширения - это сильно типизированные экземпляры, но (а) они не могут существовать независимо и (b) они должны быть присоединены к статье или вложенному элементу.Since the type of article or the type of the nested item specified by the initial set of storage platform schemas may not fully meet the needs of the ISV, you must enable the ISV to modify the type. This is possible by formalizing extensions. Extensions are strongly typed instances, but (a) they cannot exist independently and (b) they must be attached to the article or nested element.

Помимо удовлетворения необходимости в расширяемости схемы, расширения также призваны решать вопрос «множественного определения типов». Поскольку, в некоторых вариантах осуществления, платформа хранения может не поддерживать множественное наследование или перекрытие подтипов, приложения могут использовать расширения для моделирования перекрывающихся экземпляров типа (например, Документ является одновременно юридическим документом и защищенным документом).In addition to satisfying the need for schema extensibility, extensions are also designed to address the issue of "multiple type definitions". Since, in some embodiments, the storage platform may not support multiple inheritance or overlapping subtypes, applications can use extensions to model overlapping instances of a type (for example, a Document is both a legal document and a protected document).

a) Расширения статьиa) Article extensions

Для обеспечения расширяемости статей модель данных дополнительно задает абстрактный тип под названием Base.Extension. Это корневой тип в иерархии типов расширений. Приложения могут определять подтипы Base.Extension для создания конкретных типов расширений.To ensure the extensibility of articles, the data model additionally defines an abstract type called Base.Extension. This is the root type in the extension type hierarchy. Applications can define subtypes of Base.Extension to create specific types of extensions.

Тип Base.Extension задан в Базовой схеме следующим образом:The Base.Extension type is defined in the Base schema as follows:

<Type Name="Base.Extension" IsAbstract="True"><Type Name = "Base.Extension" IsAbstract = "True">

<Propety Name="ItemID"<Propety Name = "ItemID"

Type="the storage platformTypes.uniqueidentified"Type = "the storage platformTypes.uniqueidentified"

Nullable="false" MultiValued="false"/>Nullable = "false" MultiValued = "false" />

<Property Name="ExtensionID"<Property Name = "ExtensionID"

Type="the storage platformTypes.uniqueidentified"Type = "the storage platformTypes.uniqueidentified"

Nullable="false" MultiValued="false"/>Nullable = "false" MultiValued = "false" />

</Type></Type>

Поле ItemID содержит ItemID статьи, с которой связано расширение. Статья с этим ItemID должна существовать. Расширение нельзя создать, если статьи с данным ItemID не существует. При удалении статьи все расширения с тем же ItemID удаляются. Кортеж (ItemID,ExtensionID) уникально идентифицирует экземпляр расширения.The ItemID field contains the ItemID of the article the extension is associated with. An article with this ItemID must exist. An extension cannot be created if an article with this ItemID does not exist. When you delete an article, all extensions with the same ItemID are deleted. The tuple (ItemID, ExtensionID) uniquely identifies the extension instance.

Структура тип расширения аналогична структуре типа статьи.The structure of the type of extension is similar to the structure of the type of article.

Типы расширений имеют поля.Extension types have fields.

Поля могут быть примитивных типов или типов вложенного элемента.Fields can be primitive types or nested element types.

Типы расширений допускают определение подтипов.Extension types allow subtypes to be defined.

К типам расширений применяются следующие ограничения:The following restrictions apply to extension types:

расширения не могут быть источниками и целями отношений;extensions cannot be the sources and goals of relationships;

экземпляры типов расширений не могут существовать независимо от статьи; иinstances of extension types cannot exist independently of the article; and

Типы расширений нельзя использовать как типы полей в определениях типов платформы хранения.Extension types cannot be used as field types in storage platform type definitions.

На типы расширений, которые могут быть связаны с данным типом статьи, не накладываются никакие ограничения. Любой тип расширения может расширять любой тип статьи. Когда к статье присоединено несколько экземпляров расширения, они независимы друг от друга как по структуре, так и по поведению.The types of extensions that may be associated with this type of article are not subject to any restrictions. Any type of extension can expand any type of article. When several instances of the extension are attached to the article, they are independent of each other both in structure and in behavior.

Экземплярам расширения обеспечивается хранение и доступ отдельно от статьи. Все экземпляры типа расширения доступны для глобального вида расширений. Можно составить эффективный запрос, который возвратит все экземпляры данного типа расширения независимо от того, со статьей какого типа они связаны. API платформы хранения обеспечивают модель программирования, которая позволяет сохранять, извлекать и изменять расширения на статьях.Extension instances are provided with storage and access separate from the article. All instances of the extension type are available for the global extension type. You can create an effective query that returns all instances of this type of extension, regardless of what type of article they are associated with. Storage platform APIs provide a programming model that allows you to save, retrieve, and modify extensions on articles.

Типы расширения могут представлять собой типы, полученные путем определения подтипов с использованием единичной модели наследования платформы хранения. Вывод из типа расширения создает новый тип расширения. Структура или поведение расширения не может подменять или заменять структуру или поведения иерархии типов статей.Extension types can be types obtained by defining subtypes using a single storage platform inheritance model. Deriving an extension type creates a new extension type. The structure or behavior of an extension cannot replace or replace the structure or behavior of a hierarchy of article types.

По аналогии с типами статей экземпляры типа расширения могут быть непосредственно доступны за счет вида, связанного с типом расширения. ItemID расширения указывает, какой статье оно принадлежит, и его можно использовать для извлечения соответствующего объекта «статья» из глобального вида статьи.By analogy with article types, instances of the extension type can be directly accessed due to the view associated with the extension type. The extension’s ItemID indicates which article it belongs to and can be used to retrieve the corresponding “article” object from the global view of the article.

В целях операционной согласованности, расширения рассматриваются как часть статьи. Операции Copy/Move, Backup/Restore и другие общеизвестные операции, заданные на платформе хранения, могут выполняться на расширениях как на части статьи.For operational consistency, extensions are considered part of the article. Copy / Move, Backup / Restore, and other well-known operations defined on the storage platform can be performed on extensions as part of an article.

Рассмотрим следующий пример. В наборе типов Windows задается тип Contact (контакт).Consider the following example. In the Windows type set, the Contact type is set.

<Type Name="Contact" BaseType="Base.Item"><Type Name = "Contact" BaseType = "Base.Item">

<Property Name="Name"<Property Name = "Name"

Type="String"Type = "String"

Nullable="false"Nullable = "false"

MultiValued="false"/>MultiValued = "false" />

<Property Name="Address"<Property Name = "Address"

Type="Address"Type = "Address"

Nullable="true"Nullable = "true"

MultiValued="false"/>MultiValued = "false" />

</Tуре></ Tour>

Разработчик приложения CRM желает присоединить расширение приложения CRM к контактам, хранящимся в платформе хранения. Разработчик приложения задает расширение CRM, содержащее дополнительную структуру данных, которой может манипулировать приложение.The CRM application developer wants to attach the CRM application extension to the contacts stored in the storage platform. The application developer defines a CRM extension that contains an additional data structure that the application can manipulate.

<Type Name="CRMExtension" BaseType="Base.Extension"><Type Name = "CRMExtension" BaseType = "Base.Extension">

<Property Name="CustomerID"<Property Name = "CustomerID"

Type="String"Type = "String"

Nullable="false"Nullable = "false"

MultiValued="false"/>MultiValued = "false" />

...

</Type></Type>

Разработчик приложения HR также желает присоединить к контактам дополнительные данные. Эти данные независимы от данных приложения CRM. Опять же, разработчик приложения может создать расширениеThe HR application developer also wishes to attach additional data to the contacts. This data is independent of CRM application data. Again, the application developer can create an extension

<Type Name="HRExtension" EBaseType="Base.Extension"><Type Name = "HRExtension" EBaseType = "Base.Extension">

<Property Name="EmployeeID"<Property Name = "EmployeeID"

Type="String"Type = "String"

Nullable="false"Nullable = "false"

MultiValued="false"/>MultiValued = "false" />

...

</Type></Type>

CRMExtension и HRExtension это два независимых расширения, которые можно присоединить к статьям «контакт». Их создание и доступ к ним осуществляются независимо друг от друга.CRMExtension and HRExtension are two independent extensions that you can add to your contact articles. Their creation and access to them are carried out independently of each other.

В вышеприведенном примере поля и методы типа CRMExtension не могут подменять поля и методы иерархии контактов. Следует заметить, что экземпляры типа CRMExtension могут быть присоединены к другим типам статей, помимо «контактов».In the above example, fields and methods of the CRMExtension type cannot replace fields and methods of the contact hierarchy. It should be noted that instances of the CRMExtension type can be attached to other types of articles, in addition to “contacts”.

При извлечении статьи «контакт», ее расширения статьи не извлекаются автоматически. Для данной статьи «контакт», к связанным с ней расширениям статьи, можно осуществить доступ, запросив глобальный вид расширений для расширений с тем же ItemId.When you extract the article "contact", its extension articles are not automatically extracted. For this “contact” article, you can access the related article extensions by requesting a global view of extensions for extensions with the same ItemId.

Ко всем расширениям CRMExtension в системе можно осуществлять доступ через вид типа CRMExtension, независимо от того, какой статье оно принадлежит. Все расширения статьи для статьи совместно используют один и тот же идентификатор статьи. В вышеприведенном примере экземпляр статьи «контакт» и экземпляры присоединенных CRMExtension и HRExtension имеют одинаковый ItemID.All CRMExtension extensions in the system can be accessed through a view of the CRMExtension type, regardless of which article it belongs to. All article extensions for an article share the same article identifier. In the above example, the instance of the contact article and the instances of the attached CRMExtension and HRExtension have the same ItemID.

В следующей таблице сведены сходства и различия типов статьи, расширения и вложенного элемента:The following table summarizes the similarities and differences between article types, extensions, and nested elements:

Сравнение статьи, расширения статьи и вложенного элементаCompare article, article extension, and nested item СтатьяArticle Расширение статьиArticle Extension Вложенный элементNested element ИД статьиArticle id Имеет собственный идентификатор статьиHas its own article id Совместно со статьей использует ИД статьиTogether with the article uses the article ID Не имеет собственного ИД статьи. Вложенный элемент является частью статьиDoes not have its own article ID. The nested element is part of the article. ХранениеStorage Иерархия статьи хранится в ее собственных таблицахThe article hierarchy is stored in its own tables. Иерархия расширения статьи хранится в ее собственных таблицахArticle extension hierarchy is stored in its own tables. Хранится со статьейStored with article Запрос/поискQuery / Search Может запрашивать таблицы статейMay query article tables Может запрашивать таблицы расширений статейCan query article extension tables В общем случае, может запрашиваться только в содержащем статью контекстеIn general, it can only be requested in the context containing the article Объем запроса/поискаRequest / Search Scope Может искать по всем экземплярам типа статьиCan search across all instances of an article type Может искать по всем экземплярам типа расширения статьиCan search across all instances of an article extension type В общем случае, может искать только среди экземпляров типа вложенного элемента одной (содержащей) статьиIn the general case, it can search only among instances of the type of a nested element of one (containing) article Семантика отношенийRelationship semantics Может иметь отношения к статьямMay relate to articles Не имеет отношений к расширениям статейNot related to article extensions Не имеет отношений к вложенным элементамNot related to nested elements Связь со статьямиLink to Articles Может быть связана с другими статьями посредством отношения поддержания, внедрения и мягких отношенийMay be related to other articles through a maintenance, implementation and soft relationship. В общем случае, может быть связано только посредством расширений. Семантика расширений аналогична семантике вложенных статейIn general, it can only be connected through extensions. The semantics of extensions are similar to the semantics of nested articles Связан со статьей через поля. Вложенные элементы являются частью статьиAssociated with the article through the fields. Nested elements are part of the article.

b) Расширение типов вложенных элементовb) Extension of types of nested elements

Типы вложенных элементов не расширяются с помощью того же механизма, что и типы статей. Расширениям вложенных элементов обеспечены хранение и доступ с помощью тех же механизмов, что и для полей типов вложенных элементов.Types of nested elements are not expanded using the same mechanism as article types. The extensions of nested elements are provided with storage and access using the same mechanisms as for the type fields of nested elements.

Модель данных задает корень для типов вложенных элементов под названием Element:The data model sets the root for the types of nested elements called Element:

<Type Name="Element" IsAbstract="True"><Type Name = "Element" IsAbstract = "True">

<Property Name="ElementID"<Property Name = "ElementID"

Type="the storage platformTypes.uniqueidentifier"Type = "the storage platformTypes.uniqueidentifier"

Nullable="false"Nullable = "false"

MultiValued="false"/>MultiValued = "false" />

</Type></Type>

Тип NestedElement наследует от этого типа. Тип элемента NestedElement дополнительно задает поле, которое является множеством нескольких элементов.The type NestedElement inherits from this type. The element type NestedElement additionally defines a field that is a set of multiple elements.

<Type Name="NestedElement" BaseType="Base.Element"<Type Name = "NestedElement" BaseType = "Base.Element"

IsAbstract="True">IsAbstract = "True">

<Property Name="Extensions"<Property Name = "Extensions"

Type="Base.Element"Type = "Base.Element"

Nullable="false"Nullable = "false"

MultiValued="true"/>MultiValued = "true" />

</Type></Type>

Расширения вложенного элемента отличаются от расширений статьи следующим.Extensions of a nested element differ from the extensions of an article as follows.

Расширения вложенного элемента не являются типами расширения. Они не принадлежат иерархии типов расширения, корнем которой является тип Base.Extension.Nested item extensions are not extension types. They do not belong to the extension type hierarchy whose root is the Base.Extension type.

Расширения вложенного элемента хранятся совместно с другими полями статьи и не являются глобально доступным - нельзя составить запрос, который извлекает все экземпляры данного типа расширения.Extensions of a nested element are stored together with other fields of the article and are not globally accessible - you cannot create a query that retrieves all instances of this type of extension.

Эти расширения хранятся таким же образом, что и другие вложенные элементы (статьи). Аналогично другим вложенным множествам расширения вложенного элемента хранятся в UDT. Они доступны через поле Extensions типа вложенного элемента.These extensions are stored in the same way as other nested items (articles). Like other nested sets, extensions of the nested element are stored in the UDT. They are available through the Extensions field of the nested item type.

Интерфейсы коллекции, используемые для доступа к многозначным свойствам, также используются для доступа и итерации по множеству расширений типа.Collection interfaces used to access multi-valued properties are also used to access and iterate over multiple type extensions.

Следующая таблица сводит и сравнивает расширения статьи и расширения вложенного элемента.The following table summarizes and compares article extensions and nested element extensions.

Сравнение расширений статьи и расширений вложенного элементаComparing article extensions and nested item extensions Расширение статьиArticle Extension Разрешение вложенного элементаNested Item Resolution ХранениеStorage Иерархия расширения статьи хранится в ее собственных таблицахArticle extension hierarchy is stored in its own tables. Хранится как вложенные элементыStored as nested items Запрос/поискQuery / Search Может запрашивать таблицы расширений статьи May query article extension tables В общем случае, может запрашиваться только в содержащем статью контекстеIn general, it can only be requested in the context containing the article Объем запроса/поискаRequest / Search Scope Может искать по всем экземплярам типа расширения статьиCan search across all instances of an article extension type В общем случае, может искать только среди экземпляров типа вложенного элемента одной (содержащей) статьиIn the general case, it can search only among instances of the type of a nested element of one (containing) article ПрограммируемостьProgrammability Нужны специальные API расширения и специальные запросы таблиц расширенияNeed special extension APIs and special extension table queries Расширения вложенного элемента подобны любому другому многозначному полю вложенного элемента; используются нормальные API типа вложенного элементаExtensions of a nested element are similar to any other multivalued field of a nested element; normal nested element type APIs are used ПоведениеBehavior Может связывать поведениеCan bind behavior Никакое поведение не разрешено (?)No behavior allowed (?) Семантика отношенийRelationship semantics Нет отношений к расширениям статьиNo relation to article extensions Нет отношений к расширениям вложенного элементаNo relation to nested item extensions ИД статьиArticle id Совместно со статьей использует ИД статьиTogether with the article uses the article ID Не имеет собственного ИД статьи. Расширение вложенного элемента является частью статьиDoes not have its own article ID. Extension of a nested element is part of the article

D. МАШИНА БАЗЫ ДАННЫХD. DATABASE MACHINE

Как отмечено выше, хранилище данных реализовано на машине базы данных. Согласно данному варианту осуществления машина базы данных содержит машину реляционной базы данных, которая реализует язык запросов SQL, например машину Microsoft SQL Server, с реляционными расширениями объекта. В этом разделе описано отображение модели данных, которую реализует хранилище данных, на реляционное хранилище и обеспечивает информацию на логическом API, потребляемом клиентами платформы хранения, согласно данному варианту осуществления. Однако понятно, что при использовании другой машины базы данных можно использовать другое отображение. Действительно, помимо реализации принципиальной модели данных на машине реляционной базы данных, ее также можно реализовать на других типах баз данных, например, объектно-ориентированных базах данных и базах данных XML.As noted above, the data warehouse is implemented on a database machine. According to this embodiment, the database engine comprises a relational database engine that implements an SQL query language, such as a Microsoft SQL Server machine, with relational object extensions. This section describes the mapping of the data model that the data warehouse implements to relational storage and provides information on the logical API consumed by the clients of the storage platform according to this embodiment. However, it is understood that when using a different database machine, a different mapping can be used. Indeed, in addition to implementing a basic data model on a relational database machine, it can also be implemented on other types of databases, for example, object-oriented databases and XML databases.

Объектно-ориентированная (ОО) система базы данных обеспечивает устойчивость и транзакции для объектов языка программирования (например, C++, Java). Понятие «статья» платформы хранения отображается в «объект» в объектно-ориентированных системах, хотя встроенные коллекции нужно добавлять к объектам. Другие понятия типов платформы хранения, например наследование и типы вложенного элемента, также отображаются в объектно-ориентированную систему типов. Объектно-ориентированные системы обычно уже поддерживают идентификацию объекта; поэтому идентификацию статьи можно отображать в идентификацию объекта. Поведения статьи (операции) отображаются в объектные методы. Однако объектно-ориентированным системам обычно недостает организационных возможностей и средств поиска. Кроме того, объектно-ориентированные системы не обеспечивают поддержку для неструктурированных и частично структурированных данных. Для поддержки описанной здесь полной модели данных платформы хранения такие понятия как отношения, папки и расширения нужно добавлять в объектную модель данных. Кроме того, нужно реализовывать такие механизмы, как продвижения, синхронизация, извещения и безопасность.An object-oriented (OO) database system provides stability and transactions for programming language objects (for example, C ++, Java). The concept of an “article” of a storage platform is mapped to an “object” in object-oriented systems, although built-in collections need to be added to objects. Other concepts of storage platform types, such as inheritance and nested element types, also map to the object-oriented type system. Object-oriented systems usually already support object identification; therefore, article identification can be mapped to object identification. Article behaviors (operations) are mapped to object methods. However, object-oriented systems usually lack organizational capabilities and search tools. In addition, object-oriented systems do not provide support for unstructured and partially structured data. To support the complete storage platform data model described here, concepts such as relationships, folders, and extensions need to be added to the data object model. In addition, mechanisms such as promotions, synchronization, notifications, and security need to be implemented.

Подобно объектно-ориентированным системам базы данных XML, основанные на XSD (определение схемы XML), поддерживают систему типов, основанную на единичном наследовании. Система типов статьи согласно настоящему изобретению может отображаться в модель типов XSD. XSD также не обеспечивают поддержку поведений. XSD для статей нужно дополнять поведениями статей. Базы данных XML имеют дело с отдельными документами XSD и не имеют возможностей организации и широкомасштабного поиска. Как и с объектно-ориентированными базами данных, для поддержки описанной здесь модели данных, в такие базы данных XML нужно включать другие понятия, например отношения и папки; кроме того, нужно реализовать такие механизмы, как синхронизация, извещения и безопасность.Like object-oriented systems, XML databases based on XSD (XML Schema Definition) support a single-inheritance type system. The article type system of the present invention can be mapped to an XSD type model. XSD also does not provide behavior support. XSD for articles needs to be complemented by article behaviors. XML databases deal with individual XSD documents and lack organization and large-scale search capabilities. As with object-oriented databases, in order to support the data model described here, other concepts must be included in such XML databases, such as relationships and folders; In addition, mechanisms such as synchronization, notifications, and security must be implemented.

1. Реализация хранилища данных с использованием UDT1. Implementing a data warehouse using UDT

Согласно данному варианту осуществления машина 314 реляционной базы данных, которая, согласно одному варианту осуществления, содержит машину Microsoft SQL Server, поддерживает встроенные скалярные типы. Встроенные скалярные типы являются «родными» и «простыми». Они являются родными в том смысле, что пользователь не может задавать свои собственные типы, и они являются простыми в том смысле, что они не могут инкапсулировать сложную структуру. Типы, заданные пользователем (далее UDT), обеспечивают механизм для расширяемости типов за пределы система родных скалярных типов, позволяя пользователям расширять систему типов путем задания сложных, структурированных типов. Будучи задан пользователем, UDT не может использоваться где-либо в системе типов, в которой можно использовать встроенный скалярный тип.According to this embodiment, the relational database engine 314, which, according to one embodiment, comprises a Microsoft SQL Server machine, supports built-in scalar types. Built-in scalar types are "native" and "simple." They are native in the sense that the user cannot set their own types, and they are simple in the sense that they cannot encapsulate a complex structure. User-defined types (UDTs) provide a mechanism for extensibility of types beyond the native scalar type system, allowing users to extend the type system by defining complex, structured types. Once defined by the user, UDT cannot be used anywhere in the type system in which the built-in scalar type can be used.

Согласно аспекту настоящего изобретения схемы платформы хранения отображаются в классы UDT в хранилище машины базы данных. Статьи хранилища данных отображаются в классы UDT, выводимые из типа Base.Item. Как и статьи, расширения также отображаются в классы UDT и используют наследование. Корневым типом расширения является Base.Extension, из которого выводятся все типы расширения.According to an aspect of the present invention, storage platform schemes are mapped to UDT classes in the storage of a database machine. Data warehouse articles are mapped to UDT classes inferred from the Base.Item type. Like articles, extensions also map to UDT classes and use inheritance. The root type of extension is Base.Extension, from which all extension types are derived.

UDT - это класс CLR, он имеет состояние (т.е. поля данных) и поведение (т.е. процедуры). UDT задаются с использованием любого управляемого языка - C#, VB.NET и т.д. Методы и операторы UDT можно вызывать в T-SQL для экземпляра этого типа. UDT может быть: типом столбца в строке, типом параметра процедуры в T-SQL или типом переменной в T-SQL.UDT is a CLR class, it has state (i.e. data fields) and behavior (i.e. procedures). UDTs are set using any managed language - C #, VB.NET, etc. UDT methods and operators can be invoked in T-SQL for an instance of this type. A UDT can be: a column type in a row, a procedure parameter type in T-SQL, or a variable type in T-SQL.

Следующий пример иллюстрирует основы UDT. Пусть MapLib.dll имеет ассемблер, именуемый MapLib. В этом ассемблере имеется класс, именуемый Point, под пространством имен BaseTypes:The following example illustrates the basics of UDT. Let MapLib.dll have an assembler called MapLib. This assembler has a class called Point, under the BaseTypes namespace:

namespace BaseTypesnamespace BaseTypes

{{

public class Pointpublic class Point

{{

//возвращает расстояние от заданной точки.// returns the distance from the given point.

public double Distance(Point p)public double Distance (Point p)

{{

// возвращает расстояние между точкой p и этой точкой// returns the distance between point p and this point

}}

// другое содержимое в классе// other content in the class

}}

}}

Следующий код T-SQL связывает класс Point с UDT SQL Server, именуемым Point. Первый этап вызывает "CreateAssembly", который загружает ассемблер MapLib в базу данных. Второй этап вызывает "Create Type" для создания типа, заданного пользователем, "Point" и связывания его с управляемым типом BaseTypes.Point:The following T-SQL code associates the Point class with a SQL Server UDT called Point. The first step calls "CreateAssembly", which loads the MapLib assembler into the database. The second step calls "Create Type" to create a user-defined type, "Point" and associate it with the BaseTypes.Point managed type:

CREATE ASSEMBLY MapLib FROM '\\mysrv\share\MapLib.dll'CREATE ASSEMBLY MapLib FROM '\\ mysrv \ share \ MapLib.dll'

gogo

CREATE TYPE PointCREATE TYPE Point

EXTERNAL NAME 'BaseTypes.Point'EXTERNAL NAME 'BaseTypes.Point'

gogo

После создания UDT "Point" можно использовать как столбец в таблице, и в T-SQL можно вызывать методы, как показано ниже:After creating the UDT, “Point” can be used as a column in a table, and methods can be called in T-SQL, as shown below:

Create table Cities(Create table Cities (

Name varchar(20),Name varchar (20),

State varchar(20),State varchar (20),

Location Point)Location Point)

-- Извлекают расстояние между городами- Extract the distance between cities

-- из координат (32,23)- from coordinates (32,23)

Declare @p point(32, 23), @distance floatDeclare @p point (32, 23), @distance float

Select Location::Distance(@p)Select Location :: Distance (@p)

From CitiesFrom cities

Отображения схемы платформы хранения в классы UDT довольно прямые на высоком уровне. В общем случае схема платформы хранения отображается в пространство имен CLR. Тип платформы хранения отображается в класс CLR. Наследование класса CLR отражает наследование типа платформы хранения, и свойство платформы хранения отображается в свойство класса CLR.The mapping of the storage platform schema to the UDT classes is fairly straightforward at a high level. In general, the storage platform schema maps to the CLR namespace. The type of storage platform is mapped to the CLR class. CLR class inheritance reflects the inheritance of the storage platform type, and the storage platform property maps to the CLR class property.

Иерархия статьи, показанная на фиг.29, используется в качестве примера в этом документе. Показан тип Base.Item, из которого выводятся все типы статьи, совместно с множеством производных типов статьи (например, Contact.Person и Contact.Employee), с наследованием, указанным стрелками.The article hierarchy shown in FIG. 29 is used as an example in this document. The Base.Item type is shown, from which all article types are derived, together with many derived article types (for example, Contact.Person and Contact.Employee), with the inheritance indicated by arrows.

2. Отображение статей2. Display articles

Если нужно, чтобы можно было глобально искать статью, и для поддержки в реляционной базе данных, согласно данному варианту осуществления наследования и подставимости типов, одна возможная реализация хранения статей в хранилище базы данных предусматривает хранение всех статей в одной таблице со столбцом типа Base.Item. Используя подставимость типов, можно сохранять статьи всех типов и можно фильтровать поиски по типу и подтипу статьи с использованием оператора Юкона "is of (Тип)".If you want to be able to globally search for an article, and for support in a relational database, according to this embodiment of inheriting and substituting types, one possible implementation of storing articles in a database repository involves storing all the articles in one table with a column of type Base.Item. Using the type substitution, you can save articles of all types and you can filter searches by type and subtype of the article using the Yukon operator "is of ( Type )".

Однако благодаря вопросам, связанным со служебной нагрузкой, связанной с таким подходом, согласно данному варианту осуществления статьи делятся по типу верхнего уровня, например, статьи каждого «семейства» типов хранятся в отдельной таблице. Согласно этой схеме разделения таблица создается для каждого типа статьи, наследующего непосредственно от Base.Item. Типы, наследующие ниже их, хранятся в соответствующей таблице семейства типов с использованием подставимости типов, как описано выше. Только первый уровень наследования от Base.Item рассматривается особо. Для примера иерархии статьи, показанного на фиг.29, это дает следующие таблицы семейств типов:However, due to issues related to the workload associated with this approach, according to this embodiment, the articles are divided by the top-level type, for example, the articles of each “family” of types are stored in a separate table. According to this separation scheme, a table is created for each type of article that inherits directly from Base.Item. Types inheriting below them are stored in the corresponding table of the type family using type substitutions, as described above. Only the first level of inheritance from Base.Item is considered separately. For the example hierarchy of the article shown in FIG. 29, this gives the following type family tables:

create table Contact.[Table!Person] (create table Contact. [Table! Person] (

_Item Contact.Person not null,_Item Contact.Person not null,

{информация отслеживания изменений}{change tracking information}

))

create table Doc.[Table!Document] (create table Doc. [Table! Document] (

_Item Doc.Document not null,_Item Doc.Document not null,

{Информация отслеживания изменений}{Change Tracking Information}

))

«Теневая» таблица используется для хранения копий свойств, подлежащих глобальному поиску, для всех статей. Эта таблица может поддерживаться методом Update() API платформы хранения, посредством которого производятся все изменения данных. В отличие от таблиц семейств типов, эта глобальная таблица статей содержит только скалярные свойства верхнего уровня статьи, а не весь объект статьи UDT. Структура глобальной таблицы статей такова:The “shadow” table is used to store copies of properties subject to global search for all articles. This table can be supported by the Update () method of the storage platform API through which all data changes are made. Unlike type family tables, this global article table contains only scalar properties of the top-level article, and not the entire UDT article object. The structure of the global article table is as follows:

create table Base.[Table!Item] (create table Base. [Table! Item] (

ItemID uniqueidentifier not null constraintItemID uniqueidentifier not null constraint

[PK_Clu_Item!ItemID] primary key clustered,[PK_Clu_Item! ItemID] primary key clustered,

TypeID uniqueidentifier not null,TypeID uniqueidentifier not null,

{Дополнительные свойства Base.Item},{Additional properties of Base.Item},

{Информация отслеживания изменений}{Change Tracking Information}

))

Глобальная таблица статей допускает навигацию к объекту статьи, хранящемуся в таблице семейств типов, благодаря открытию ItemID и TypeID. ItemID, в общем случае, уникально идентифицирует статью в хранилище данных. TypeID можно отображать с использованием метаданных, которые здесь не описаны, в имя типа и вид, содержащий статью.The global article table allows navigation to the article object stored in the type family table by opening the ItemID and TypeID. ItemID, in general, uniquely identifies an article in a data warehouse. TypeID can be displayed using metadata, which are not described here, in the type name and view containing the article.

Поскольку отыскание статьи по ее ItemID может быть обычной операцией, как в контексте глобальной таблицы статей, так и в другом месте, обеспечивается функция GetItem() для извлечения объекта статьи по данному ItemID статьи. Эта функция имеет следующую декларацию:Since retrieving an article by its ItemID can be a normal operation, both in the context of the global table of articles and elsewhere, the GetItem () function is provided to retrieve the article object for this ItemID of the article. This function has the following declaration:

Base.Item Base.GetItem (uniqueidentifier ItemID)Base.Item Base.GetItem (uniqueidentifier ItemID)

Для удобства доступа и для сокрытия деталей реализации, насколько это возможно, все запросы статей должны быть относительно видов, построенных на вышеописанных таблицах статей. В частности, виды можно создавать для каждого типа статьи относительно соответствующей таблицы семейств типов. Эти виды типов могут выбирать все статьи соответствующего типа, включая подтипы. Для удобства, помимо объекта UDT, виды могут представлять столбцы для всех полей верхнего уровня этого типа, включая унаследованные поля. Виды для примера иерархии статьи, показанного на фиг.29, таковы:For ease of access and to conceal implementation details, as far as possible, all article requests should be relative to the views built on the above article tables. In particular, views can be created for each type of article relative to the corresponding table of type families. These types of types can select all articles of the corresponding type, including subtypes. For convenience, in addition to the UDT object, views can represent columns for all top-level fields of this type, including inherited fields. Views for an example of the hierarchy of the article shown in Fig.29, are as follows:

create view Contact.Person ascreate view Contact.Person as

select _Item.ItemID, {Свойства Base.Item},select _Item.ItemID, {Base.Item Properties},

{Свойства Contact.Person},{Contact.Person Properties},

{Информация отслеживания изменений}, _Item{Change Tracking Information}, _Item

from Contact.[Table!Person]from Contact. [Table! Person]

--Заметим, что вид Contact.Employee использует предикат- Note that the Contact.Employee view uses the predicate

-- "where" для ограничения множества найденных статей- "where" to limit the number of articles found

-- экземплярами Contact.Employee- instances of Contact.Employee

create view Contact.Employee ascreate view Contact.Employee as

select _Item.ItemID, {Свойства Base.Item},select _Item.ItemID, {Base.Item Properties},

{Свойства Contact.Person},{Contact.Person Properties},

{Свойства Contact.Employee},{Contact.Employee Properties},

{Информация отслеживания изменений},{Change Tracking Information},

cast (_Item as Contact.Employee)cast (_Item as Contact.Employee)

from Contact.[Table!Person]from Contact. [Table! Person]

where _Item is of (Contact.Employee)where _Item is of (Contact.Employee)

create view Doc.Document ascreate view Doc.Document as

select _Item.ItemID, {Свойства Base.Item},select _Item.ItemID, {Base.Item Properties},

{Свойства Doc.Document},{Doc.Document Properties},

{Информация отслеживания изменений}, _Item{Change Tracking Information}, _Item

from Doc.[Table!Document]from Doc. [Table! Document]

--Заметим, что вид Doc.WordDocument uses предикат "where"- Note that the view Doc.WordDocument uses the predicate "where"

-- для ограничения множества найденных статей экземплярами- to limit the set of articles found to be instances

-- Doc.WordDocument- Doc.WordDocument

create view Doc.WordDocument ascreate view Doc.WordDocument as

select _Item.ItemID, {Свойства Base.Item},select _Item.ItemID, {Base.Item Properties},

{Свойства Doc.Document},{Doc.Document Properties},

{Свойства Doc.WordDocument},{Doc.WordDocument Properties},

{Информация отслеживания изменений},{Change Tracking Information},

cast (_Item as Doc.WordDocument)cast (_Item as Doc.WordDocument)

from Doc.[Table!Document]from Doc. [Table! Document]

where _Item is of (Doc.WordDocument)where _Item is of (Doc.WordDocument)

Для полноты, вид также можно создавать по глобальной таблице статей. Этот вид первоначально открывает те же столбцы, что и таблица:For completeness, a view can also be created from the global table of articles. This view initially opens the same columns as the table:

create view Base.Item ascreate view Base.Item as

select ItemID, TypeID, {Свойства Base.Item},select ItemID, TypeID, {Base.Item Properties},

{Информация отслеживания изменений}{Change Tracking Information}

from Base.[Table!Item]from Base. [Table! Item]

3. Отображение расширений3. Display extensions

Расширения весьма сходны со статьями и подчиняются некоторым из тех же требований. В качестве другого корневого типа, поддерживающего наследование, расширения подлежат многим из тех же соображений и компромиссов в хранении. Вследствие этого к расширениям применяется аналогичное отображение семейств типов, вместо подхода единой таблицы. Конечно, в других вариантах осуществления, можно использовать подход единой таблицы.Extensions are very similar to articles and obey some of the same requirements. As another root type that supports inheritance, extensions are subject to many of the same considerations and trade-offs in storage. As a result, similar type mappings are applied to extensions, instead of a single table approach. Of course, in other embodiments, a single table approach can be used.

Согласно данному варианту осуществления расширение связано с точно одной статьей посредством ItemID и содержит ExtensionID, который является уникальным в контексте статьи. Таблица расширений имеет следующее определение:According to this embodiment, the extension is associated with exactly one article through an ItemID and contains an ExtensionID that is unique in the context of the article. The extension table has the following definition:

create table Base.[Table!Extension] (create table Base. [Table! Extension] (

ItemID uniqueidentifier not null,ItemID uniqueidentifier not null,

ExtensionID uniqueidentifier not null,ExtensionID uniqueidentifier not null,

TypeID uniqueidentifier not null,TypeID uniqueidentifier not null,

{Свойства Base.Extension},{Base.Extension Properties},

{Информация отслеживания изменений},{Change Tracking Information},

constraint [PK_Clu_Extension!ItemID!ExtensionID]constraint [PK_Clu_Extension! ItemID! ExtensionID]

primary key clustered (ItemID asc, ExtensionID asc)primary key clustered (ItemID asc, ExtensionID asc)

))

Как и для статей, может быть обеспечена функция для извлечения расширения по его идентификации, которая образована парой ItemID и ExtensionID. Эта функция имеет следующую декларацию:As with articles, a function can be provided to retrieve an extension by its identification, which is formed by a pair of ItemID and ExtensionID. This function has the following declaration:

Base.Extension Base.GetExtension(uniqueidentifier ItemID, uniqueidentifier ExtensionID)Base.Extension Base.GetExtension (uniqueidentifier ItemID, uniqueidentifier ExtensionID)

Для каждого типа расширения создается Вид, по аналогии с видами типов статьи. Пусть иерархия расширения параллельна примеру иерархии статьи, со следующими типами: Base.Extension, Contact.PersonExtension, Contact.EmployeeExtension. Можно создать следующие виды:For each type of extension, a View is created, similar to the types of article types. Let the extension hierarchy be parallel to the article hierarchy example, with the following types: Base.Extension, Contact.PersonExtension, Contact.EmployeeExtension. You can create the following views:

create view Base.Extension ascreate view Base.Extension as

select ItemID, ExtensionID, TypeID,select ItemID, ExtensionID, TypeID,

{Свойства Base.Extension},{Base.Extension Properties},

{Информация отслеживания изменений}{Change Tracking Information}

from Base.[Table!Extension]from Base. [Table! Extension]

create view Contact.[Extension!PersonExtension] ascreate view Contact. [Extension! PersonExtension] as

select _Extension.ItemID,select _Extension.ItemID,

_Extension.ExtensionID,_Extension.ExtensionID,

{Свойства Base.Extension},{Base.Extension Properties},

{Свойства Contact.Person Extension},{Contact.Person Extension Properties},

{Информация отслеживания изменений}, _Extension{Change Tracking Information}, _Extension

from Base.[Table!PersonExtension]from Base. [Table! PersonExtension]

create view Contact.[Extension!EmployeeExtension] ascreate view Contact. [Extension! EmployeeExtension] as

select _Extension.ItemID,select _Extension.ItemID,

_Extension.ExtensionID,_Extension.ExtensionID,

{Свойства Base.Extension},{Base.Extension Properties},

{Свойства Contact.PersonExtension},{Contact.PersonExtension Properties},

{Свойства Contact.EmployeeExtension},{Contact.EmployeeExtension Properties},

{Информация отслеживания изменений},{Change Tracking Information},

cast (_Extension as Contact.EmployeeExtension)cast (_Extension as Contact.EmployeeExtension)

from Base.[Table!PersonExtension]from Base. [Table! PersonExtension]

where _Extension is of (Contact.EmployeeExtension)where _Extension is of (Contact.EmployeeExtension)

4. Отображение вложенных элементов4. Display of nested elements

Вложенные элементы являются типами, которые могут быть внедрены в статьи, расширения, отношения или другие вложенные элементы для формирования глубоко вложенных структур. Наподобие статей и расширений, вложенные элементы реализуются как UDT, но они хранятся в статьях и расширениях. Поэтому вложенные элементы не имеют хранилища, отображающегося за пределы их контейнеров статей и расширений. Другими словами, в системе не существует таблиц, в которых непосредственно хранятся экземпляры типов вложенного элемента, не существует видов, относящихся конкретно к вложенным элементам.Nested elements are types that can be embedded in articles, extensions, relationships, or other nested elements to form deeply nested structures. Like articles and extensions, nested elements are implemented as UDTs, but they are stored in articles and extensions. Therefore, nested items do not have a repository that appears outside their article and extension containers. In other words, there are no tables in the system that directly store instances of types of a nested element, and there are no types specific to nested elements.

5. Идентификация объекта5. Object identification

Каждая сущность в модели данных, т.е. каждая(ое) статья, расширение и отношение, имеет уникальное ключевое значение. Статья уникально идентифицируется своим ItemId. Расширение уникально идентифицируется составным ключом (ItemId, ExtensionId). ItemId, ExtensionId и RelationshipId являются значениями типа GUID.Each entity in the data model, i.e. each article, extension and attitude, has a unique key value. An article is uniquely identified by its ItemId. An extension is uniquely identified by a compound key (ItemId, ExtensionId). ItemId, ExtensionId, and RelationshipId are GUID type values.

6. Именование объектов SQL6. Naming SQL objects

Все объекты, созданные в хранилище данных, могут сохраняться в имени схемы SQL, выведенной из имени схемы платформы хранения. Например, Базовая схема платформы хранения (часто именуемая "Base"), может порождать типы в схеме SQL "[System.Storage]", например, "[System.Storage].Item". Сгенерированные имена снабжены спецификатором в качестве префикса во избежание конфликтов именования. При необходимости восклицательный знак (!) используется в качестве разделителя для логической части имени. В нижеприведенной таблице описано соглашение именования, используемое для объектов в хранилище данных. Каждый элемент схемы (статья, расширение, отношение и вид) перечислен совместно с соглашением декорации именования, используемым для доступа к экземплярам в хранилище данных.All objects created in the data warehouse can be saved in the SQL schema name derived from the storage platform schema name. For example, the Base Storage Platform Schema (often referred to as "Base") can spawn types in the SQL schema "[System.Storage]", for example, "[System.Storage] .Item". Generated names are prefixed with a qualifier to avoid naming conflicts. If necessary, an exclamation mark (!) Is used as a separator for the logical part of the name. The table below describes the naming convention used for objects in the data warehouse. Each element of the schema (article, extension, relationship, and view) is listed in conjunction with the naming convention used to access instances in the data warehouse.

ОбъектAn object Декорация имениName decoration ОписаниеDescription ПримерExample Главный вид поиска статьиThe main type of article search Master!ItemMaster! Item Обеспечивает сводку статей в текущем домене статьи.Provides a summary of articles in the current article domain. [System.Storage].
[Master!Item]
[System.Storage].
[Master! Item]
Типизиро-ванный вид поиска статьи Typical type of article search Тип статьиType of article Обеспечивают все данные свойств из статьи и любых родительских типов.Provide all the property data from the article and any parent types. [AcmeCorp.Doc].
[OfficeDoc]
[AcmeCorp.Doc].
[OfficeDoc]
Главный вид поиска расширенияThe main type of extension search Master!ExtensionMaster! Extension Обеспечивает сводку всех расширений в текущем домене статьи.Provides a summary of all extensions in the current article domain. [System.Storage].
[Master!Extension]
[System.Storage].
[Master ! Extension]
Типизиро-ванный вид поиска расширенияA typed extension search type Extension!тип расширения Extension ! extension type Обеспечивает все данные свойств для расширения. Provides all property data for extension . [AcmeCorp.Doc].
[Extension!StickyNote]
[AcmeCorp.Doc].
[Extension ! StickyNote]
Главный вид отношенияThe main kind of relationship Master!Relationship Master ! Relationship Обеспечивает сводку всех отношений в текущем домене статьи.Provides a summary of all relationships in the current article domain. [System.Storage].
[Master!Relationship]
[System.Storage].
[Master ! Relationship]
Вид отношенияRelationship type Relationship!имя отношения Relationship ! relationship name Обеспечивает все данные, связанные с данным отношением.Provides all the data associated with this relationship. [AcmeCorp.Doc].
[Relationship!AuthorsFrom Document]
[AcmeCorp.Doc].
[Relationship ! AuthorsFrom Document]
ВидView View!имя вида View ! view name Обеспечивает столбцы/типы на основании определения вида схемы.Provides columns / types based on a schema view definition. [AcmeCorp.Doc].
[View!DocumentTitles]
[AcmeCorp.Doc].
[View! DocumentTitles]

7. Именование столбцов7. Naming columns

При отображении любой объектной модели в хранилище возникает возможность конфликтов именования вследствие дополнительной информации, хранящейся совместно с объектом приложения. Во избежание конфликтов именования все столбцы, не связанные с типом (столбцы, которые не отображаются непосредственно в именованное свойство при декларировании типов), снабжаются префиксом в виде знака подчеркивания (_). Согласно данному варианту осуществления знаки подчеркивания (_) не разрешены в качестве начального символа любого свойства идентификатора. Кроме того, для унификации именования между CLR и хранилищем данных, все свойства типов платформы хранения или элемента схемы (отношения и т.д.) должны иметь первый символ в виде заглавной буквы.When displaying any object model in the repository, the possibility of naming conflicts arises due to additional information stored in conjunction with the application object. To avoid naming conflicts, all non-type columns (columns that do not map directly to the named property when declaring types) are prefixed with an underscore (_). According to this embodiment, underscores (_) are not permitted as the initial character of any identifier property. In addition, to unify the naming between the CLR and the data warehouse, all properties of the types of the storage platform or schema element (relationships, etc.) must have the first capital letter.

8. Виды поиска8. Types of search

Виды обеспечиваются платформой хранения для поиска сохраненного контента. Вид SQL обеспечивается для каждого типа статьи и расширения. Кроме того, виды обеспечиваются для поддержки отношений и видов (заданных в Модели данных). Все виды SQL и нижележащие таблицы в платформе хранения предназначены только для чтения. Данные можно сохранять или изменять с использованием метода Update() API платформы хранения, что более подробно описано ниже.Views are provided by the storage platform to search for stored content. An SQL view is provided for each type of article and extension. In addition, views are provided to support relationships and views (defined in the Data Model). All kinds of SQL and underlying tables in the storage platform are read-only. Data can be saved or modified using the Update () method of the storage platform API, which is described in more detail below.

Каждый вид, заданный в явном виде в схеме платформы хранения (задается разработчиком схемы, а не автоматически генерируется платформой хранения) доступен по имени вида SQL [<имя схемы>].[View!<имя вида>]. Например, вид под названием "BookSales" в схеме "AcmePublisher.Books" будет доступен с использованием имени "[AcmePublisher.Books].[View!BookSales]". Поскольку выходной формат вида является регулируемым для каждого вида (задан произвольным запросом, обеспеченным стороной, задающей вид), столбцы непосредственно отображаются на основании определения вида схемы.Each view specified explicitly in the storage platform scheme (specified by the developer of the scheme and not automatically generated by the storage platform) is available by the name of the SQL type [<schema name>]. [View! <View name>]. For example, a view called "BookSales" in the "AcmePublisher.Books" schema will be available using the name "[AcmePublisher.Books]. [View! BookSales]". Since the output format of the view is adjustable for each view (defined by an arbitrary request provided by the party that sets the view), the columns are directly displayed based on the definition of the type of scheme.

Все виды поиска SQL в хранилище данных платформы хранения используют следующее соглашение по упорядочению для столбцов:All kinds of SQL searches in the storage platform data warehouse use the following collation for columns:

1. Логические «ключевые» столбцы результата вида, например, ItemId, ElementId, RelationshipId, … 1. Logical "key" columns of the result of the form, for example, ItemId, ElementId, RelationshipId, ...

2. Типизированная информация метаданных результата, например, TypeId. 2. Typed result metadata information, such as TypeId.

3. Столбцы отслеживания изменений, например, CreateVersion, UpdateVersion,... 3. Change tracking columns, for example, CreateVersion, UpdateVersion, ...

4. Столбцы, зависящие от типа (Свойства объявленного типа).4. Type-dependent columns (Properties of the declared type).

5. Виды, зависящие от типа (виды семейства) также содержат объектный столбец, который возвращает объект.5. Type-specific views (family views) also contain an object column that returns an object.

Члены каждого семейства типов можно искать с использованием ряда видов статьи, причем имеется один вид на тип статьи в хранилище данных.Members of each type family can be searched using a number of article types, and there is one type of article type in the data warehouse.

а) Статьяa) Article

Каждый вид поиска статьи содержит строку для каждого экземпляра статьи конкретного типа или его подтипов. Например, вид для типа Document может возвращать экземпляры Document, LegalDocument и ReviewDocument. Приведенные в этом примере виды Статьи можно осмыслить, как показано на фиг.28.Each type of article search contains a string for each article instance of a particular type or its subtypes. For example, a view for a Document type may return instances of Document, LegalDocument, and ReviewDocument. The types of Articles given in this example can be understood as shown in FIG. 28.

(1) Главный вид поиска статьи(1) The main type of article search

Каждый экземпляр хранилища данных платформы хранения задает особый вид статьи, именуемый главным видом статьи. Этот вид обеспечивает сводную информацию по каждой статье в хранилище данных. Вид обеспечивает один столбец на свойство типа статьи, столбец, который описывает тип статьи и несколько столбцов, которые используются для обеспечения информации отслеживания изменений и синхронизации. Главный вид статьи идентифицируется в хранилище данных с использованием имени "[System.Storage].[Master!Item]".Each instance of the storage platform data warehouse defines a specific type of article called the main type of article. This view provides summary information for each article in the data warehouse. The view provides one column per article type property, a column that describes the article type, and several columns that are used to provide change tracking and synchronization information. The main view of the article is identified in the data warehouse using the name "[System.Storage]. [Master! Item]".

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация платформы хранения статьиArticle Storage Platform Identification _TypeId_TypeId TypeIdTypeid TypeId статьи - идентифицирует точный тип статьи и может использоваться для извлечения информации о типе с использованием каталога метаданных.Article TypeId - Identifies the exact type of the article and can be used to retrieve type information using the metadata catalog. _RootItemId_RootItemId ItemIdItemId ItemId первого невнедренного предка, который управляет временем жизни этой статьи.The ItemId of the first non-embedded ancestor that controls the lifetime of this article. <глобальное отслеживание изменений><global change tracking> ... Глобальная информация отслеживания измененийGlobal Change Tracking Information <свойства статьи><article properties> н/пn / a Один столбец на свойство типа статьиOne column per article type property

(2) Типизированные виды поиска статьи(2) Typed Article Search Types

Каждый тип статьи также имеет вид поиска. Хотя этот вид аналогичен виду корневой статьи, он также обеспечивает доступ к объекту статьи посредством столбца "_Item". Каждый типизированный вид поиска статьи идентифицируется в хранилище данных с использованием имени [имя схемы].[имя типа статьи]. Например [AcmeCorp.Doc].[OfficeDoc].Each type of article also has the form of a search. Although this view is similar to the root article, it also provides access to the article object through the "_Item" column. Each typed type of article search is identified in the data warehouse using the name [ schema name ]. [ Article type name ]. For example [AcmeCorp.Doc]. [OfficeDoc].

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация платформы хранения статьиArticle Storage Platform Identification <отслеживание изменения типа><type change tracking> ... Информация отслеживания изменений типаType Change Tracking Information <родительские свойства><parent properties> <связан со свойством><associated with a property> Один столбец на родительское свойствоOne column per parent property <свойства статьи><article properties> <связан со свойством><associated with a property> Один столбец на исключительное свойство этого типаOne column per exceptional property of this type -Item - Item Тип CLR статьиCLR type of article Объект CLR - тип объявленной статьиCLR object - type of declared article

b) Расширения статьиb) Article extensions

Все расширения статьи в хранилище WinFS также доступны с использованием видов поиска.All article extensions in the WinFS repository are also available using search types.

(1) Главный вид поиска расширения(1) Main view of extension search

Каждый экземпляр хранилища данных задает особый вид расширения, именуемый главным видом расширения. Этот вид обеспечивает сводную информацию по каждому расширению в хранилище данных. Вид имеет столбец на свойство расширения, столбец, который описывает тип расширения и несколько столбцов, которые используются для обеспечения информации отслеживания изменений и синхронизации. Главный вид расширения идентифицируется в хранилище данных с использованием имени "[System.Storage].[Master!Extension]".Each instance of the data warehouse defines a specific type of extension, called the main type of extension. This view provides a summary of each extension in the data warehouse. The view has a column on the extension property, a column that describes the type of extension, and several columns that are used to provide change tracking and synchronization information. The main type of extension is identified in the data warehouse using the name "[System.Storage]. [Master! Extension]".

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация платформы хранения статьи, с которой связано это расширениеIdentification of the article storage platform this extension is associated with ExtensionIdExtensionId ExtensionId (GUID)ExtensionId (GUID) ИД этого экземпляра расширенияID of this extension instance _TypeId_TypeId TypeIdTypeid TypeId расширения - идентифицирует точный тип расширения и может использоваться для извлечения информации о расширении с использованием каталога метаданных.Extension TypeId - Identifies the exact type of extension and can be used to retrieve extension information using the metadata catalog. <глобальное отслеживание изменений><global change tracking> ... Глобальная информация отслеживания измененийGlobal Change Tracking Information <свойства расширения><extension properties> <зависит от свойства><depends on property> Один столбец на свойство типа расширения One column per extension type property

(2) Типизированные виды поиска расширения(2) Typed extension search types

Каждый тип расширения также имеет вид поиска. Хотя этот вид аналогичен главному виду расширения, он также обеспечивает доступ к объекту статьи посредством столбца _Extension. Каждый типизированный вид поиска расширения [имя схемы].[расширение!имя типа расширения]. Например [AcmeCorp.Doc].[Extension!OfficeDocExt].Each type of extension also has the form of a search. Although this view is similar to the main view of the extension, it also provides access to the article object through the _Extension column. Each typed type of extension search [ schema name ]. [ Extension ! extension type name ]. For example [AcmeCorp.Doc]. [Extension! OfficeDocExt].

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация платформы хранения статьи, с которой связано это расширениеIdentification of the article storage platform this extension is associated with ExtensionIdExtensionId ExtensionId (GUID)ExtensionId (GUID) ИД этого экземпляра расширенияID of this extension instance <отслеживание изменений типа><type change tracking> ... Информация отслеживания изменений типаType Change Tracking Information <родительские свойства><parent properties> <зависит от свойства><depends on property> Один столбец на родительское свойствоOne column per parent property <свойства расширений><extension properties> <зависит от свойства><depends on property> Один столбец на исключительное свойство этого типаOne column per exceptional property of this type _Extension _ Extension Тип CLR экземпляра расширенияExtension Instance CLR Type Объект CLR - тип объявленного расширенияCLR object - type of extension declared

c) Вложенные элементыc) Nested elements

Все вложенные элементы хранятся в экземплярах статей, расширений или отношений. Поэтому доступ к ним осуществляется путем запроса соответствующего вида поиска статьи, расширения или отношения.All nested items are stored in copies of articles, extensions, or relationships. Therefore, access to them is carried out by requesting the appropriate type of article search, extension or relationship.

d) Отношенияd) Relationships

Согласно рассмотренному выше, отношения образуют основную единицу связи между статьями в хранилище данных платформы хранения.According to the above, relations form the basic unit of communication between articles in the data warehouse of the storage platform.

(1) Главный вид поиска отношения(1) The main type of relationship search

Каждое хранилище данных обеспечивает главный вид отношения. Этот вид обеспечивает информацию обо всех экземплярах отношения в хранилище данных. Главный вид отношения идентифицируется в хранилище данных с использованием имени "[System.Storage].[Master!Relationship]".Each data warehouse provides the main kind of relationship. This view provides information about all instances of the relationship in the data warehouse. The main relationship type is identified in the data warehouse using the name "[System.Storage]. [Master! Relationship]".

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация исходной концевой точки (ItemId)Source Endpoint Identification (ItemId) RelationshipIdRelationshipId RelationshipId (GUID)RelationshipId (GUID) ИД экземпляра отношенияRelationship instance id _RelTypeId_RelTypeId RelationshipTypeIdRelationshipTypeId RelTypeId отношения - идентифицирует тип экземпляра отношения с использованием каталога метаданных.RelTypeId relationships — Identifies the instance type of the relationship using the metadata catalog. <глобальное отслеживание изменений><global change tracking> ...... Глобальная информация отслеживания изменений.Global change tracking information. TargetItemReferenceTargetItemReference ItemReferenceItemReference Идентификация целевой концевой точкиTarget Endpoint Identification _Relationship_Relationship RelationshipRelationship Экземпляр объекта отношения для этого экземпляраAn instance of the relationship object for this instance.

(2) Виды поиска экземпляра отношения(2) Types of relationship instance search

Каждое объявленное отношение также имеет вид поиска, который возвращает все экземпляры конкретного отношения. Хотя этот вид аналогичен главному виду отношения, он также обеспечивает именованные столбцы для каждого свойства данных отношения. Каждый экземпляр отношения вида поиска идентифицируется в хранилище данных с использованием имени [имя схемы].[Relationship!имя отношения]. Например, [AcmeCoip.Doc].[Relationship!DocumentAuthor].Each declared relation also has the form of a search, which returns all instances of a particular relation. Although this view is similar to the main view of a relationship, it also provides named columns for each property of the relationship data. Each instance of the relationship of the search type is identified in the data warehouse using the name [ schema name ]. [Relationship ! relationship name ]. For example, [AcmeCoip.Doc]. [Relationship! DocumentAuthor].

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация исходной концевой точки (ItemId)Source Endpoint Identification (ItemId) RelationshipIdRelationshipId RelationshipId (GUID)RelationshipId (GUID) ИД экземпляра отношенияRelationship instance id <отслеживание изменений типа><type change tracking> ...... Информация отслеживания изменений типаType Change Tracking Information TargetItemReferenceTargetItemReference ItemReferenceItemReference Идентификация целевой концевой точкиTarget Endpoint Identification <имя источника><source name> ItemIdItemId Именованное свойство идентификации исходной концевой точки (псевдоним для ItemId)Named origin endpoint identification property (alias for ItemId) <имя цели><target name> ItemReference или производный классItemReference or derived class Именованное свойство идентификации целевой концевой точки (псевдоним и приведение для TargetItemReference)Named target endpoint identification property (alias and cast for TargetItemReference) <свойство отношения><relationship property> <зависит от свойства><depends on property> Один столбец на свойство определения отношенияOne column per relation definition property _Relationship_Relationship Тип CLR экземпляра отношенияRelationship Instance CLR Type Объект CLR - тип объявленного отношенияCLR Object - Declared Relationship Type

9. Обновления9. Updates

Все виды в хранилище данных платформы хранения предназначены только для чтения. Для создания нового экземпляра элемента модели данных (статьи, расширения или отношения) или для обновления существующего экземпляра нужно использовать методы ProcessOperation или ProcessUpdategram API платформы хранения. Метод ProcessOperation является единственной сохраненной процедурой, заданной хранилищем данных, которая потребляет «операцию», которая детализирует действие, подлежащее выполнению. Метод ProcessUpdategram является сохраненной процедурой, которая принимает упорядоченное множество операций, именуемое «апдейтграммой», которое коллективно детализирует множество действий, подлежащих выполнению.All views in the data warehouse storage platform are read-only. To create a new instance of a data model element (article, extension, or relationship) or to update an existing instance, you must use the ProcessOperation or ProcessUpdategram API of the storage platform. The ProcessOperation method is the only stored procedure specified by the data store that consumes an “operation” that details the action to be performed. The ProcessUpdategram method is a stored procedure that accepts an ordered set of operations called an “updategram” that collectively details the set of actions to be performed.

Формат операции является расширяемым и обеспечивает различные операции над элементами схемы. Некоторые общие операции включают в себяThe operation format is extensible and provides various operations on circuit elements. Some common operations include

1. Операции над статьями:1. Operations on articles:

а. CreateItem (создает новую статью в контексте внедрения или отношения поддержки),but. CreateItem (creates a new article in the context of an implementation or support relationship)

b. UpdateItem (обновляет существующую статью),b. UpdateItem (updates an existing article)

2. Операции над отношениями:2. Relationship operations:

а. CreateRelationship (создает экземпляр отношения ссылки или поддержки),but. CreateRelationship (creates an instance of a link or support relationship)

b. UpdateRelationship (обновляет экземпляр отношения),b. UpdateRelationship (updates the relationship instance)

с. DeleteRelationship (удаляет экземпляры отношения),from. DeleteRelationship (deletes relationship instances)

3. Операции над расширениями,3. Operations on extensions,

а. CreateExtension (добавляет расширение к существующей статье),but. CreateExtension (adds an extension to an existing article)

b. UpdateExtension (обновляет существующее расширение),b. UpdateExtension (updates an existing extension)

с. DeleteExtension (удаляет расширение),from. DeleteExtension (removes the extension)

10. Отслеживание изменений и надгробия10. Track changes and gravestones

Услуги отслеживания изменений и надгробий обеспечены хранилищем данных, что более подробно рассмотрено ниже. Этот раздел обеспечивает обзор информации отслеживания изменений, открытой в хранилище данных.Change tracking and gravestone services are provided with a data warehouse, which is discussed in more detail below. This section provides an overview of the change tracking information that is open in the data warehouse.

а) Отслеживание измененийa) Change tracking

Каждый вид поиска, обеспеченный хранилищем данных, содержит столбцы, используемые для обеспечения информации отслеживания изменений; столбцы являются общими по всем видам статьи, расширения и отношения. Виды схемы платформы хранения, заданные в явном виде разработчиками схем, не обеспечивают автоматически информацию отслеживания изменений - такая информация обеспечивается косвенно через виды поиска, на которых построен сам вид.Each type of search provided by the data warehouse contains columns used to provide change tracking information; columns are common across all kinds of articles, extensions, and relationships. Types of storage platform schemas that are explicitly set by schema developers do not automatically provide change tracking information — such information is provided indirectly through the search types on which the view itself is built.

Для каждого элемента в хранилище данных информация отслеживания изменений доступна из двух мест - «главного» вида элемента и «типизированного» вида элемента. Например, информация отслеживания изменений на типе статьи AcmeCorp.Document.Document доступна из главного вида статьи "[System.Storage].[Master!Item]" и типизированного вида поиска статьи [AcmeCorp.Document].[Document].For each item in the data warehouse, change tracking information is available from two places - the “main” view of the item and the “typed” view of the item. For example, change tracking information on an AcmeCorp.Document.Document article type is available from the main article type [System.Storage]. [Master! Item] and the typed article search type [AcmeCorp.Document]. [Document].

(1) Отслеживание изменений в «главных» видах поиска(1) Track changes in the “main” types of searches

Информация отслеживания изменений в главных видах поиска обеспечивает информацию по созданию и обновлению версий элемента, информацию о том, какой партнер синхронизации создал элемент, какой партнер синхронизации последним обновил элемент и номера версий от каждого партнера для создания и обновления. Партнеры в отношениях синхронизации (описаны ниже) идентифицируются ключом партнера. Единичный объект UDT под названием _ChangeTrackingInfo типа [System.Storage.Store].ChangeTrackingInfo содержит всю эту информацию. Тип задан в схеме System.Storage. _ChangeTrackingInfo доступен во всех глобальных видах поиска для статьи, расширения и отношения. Определение типа для ChangeTrackingInfo таково:Information tracking changes in the main types of searches provides information on creating and updating versions of an element, information about which synchronization partner created the element, which synchronization partner last updated the element and version numbers from each partner to create and update. Partners in a synchronization relationship (described below) are identified by the partner key. A single UDT object called _ChangeTrackingInfo of type [System.Storage.Store] .ChangeTrackingInfo contains all this information. The type is specified in the System.Storage schema. _ChangeTrackingInfo is available in all global search types for article, extension and relationship. The type definition for ChangeTrackingInfo is as follows:

<Type Name="ChangeTrackingInfo" BaseType="Base.NestedElement"><Type Name = "ChangeTrackingInfo" BaseType = "Base.NestedElement">

<FieldProperty Name="CreationLocalTS"<FieldProperty Name = "CreationLocalTS"

Type="SqlTypes.SqlInt64"Type = "SqlTypes.SqlInt64"

Nullable="False"/>Nullable = "False" />

<FieldProperty Name="CreatingPartnerKey"<FieldProperty Name = "CreatingPartnerKey"

Type="SqlTypes.SqlInt32" Nullable="False"/>Type = "SqlTypes.SqlInt32" Nullable = "False" />

<FieldProperty Name="CreatingPartnerTS"<FieldProperty Name = "CreatingPartnerTS"

Type="SqlTypes.SqlInt64" Nullable="False"/>Type = "SqlTypes.SqlInt64" Nullable = "False" />

<FieldProperty Name="LastUpdateLocalTS"<FieldProperty Name = "LastUpdateLocalTS"

Type="SqlTypes.SqlInt64" Nullable="False"/>Type = "SqlTypes.SqlInt64" Nullable = "False" />

<FieldProperty Name="LastUpdatingPartnerKey"<FieldProperty Name = "LastUpdatingPartnerKey"

Type="SqlTypes.SqlInt32" Nullable="False"/>Type = "SqlTypes.SqlInt32" Nullable = "False" />

<FieldProperty Name="LastUpdatingPartnerTS"<FieldProperty Name = "LastUpdatingPartnerTS"

Type="SqlTypes.Sqllnt64"Type = "SqlTypes.Sqllnt64"

Nullable="False"/>Nullable = "False" />

</Type></Type>

Эти свойства содержат следующую информацию:These properties contain the following information:

СтолбецColumn ОписаниеDescription _CreationLocalTS_CreationLocalTS Создание метки времени локальной машинойCreating a Timestamp by a Local Machine _CreatingPartnerKey_CreatingPartnerKey PartnerKey партнера, создавшего эту сущность. Если сущность создана локально, это PartnerKey локальной машины.PartnerKey is the partner who created this entity. If the entity is created locally, this is the PartnerKey of the local machine. _CreatingPartnerTS_CreatingPartnerTS Метка времени, соответствующая времени создания этой сущности на партнере, соответствующем _CreatingPartnerKey.The timestamp corresponding to the time this entity was created on the partner matching _CreatingPartnerKey. _LastUpdateLocalTS_LastUpdateLocalTS Локальная метка времени, соответствующая времени обновления на локальной машине.Local timestamp corresponding to the update time on the local machine. _LastUpdatingPartnerKey_LastUpdatingPartnerKey PartnerKey партнера, который последним обновил эту сущность. Если последнее обновление этой сущности произведено локально, это PartnerKey локальной машины.PartnerKey is the partner who last updated this entity. If the last update of this entity was done locally, this is the PartnerKey of the local machine. _LastUpdatingPartnerTS_LastUpdatingPartnerTS Метка времени, соответствующая времени обновления этой сущности на партнере, соответствующем _LastUpdatingPartnerKey.The timestamp corresponding to the update time of this entity on the partner matching _LastUpdatingPartnerKey.

(2) Отслеживание изменений в «типизированных» видах поиска(2) Tracking changes in typed search types

Помимо обеспечения той же информации, что и глобальный вид поиска, каждый типизированный вид поиска обеспечивает дополнительную информацию, записывающую состояние синхронизации каждого элемента в топологии синхронизации.In addition to providing the same information as the global search view, each typed search view provides additional information that records the synchronization state of each element in the synchronization topology.

СтолбецColumn ТипType of ОписаниеDescription <глобальное отслеживание изменений><global change tracking> ...... Информация о глобальном отслеживании измененийGlobal Change Tracking Information _ChangeUnitVersions_ChangeUnitVersions MultiSet<ChangeUnitVersion>MultiSet <ChangeUnitVersion> Описание номеров версий блоков изменения в конкретном элементеDescription of version numbers of change blocks in a specific element _ElementSyncMetadata_ElementSyncMetadata ElementSyncMetadataElementSyncMetadata Дополнительные независимые от версии метаданные об этой статье, которые единственно представляют интерес для среды выполнения синхронизации.Additional version-independent metadata about this article that is only of interest to the synchronization runtime. _VersionSyncMetadata_VersionSyncMetadata VersionSyncMetadataVersionSyncMetadata Дополнительные независимые от версии метаданные об этой версии, которые единственно представляют интерес для среды выполнения синхронизации.Additional version-independent metadata about this version that is solely of interest to the synchronization runtime.

b) Надгробияb) Tombstones

Хранилище данных обеспечивает информацию надгробий для статей, расширений и отношений. Виды надгробий обеспечивают информацию как о живых, так и о захороненных сущностях (статьях, расширениях и отношениях) в одном месте. Виды надгробий статьи и расширения не обеспечивают доступ к соответствующему объекту, тогда как вид надгробия отношения обеспечивает доступ к объекту отношения (объект отношения равен NULL в случае захороненного отношения).The data warehouse provides tombstone information for articles, extensions, and relationships. Types of gravestones provide information about both living and buried entities (articles, extensions and relationships) in one place. The tombstone types of the article and the extension do not provide access to the corresponding object, while the tombstone type of the relationship provides access to the relationship object (the relationship object is NULL in the case of a buried relationship).

(1) Надгробия статей(1) Tombstones articles

Надгробия статей извлекаются из системы посредством вида [System.Storage].[Tombstone!Item].Tombstones of articles are retrieved from the system using the [System.Storage]. [Tombstone! Item] view.

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация статьиArticle Identification _ТуреID_TureID TypeIdTypeid Тип статьиType of article <Свойства статей><Article Properties> ... Свойства, заданные для всех статейProperties set for all articles _RootItemId_RootItemId ItemIdItemId ItemId первой невнедренной статьи, которая содержит эту статью.ItemId of the first non-embedded article that contains this article. _ChangeTrackingInfo_ChangeTrackingInfo Экземпляр CLR типа ChangeTrackingInfoCLR instance of type ChangeTrackingInfo Информация отслеживания изменений для этой статьи.Change tracking information for this article. _IsDeleted_IsDeleted BITBit Это флаг, который равен 0 для живых статей и 1 для захороненных статей.This is a flag that is 0 for live articles and 1 for buried articles. _DeletionWallclock_DeletionWallclock UTCDATETIMEUtcatetime Дата и время настенных часов UTC, соответствующие партнеру, который удалил статью. Равен NULL, если статья живая.The UTC wall clock date and time corresponding to the partner who deleted the article. Equals NULL if the article is live.

(2) Надгробия расширений(2) Gravestone extensions

Надгробия расширений извлекаются из системы с использованием вида [System.Storage].[Tombstone!Extension]. Информация отслеживания изменений расширений аналогична обеспечиваемой для статей с дополнением свойства ExtensionId.Tombstones of extensions are extracted from the system using the form [System.Storage]. [Tombstone! Extension]. Extension change tracking information is similar to that provided for articles with the ExtensionId property extension.

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация статьи, которой принадлежит расширениеIdentification of the article to which the extension belongs ExtensionIdExtensionId ExtensionIdExtensionId ИД расширения для расширенияExtension ID for extension _ТуреID_TureID TypeIdTypeid Тип расширенияExtension type _ChangeTrackingInfo_ChangeTrackingInfo Экземпляр CLR типа ChangeTrackingInfoCLR instance of type ChangeTrackingInfo Информация отслеживания изменений для этого расширенияChange tracking information for this extension _IsDeleted_IsDeleted BITBit Это флаг, который равен 0 для живых статей, и 1 для захороненных расширений.This is a flag that is 0 for live articles, and 1 for buried extensions. _DeletionWallclock_DeletionWallclock UTCDATETIMEUtcatetime Дата и время настенных часов UTC, соответствующие партнеру, который удалил расширение. Равен NULL, если расширение живое.The UTC wall clock date and time corresponding to the partner who uninstalled the extension. Equals NULL if the extension is live.

(3) Надгробия отношений(3) Tombstones of a relationship

Надгробия отношений извлекаются из системы посредством вида [System.Storage].[Tombstone!Relationship]. Информация надгробий отношений аналогична обеспечиваемой для расширений. Однако обеспечивается дополнительная информация о ItemRef цели экземпляра отношения. Кроме того, выбирается объект отношения.Tombstones of relationships are retrieved from the system using the [System.Storage]. [Tombstone! Relationship] view. Tombstone relationship information is similar to that provided for extensions. However, additional information is provided about the ItemRef of the relationship instance target. In addition, a relationship object is selected.

СтолбецColumn ТипType of ОписаниеDescription ItemIdItemId ItemIdItemId Идентификация статьи, которая владела отношением (идентификация исходной концевой точки отношения)Identification of the article that owned the relationship (identification of the source endpoint of the relationship) RelationshipIdRelationshipId RelationshipIdRelationshipId ИД отношения для отношенияRelationship id for relationship _TypeID_TypeID TypeIdTypeid Тип отношенияRelationship type _ChangeTrackingInfo_ChangeTrackingInfo Экземпляр CLR типа ChangeTrackingInfoCLR instance of type ChangeTrackingInfo Информация отслеживания изменений для этого отношенияChange tracking information for this relationship _IsDeleted_IsDeleted BITBit Это флаг, который равен 0 для живых статей, и 1 для захороненных расширений.This is a flag that is 0 for live articles, and 1 for buried extensions. _DeletionWallclock_DeletionWallclock UTCDATETIMEUtcatetime Дата и время настенных часов UTC, соответствующие партнеру, который удалил отношение. Равен NULL, если отношение живое.The UTC wall clock date and time corresponding to the partner who deleted the relationship. Equals NULL if the relation is live. _Relationship_Relationship Экземпляр CLR для отношенияCLR instance for relationship Это объект отношения для живого отношения. Равен NULL для захороненных отношений.It is a relationship object for a living relationship. Equals NULL for buried relationships. TargetItemReferenceTargetItemReference ItemReferenceItemReference Идентификация целевой концевой точкиTarget Endpoint Identification

(4) Очистка надгробий(4) Tombstone Cleaning

Во избежание неограниченного роста информации надгробий хранилище данных обеспечивает задание очистки надгробий. Это задание определяет, когда можно отбросить информацию надгробий. Задание вычисляет границу на локальном создании/обновлении версии, после урезает информацию надгробий, отбрасывая все более ранние версии надгробия.To avoid unlimited growth of tombstone information, the data warehouse provides the task of cleaning tombstones. This task determines when tombstone information can be discarded. The task calculates the boundary on the local version creation / update, then truncates the tombstone information, discarding all earlier versions of the tombstone.

11. API и функции помощника11. API and helper functions

Базовое отображение также обеспечивает ряд функций помощника. Эти функции обеспечены в помощь обычным операциям на модели данных.Basic mapping also provides a number of helper functions. These functions are provided to aid the usual operations on the data model.

а) Функция [System.Storage].GetItema) Function [System.Storage] .GetItem

//Возвращает объект статьи, заданный ItemId// Returns the article object specified by ItemId

////

Item GetItem (ItemId ItemId)Item GetItem (ItemId ItemId)

b) Функция [System.Storage].GetExtensionb) Function [System.Storage] .GetExtension

//Возвращает объект расширения, заданный ItemId и// Returns the extension object specified by ItemId and

//ExtensionId// ExtensionId

////

Extension GetExtension (ItemId ItemId, ExtensionId ExtensionId)Extension GetExtension (ItemId ItemId, ExtensionId ExtensionId)

с) Функция [System.Storage].GetRelationshipc) Function [System.Storage] .GetRelationship

// Возвращает объект отношения, заданный ItemId и// Returns the relationship object specified by ItemId and

// RelationshipId// RelationshipId

////

Relationship GetRelationship (ItemId ItemId, RelationshipId RelationshipId)Relationship GetRelationship (ItemId ItemId, RelationshipId RelationshipId)

12. Метаданные12. Metadata

Существует два типа метаданных, представленных в хранилище: метаданные экземпляра (тип статьи и т.д.) и метаданные типа.There are two types of metadata presented in the repository: instance metadata (article type, etc.) and type metadata.

а) Метаданные схемыa) Schema metadata

Метаданные схемы хранятся в хранилище данных как экземпляры типов статьи из метасхемы.Schema metadata is stored in the data warehouse as instances of article types from the metascheme.

b) Метаданные экземпляраb) Instance metadata

Метаданные экземпляра используются приложением для запроса типа статьи и находят расширения, связанные со статьей. На основании ItemId для статьи, приложение может запрашивать глобальный вид статьи для возвращения типа статьи и использовать это значение для запроса вида Meta.Type для возвращения информации об объявленном типе статьи. Например,Instance metadata is used by the application to query the type of article and find the extensions associated with the article. Based on the ItemId for the article, the application can query the global type of the article to return the type of the article and use this value to query the type Meta.Type to return information about the declared type of the article. For example,

// Возвращает метаданные объекта статьи для данного// Returns the metadata of the article object for this

// экземпляра статьи// article instance

SELECT m._Item AS metadataInfoObjSELECT m._Item AS metadataInfoObj

FROM [System.Storage].[Item] i INNER JOIN [Meta].[Type] mFROM [System.Storage]. [Item] i INNER JOIN [Meta]. [Type] m

ON i._TypeId = m.ItemIdON i._TypeId = m.ItemId

WHERE i.ItemId = @ItemIdWHERE i.ItemId = @ItemId

Е. БезопасностьE. Security

В этом разделе описана модель безопасности для платформы хранения настоящего изобретения согласно одному варианту осуществления.This section describes the security model for the storage platform of the present invention according to one embodiment.

1. Обзор1. Overview

Согласно данному варианту осуществления степень фрагментарности, с которой задается и применяется политика безопасности платформы хранения, соответствует уровню различных операций на статье в данном хранилище данных; невозможно обеспечить безопасность частей статьи отдельно от целого. Модель безопасности задет множество принципалов, которым может быть разрешен или запрещен доступ для осуществления этих операций на статье посредством Списков управления доступом (ACL). Каждый ACL является упорядоченной коллекцией записей управления доступом (ACE).According to this embodiment, the degree of fragmentation with which the security policy of the storage platform is defined and applied corresponds to the level of various operations on an article in this data warehouse; it is impossible to ensure the security of parts of the article separately from the whole. The security model affects many principals who can be allowed or denied access to perform these operations on an article through Access Control Lists (ACLs). Each ACL is an ordered collection of access control entries (ACEs).

Политику безопасности для статьи можно полностью описать посредством дискреционной политики управления доступом и системной политики управления доступом. Каждая из них является множеством ACL. Первое множество (DACL) описывает дискреционный доступ, предоставленный различным принципалам владельцем статьи, тогда как второе множество ACL называют SACL (системными списками управления доступом), которые задают, как осуществляется системный аудит, когда объектом манипулируют определенными способами. Кроме того, каждая статья в хранилище данных связана с SID, который соответствует владельцу статьи (SID владельца).The security policy for the article can be fully described through a discretionary access control policy and a system access control policy. Each of them is a set of ACLs. The first set (DACL) describes the discretionary access granted to various principals by the owner of the article, while the second set of ACLs are called SACLs (system access control lists) that specify how system auditing is performed when an object is manipulated in certain ways. In addition, each article in the data warehouse is associated with a SID that corresponds to the owner of the article (owner SID).

Основной механизм для организации статей в хранилище данных платформы хранения - это механизм иерархии включения. Иерархия включения реализуется с использованием отношений поддержки между статьями. Отношение поддержки между двумя статьями А и В, выраженное как «А содержит В», позволяет статье А влиять на время жизни статьи В. В общем случае, статья в хранилище данных не может существовать, пока существует отношение поддержки от другой статьи к ней. Отношение поддержки, помимо того, что управляет временем жизни статьи, обеспечивает необходимый механизм для распространения политики безопасности для статьи.The main mechanism for organizing articles in the storage platform data warehouse is the inclusion hierarchy mechanism. The inclusion hierarchy is implemented using support relationships between articles. The support relationship between two articles A and B, expressed as “A contains B”, allows article A to influence the life time of article B. In general, an article in the data warehouse cannot exist as long as there is a support relationship from another article to it. A support relationship, in addition to managing the life time of an article, provides the necessary mechanism for distributing security policies for an article.

Политика безопасности, заданная для каждой статьи, состоит из двух частей - части, которая в явном виде задана для этой статьи, и части, которая унаследована от родителя статьи в хранилище данных. Явно заданная политика безопасности для любой статьи состоит из двух частей - части, которая управляет доступом к рассматриваемой статье, и части, которая влияет на политику безопасности, унаследованную всеми ее потомками в иерархии включения. Политика безопасности, унаследованная потомком, является функцией явно заданной политики и унаследованной политики.The security policy set for each article consists of two parts - the part that is explicitly set for this article, and the part that is inherited from the article’s parent in the data warehouse. An explicitly defined security policy for any article consists of two parts - the part that controls access to the article in question, and the part that affects the security policy inherited by all its descendants in the inclusion hierarchy. The security policy inherited by the descendant is a function of the explicit policy and the inherited policy.

Поскольку политика безопасности распространяется через отношения поддержки и также может подменяться на любой статье, необходимо указывать, как определена эффективная политика безопасности для статьи. Согласно данному варианту осуществления статья в иерархии включения хранилища данных наследует ACL вдоль каждого пути от корня хранилища до статьи.Since the security policy is distributed through a support relationship and can also be substituted for any article, it is necessary to indicate how an effective security policy is defined for the article. According to this embodiment, the entry in the data warehouse enable hierarchy inherits ACLs along each path from the root of the store to the entry.

В унаследованном ACL для любого данного пути упорядочение различных ACE в ACL определяет окончательную политику безопасности, которая применяется. Для описания упорядочения ACE в ACL используется следующая система обозначений. Упорядочение ACE в ACL, который унаследован статьей, определяется следующими двумя правилами.In a legacy ACL for any given path, ordering the various ACEs in the ACL determines the final security policy that applies. The following notation is used to describe ACE ordering in the ACL. The ordering of an ACE in an ACL that is inherited by an article is determined by the following two rules.

Первое правило наслаивает ACE, унаследованные от различных статей на пути к статье I от корня иерархии включения. ACE, унаследованные от более близкого контейнера, получают преимущество над записями, унаследованными от удаленного контейнера. С интуитивной точки зрения это позволяет администратору подменять ACE, унаследованные от более удаленных в иерархии включения. Правило таково:The first rule layers ACEs inherited from various articles on the way to article I from the root of the inclusion hierarchy. ACEs inherited from a closer container take precedence over records inherited from a remote container. From an intuitive point of view, this allows the administrator to replace ACEs inherited from those that are more remote in the inclusion hierarchy. The rule is this:

Для всех унаследованных ACL L на статье IFor all inherited ACL Ls in Article I

Для всех статей I1, I2For all articles I1, I2

Для всех ACE A1 и A2 в L,For all ACE A1 and A2 in L,

I1 является предком I2, иI1 is the ancestor of I2, and

I2 является предком I3, иI2 is the ancestor of I3, and

A1 является ACE, унаследованной от I1, иA1 is an ACE inherited from I1, and

A2 является ACE, унаследованной от I2A2 is an ACE inherited from I2

ВлечетAttracts

А2 предшествует А1 в L.A2 precedes A1 in L.

Второе правило устанавливает положение ACE, которые отказывают в доступе к статье, впереди ACE, которые предоставляют доступ к статье.The second rule establishes the position of ACEs that deny access to an article, ahead of ACEs that provide access to an article.

Для всех унаследованных ACL L на статье IFor all inherited ACL Ls in Article I

Для всех статей I1For all articles I1

Для всех ACE A1 и A2 в L,For all ACE A1 and A2 in L,

I1 является предком I2, иI1 is the ancestor of I2, and

A1 является ACCESS_DENIED_ACE, унаследованной от I1, иA1 is ACCESS_DENIED_ACE inherited from I1, and

A2 является ACCESS_GRANTED_ACE унаследованной от I1A2 is ACCESS_GRANTED_ACE inherited from I1

ВлечетAttracts

А1 предшествует А2 в L.A1 precedes A2 in L.

В случае, когда иерархия включения является деревом, имеется в точности один путь от корня дерева к статье, и статья имеет в точности один унаследованный ACL. В этих обстоятельствах ACL, унаследованный статьей, совпадает с ACL, унаследованный файлом (статьей) в существующей модели безопасности Windows в терминах относительного упорядочения ACE в них.In the case where the inclusion hierarchy is a tree, there is exactly one path from the root of the tree to the article, and the article has exactly one inherited ACL. In these circumstances, the ACL inherited by the article is the same as the ACL inherited by the file (s) in the existing Windows security model in terms of relative ordering of the ACEs in them.

Однако иерархия включения в хранилище данных является ориентированным ациклическим графом (DAG), поскольку множественные отношения поддержки разрешены для статей. В этих условиях существует несколько путей к статье от корня иерархии включения. Поскольку статья наследует ACL вдоль каждого пути, она связана с коллекцией ACL, а не с одним из них. Заметим, что в этом состоит отличие от традиционной модели файловой системы, где с файлом или папкой связан в точности один ACL.However, the inclusion hierarchy in the data warehouse is a directed acyclic graph (DAG), since multiple support relationships are allowed for articles. Under these conditions, there are several paths to the article from the root of the inclusion hierarchy. Because the article inherits ACLs along each path, it is associated with a collection of ACLs, not one of them. Note that this is different from the traditional file system model, where exactly one ACL is associated with a file or folder.

Существуют два аспекта, которые нужно рассмотреть, когда иерархия включения является DAG, а не деревом. Необходимо описание, как вычисляется эффективная политика безопасности для статьи, когда она наследует более одного ACL от своих родителей, и их организация и представление имеет прямое отношение к администрированию модели безопасности для хранилища данных платформы хранения.There are two aspects to consider when the inclusion hierarchy is a DAG, not a tree. A description is needed of how an effective security policy is computed for an article when it inherits more than one ACL from its parents, and their organization and presentation is directly related to the administration of the security model for the storage platform data warehouse.

Следующий алгоритм оценивает права доступа данного принципала к данной статье. На протяжении этого документа для описания ACL, связанных со статьей, используется следующая система обозначений.The following algorithm evaluates the access rights of a given principal to this article. Throughout this document, the following notation is used to describe the ACLs associated with the article.

Inherited_ACLs(ItemId) - множество ACL, унаследованных статьей, идентифицированных посредством ItemId, от своих родителей в хранилище.Inherited_ACLs (ItemId) - the set of ACLs inherited by the article identified by ItemId from their parents in the repository.

Explicit_ACL(ItemId) - ACL, явно заданный для статьи, идентифицированной посредством ItemId.Explicit_ACL (ItemId) - An ACL explicitly set for an article identified by ItemId.

NTSTATUSNTSTATUS

ACLAccessCheck(ACLAccessCheck (

PSIDPSID pOwnerSid,pOwnerSid, PDACLPDACL pDacl,pDacl, DWORDDWORD DesiredAccess,DesiredAccess, HANDLEHandle ClientToken,ClientToken PPRIVILEGE_SETPPRIVILEGE_SET pPrivilegeSet,pPrivilegeSet, DWORDDWORD *pGrantedAccess)* pGrantedAccess)

Вышеописанная процедура возвращает STATUS_SUCCESS, если запрошенный доступ не был явно отклонен, и pGrantedAccess определяет, какие из прав, запрошенных пользователем, были предоставлены указанным ACL. Если какой-либо из запросов доступа был явно отклонен, процедура возвращает STATUS_ACCESS_DENIED.The above procedure returns STATUS_SUCCESS if the requested access was not explicitly denied, and pGrantedAccess determines which of the rights requested by the user were granted by the specified ACL. If any of the access requests was explicitly rejected, the procedure returns STATUS_ACCESS_DENIED.

NTSTATUSNTSTATUS

WinFSItemAccessCheck(WinFSItemAccessCheck (

WINFS_ITEMIDWINFS_ITEMID ItemId,ItemId, DWORDDWORD DesiredAccess,DesiredAccess, HANDLEHandle ClientToken,ClientToken PPRIVILEGE_SETPPRIVILEGE_SET pPrivilegeSet)pPrivilegeSet)

{{

NTSTATUSNTSTATUS Status;Status PDACLPDACL pExplicitACL = NULL;pExplicitACL = NULL; PDACLPDACL pInheritedACLs = NULL;pInheritedACLs = NULL; DWORDDWORD NumberOfInheritedACLs = 0;NumberOfInheritedACLs = 0;

pExplicitACL = GetExplicitACLForItem(ItemId);pExplicitACL = GetExplicitACLForItem (ItemId);

GetInheritedACLsForItem(ItemId,&pInheritedACLs,&NurnberOfInheritedAC Ls)GetInheritedACLsForItem (ItemId, & pInheritedACLs, & NurnberOfInheritedAC Ls)

Status = ACLAccessCheck(Status = ACLAccessCheck (

pOwnerSid,pOwnerSid,

pExplicitACL,pExplicitACL,

DesiredAccess,DesiredAccess,

ClientToken,ClientToken

pPrivilegeSet,pPrivilegeSet,

&GrantedAccess);&GrantedAccess);

if (Status != STATUS_SUCCESS)if (Status! = STATUS_SUCCESS)

return Status;return Status;

if (DesiredAccess == GrantedAccess)if (DesiredAccess == GrantedAccess)

return STATUS_SUCCESS;return STATUS_SUCCESS;

for(for (

i = 0;i = 0;

(i < NumberOfInheritedACLs && Status == STATUS_SUCCESS);(i <NumberOfInheritedACLs && Status == STATUS_SUCCESS);

i++){i ++) {

GrantedAccessForACL = 0;GrantedAccessForACL = 0;

Status = ACLAccessCheck(Status = ACLAccessCheck (

pOwnerSid,pOwnerSid,

pExplicitACL,pExplicitACL,

DesiredAccess,DesiredAccess,

ClientToken,ClientToken

pPrivilegeSet,pPrivilegeSet,

&GrantedAccessForACL);&GrantedAccessForACL);

if (Status == STATUS_SUCCESS) {if (Status == STATUS_SUCCESS) {

GrantedAccess != GrantedAccessForACL;GrantedAccess! = GrantedAccessForACL;

}}

}}

if ((Status == STATUS-SUCCESS) &&if ((Status == STATUS-SUCCESS) &&

(GrantedAccess != DesiredAccess)) {(GrantedAccess! = DesiredAccess)) {

Status = STATUS_ACCESS_DENIED;Status = STATUS_ACCESS_DENIED;

}}

return Status;return Status;

}}

Сфера влияния политики безопасности, заданной на любой статье, покрывает все потомки статьи в иерархии включения, заданной на хранилище данных. Для всех статей, где задана явная политика, мы в результате задаем политику, которая наследуется всеми ее потомками в иерархии включения. Эффективные ACL, унаследованные всеми потомками, получают, беря каждый из ACL, унаследованных статьей, и добавляя наследуемые ACE в явном ACL в начало ACL. Это называется множеством наследуемых ACL, связанных со статьей.The scope of the security policy defined on any article covers all descendants of the article in the inclusion hierarchy defined on the data warehouse. For all articles where an explicit policy is specified, as a result, we set a policy that is inherited by all its descendants in the inclusion hierarchy. Effective ACLs inherited by all descendants are obtained by taking each of the ACLs inherited by the article and adding inherited ACEs in the explicit ACL at the beginning of the ACL. This is called the multiple inherited ACLs associated with the article.

В отсутствие какой-либо явной спецификации безопасности в иерархии включения, имеющей корнем статью папки, спецификация безопасности статьи применяется ко всем потомкам этой статьи в иерархии включения. Таким образом, каждая статья, для которой обеспечена явная спецификация политики безопасности, задает область одинаково защищенных статей, и эффективные ACL для всех статей в области образуют множество наследуемых ACL для этой статьи. Это полностью задает области в случае, когда иерархия включения представляет собой дерево. Если с каждой областью связать число, то будет достаточно просто включить область, которой принадлежит статья, совместно со статьей.In the absence of any explicit security specification in the inclusion hierarchy that has the root of the folder entry, the security specification of the entry applies to all descendants of this entry in the inclusion hierarchy. Thus, each article for which an explicit security policy specification is provided defines an area of equally protected articles, and effective ACLs for all articles in the field form many inherited ACLs for this article. This fully defines the areas when the inclusion hierarchy is a tree. If you associate a number with each area, it will be quite simple to include the area to which the article belongs, together with the article.

Однако для иерархий включения, которые являются DAG, точки в иерархии включения, в которых эффективная политика безопасности изменяется, определяется двумя разновидностями статей. К первой относятся статьи, для которых были заданы явные ACL. Обычно в иерархии включения существуют точки, где администратор в явном виде задал ACL. Ко второй относятся статьи, которые имеют более одного родителя, и с разными родителями связаны разные политики безопасности. Обычно это статьи, которые являются точками слияния политик безопасности, заданных для тома, и указывают начало новой политики безопасности.However, for inclusion hierarchies that are DAGs, points in the inclusion hierarchy at which the effective security policy changes are defined by two kinds of entries. The first includes articles for which explicit ACLs have been defined. Typically, there are points in the inclusion hierarchy where the administrator explicitly specified the ACL. The second includes articles that have more than one parent, and different security policies are associated with different parents. Typically, these are articles that are the merging points of the security policies defined for the volume and indicate the beginning of a new security policy.

Благодаря этому определению все статьи в хранилище данных попадают в одну из двух категорий - те, которые являются корнем одинаково защищенной области безопасности, и те, которые таковыми не являются. Статьи, которые не задают области безопасности, принадлежат в точности одной области безопасности. Как и в случае деревьев, эффективную безопасность для статьи можно задавать, указывая область, к которой принадлежит статья, совместно со статьей. Это обеспечивает прямую модель администрирования безопасности хранилища данных платформы хранения на основании различных одинаково защищенных областей в хранилище.Thanks to this definition, all articles in the data warehouse fall into one of two categories - those that are the root of the equally protected security area, and those that are not. Articles that do not define a security domain belong to exactly one security domain. As with trees, effective security for an article can be specified by specifying the area to which the article belongs, together with the article. This provides a direct model for administering the security of the storage platform data warehouse based on various equally protected areas in the warehouse.

2. Подробное описание модели безопасности2. Detailed description of the security model

В этом разделе подробно описано обеспечение безопасности статей путем описания того, как индивидуальные права в описателе безопасности и содержащихся в них ACL влияют на различные операции.This section describes in detail how to secure articles by describing how individual rights in the security descriptor and the ACLs contained in them affect various operations.

a) Структура описателя безопасностиa) Security descriptor structure

Прежде чем подробно описать модель безопасности полезно рассмотреть описатели безопасности в более общем аспекте. Описатель безопасности содержит информацию безопасности, связанную с защищаемым объектом. Описатель безопасности состоит из структуры SECURITY_DESCRIPTOR и связанной с ней информацией безопасности. Описатель безопасности может включать в себя следующую информацию безопасности:Before describing the security model in detail, it is useful to consider security descriptors in a more general way. The security descriptor contains security information associated with the protected object. The security descriptor consists of the SECURITY_DESCRIPTOR structure and associated security information. The security descriptor may include the following security information:

1. SID'ы для владельца и первичной группы объекта.1. SIDs for the owner and primary group of the object.

2. DACL, которая задает права доступа, разрешенные или запрещенные конкретным пользователям или группам.2. DACL, which sets the access rights allowed or denied to specific users or groups.

3. SACL, который задает типы попыток доступа, которые генерируют записи аудита для объекта.3. SACL, which defines the types of access attempts that generate audit records for an object.

4. Множество битов управления, которые уточняют значение описателя безопасности или отдельных его элементов.4. Many control bits that specify the value of the security descriptor or its individual elements.

Предпочтительно, приложения не способны непосредственно манипулировать содержимым описателя безопасности. Существуют функции для задания и извлечения информации безопасности в описателе безопасности объекта. Кроме того, имеются функции для создания и инициализации описателя безопасности для нового объекта.Preferably, applications are not able to directly manipulate the contents of the security descriptor. There are functions for setting and retrieving security information in the object's security descriptor. In addition, there are functions for creating and initializing a security descriptor for a new object.

Дискреционный список управления доступом (DACL) идентифицирует доверенных лиц, которым разрешен или запрещен доступ к защищаемому объекту. Когда процесс пытается осуществить доступ к защищаемому объекту, система проверяет ACE в DACL объекта, чтобы определить, предоставить ли доступ к нему. Если объект не имеет DACL, система предоставляет полный доступ любому. Если DACL объекта не имеет ACE, система отклоняет все попытки доступа к объекту, поскольку DACL не дает никаких прав доступа. Система последовательно проверяет ACE, пока не найдет одну или более ACE, которые разрешают все запрошенные права доступа или пока не будут запрещены какие-либо из запрошенных прав доступа.The Discretionary Access Control List (DACL) identifies the trustees who are allowed or denied access to the protected object. When a process tries to access the protected object, the system checks the ACE in the object's DACL to determine whether to provide access to it. If the object does not have a DACL, the system provides full access to anyone. If the object's DACL does not have ACE, the system rejects all access attempts to the object, since the DACL does not give any access rights. The system sequentially checks the ACEs until it finds one or more ACEs that allow all requested access rights or until any of the requested access permissions are denied.

Системный список управления доступом (SACL) позволяет администратору регистрировать попытки доступа к защищенному объекту. Каждая ACE указывает типы попыток доступа со стороны указанного доверенного лица, что заставляет систему генерировать запись в журнале событий безопасности. ACE в SACL может генерировать записи аудита при неудачной попытке доступа, при удачной попытке доступа или в обоих случаях. SACL также может выдавать сигнал тревоги, когда неуполномоченный пользователь пытается осуществить доступ к объекту.The system access control list (SACL) allows the administrator to register attempts to access a protected object. Each ACE indicates the types of access attempts by the specified trustee, which causes the system to generate a security event log entry. The ACE in the SACL can generate audit records for a failed access attempt, for a successful access attempt, or in both cases. The SACL can also issue an alarm when an unauthorized user attempts to access an object.

Все типы ACE содержат следующую информацию управления доступом:All ACE types contain the following access control information:

1. Идентификатор безопасности (SID), которая идентифицирует доверенное лицо, к которому применяется ACE.1. A security identifier (SID) that identifies the trustee to whom the ACE applies.

2. Маска доступа, которая задает права доступа под управлением ACE.2. An access mask that sets access rights under ACE.

3. Флаг, указывающий тип ACE.3. A flag indicating the type of ACE.

4. Множество битовых флагов, которые определяют, могут ли дочерние контейнеры или объекты наследовать ACE от первичного объекта, к которому присоединен ACL.4. A set of bit flags that determine whether child containers or objects can inherit ACEs from the primary object to which the ACL is attached.

В нижеследующей таблице приведены три типа ACE, поддерживаемые всеми защищаемыми объектами.The following table shows three types of ACEs supported by all protected objects.

ТипType of ОписаниеDescription ACE, запрещающая доступACE Denying Access Используется в DACL для запрещения прав доступа доверенному лицу.Used in the DACL to prohibit access rights for a trustee. ACE, разрешающая доступACE allowing access Используется в DACL для разрешения прав доступа доверенному лицу.Used in the DACL to authorize access rights for a trustee. ACE системного аудитаACE System Audit Используется в SACL для генерации записи аудита, когда доверенное лицо пытается воспользоваться указанными правами доступа.Used by the SACL to generate an audit record when a proxy attempts to use the specified access rights.

(1) Формат маски доступа(1) Access mask format

Все защищаемые объекты организуют свои права доступа с использованием формата маски доступа, показанной на фиг.26. В этом формате, 16 младших битов предназначены для прав доступа, зависящих от объекта, следующие 7 битов предназначены для стандартных прав доступа, которые применяются к большинству типов объектов, и 4 старших бита используются для указания общих прав доступа, которые каждый тип объекта может отображать в множество стандартных и зависящих от объекта прав. Бит ACCESS_SYSTEM_SECURITY соответствует праву доступа SACL объекта.All protected objects organize their access rights using the access mask format shown in FIG. In this format, the 16 low-order bits are for object-specific access rights, the next 7 bits are for standard access rights that apply to most types of objects, and the 4 high-order bits are used to indicate the general access rights that each type of object can display in many standard and object-specific rights. The ACCESS_SYSTEM_SECURITY bit corresponds to the access right of the SACL of the object.

(2) Общие права доступа(2) General permissions

Общие права задаются в 4 старших битах маски. Каждый тип защищаемого объекта отображает эти биты в множество своих стандартных и зависящих от объекта прав доступа. Например, объект файла отображает бит GENERIC_READ в стандартные права доступа READ_CONTROL и SYNCHRONIZE и в права доступа, зависящие от объекта, FILE_READ_DATA, FILE_READ_EA, и FILE_READ_ATTRIBUTES. Объекты других типов отображают бит GENERIC_READ в какое-либо множество прав доступа, пригодных для этого типа объекта.Common rights are set in the 4 high-order bits of the mask. Each type of protected object maps these bits to its many standard and object-specific access rights. For example, a file object maps the GENERIC_READ bit to standard READ_CONTROL and SYNCHRONIZE access rights and to object-specific access rights FILE_READ_DATA, FILE_READ_EA, and FILE_READ_ATTRIBUTES. Other types of objects map the GENERIC_READ bit to any set of permissions suitable for this type of object.

Общие права доступа можно использовать для указания типа доступа, необходимых при открытии описателя объекту. Это обычно проще, чем задавать все соответствующие стандартные и особые права. В нижеследующей таблице приведены константы, заданные для общих прав доступа.General permissions can be used to specify the type of access required when opening a handle to an object. This is usually simpler than setting all the appropriate standard and special rights. The following table lists the constants defined for general permissions.

константаconstant Общее значениеOverall value GENERIC_ALLGENERIC_ALL Чтение, запись и доступ для выполненияRead, write, and access to execute GENERIC_EXECUTEGENERIC_EXECUTE Доступ для выполненияAccess to execute GENERIC_READGENERIC_READ Доступ для чтенияRead access GENERIC_WRITEGENERIC_WRITE Доступ для записиWrite access

(3) Стандартные права доступа(3) Standard access rights

Каждый тип защищаемого объекта имеет множество прав доступа, которые соответствуют операциям, характерных для этого типа объекта. Помимо этих прав доступа, зависящих от объекта, имеется множество стандартных прав доступа, которые соответствуют операциям, общим для большинства типов защищаемых объектов. В нижеследующей таблице показаны константы, заданные для стандартных прав доступа.Each type of protected object has many access rights that correspond to the operations specific to this type of object. In addition to these object-specific access rights, there are many standard access rights that correspond to the operations common to most types of protected objects. The following table shows the constants defined for standard permissions.

КонстантаConstant ЗначениеValue DELETEDELETE Право удаления объекта.The right to delete an object. READ_CONTROLREAD_CONTROL Право считывать информацию в описателе безопасности объекта, не включая информацию в SACL.The right to read information in the object's security descriptor, not including information in the SACL. SYNCHRONIZESYNCHRONIZE Право использовать объект для синхронизации. Это позволяет потоку ожидать, пока объект не окажется в сигнализированном состоянии. Некоторые типы объектов не поддерживают это право доступа.The right to use the object for synchronization. This allows the thread to wait until the object is in the signaled state. Some types of objects do not support this access right. WRITE_DACWRITE_DAC Право изменять DACL в описателе безопасности объекта.The right to change the DACL in the object's security descriptor. WRITE_OWNERWRITE_OWNER Право менять владельца в описателе безопасности объекта.The right to change the owner in the security descriptor of the object.

b) Права, зависящие от статьиb) Article-specific rights

В структуре маски доступа, показанной на фиг.26, права, зависящие от статьи, размещаются в разделе «права, зависящие от объекта» (младшие 16 битов). Поскольку, согласно данному варианту осуществления, платформа хранения открывает два набора API для администрирования безопасности - Win32 и API платформы хранения, права, зависящие от объекта, файловой системы нужно рассматривать для мотивирования построения прав, зависящих от объекта, платформы хранения.In the structure of the access mask shown in FIG. 26, article-dependent rights are placed in the “object-specific rights” section (the lower 16 bits). Since, according to this embodiment, the storage platform opens up two sets of APIs for administering security - Win32 and the storage platform APIs, object-specific file system rights should be considered to motivate the construction of object-specific rights, the storage platform.

(1) Права, зависящие от объекта «файл» и «директория»(1) Rights depending on the object “file” and “directory”

Рассмотрим следующую таблицу:Consider the following table:

ДиректорияDirectory Описание директорииDirectory Description ФайлFile Описание файлаFile description ЗначениеValue FILE_LIST_DIRECTORYFILE_LIST_DIRECTORY Право показывать содержимое директорииThe right to show the contents of the directory FILE_READ_DATAFILE_READ_DATA Право читать данные соответствующего файлаThe right to read the data of the corresponding file 0x00010x0001 FILE_ADD_FILEFILE_ADD_FILE Право создавать файл в директорииThe right to create a file in a directory FILE_WRITE_DATAFILE_WRITE_DATA Право записывать данные в файлThe right to write data to a file 0x00020x0002 FILE_ADD_SUBDIRECTORYFILE_ADD_SUBDIRECTORY Право создавать поддиректориюThe right to create a subdirectory FILE_APPEND_DATAFILE_APPEND_DATA Право присоединять данные к файлуThe right to attach data to a file 0x00040x0004 FILE_READ_EAFILE_READ_EA Право читать расширенные атрибуты файлаThe right to read extended file attributes FILE_READ_EAFILE_READ_EA Право читать расширенные атрибуты файлаThe right to read extended file attributes 0x00080x0008 FILE_WRITE_EAFILE_WRITE_EA Право записывать расширенные атрибуты файлаThe right to write extended file attributes FILE_WRITE_EAFILE _ WRITE _ EA Право записывать расширенные атрибуты файлаThe right to write extended file attributes 0x00100x0010 FILE_TRAVERSEFILE_TRAVERSE Право обходить директориюThe right to bypass the directory FILE_EXECUTEFILE _ EXECUTE Для файла внутреннего кода, право выполнять файлFor an internal code file, the right to execute the file 0x00200x0020 FILE_DELETE_CHILDFILE_DELETE_CHILD Право удалять директорию и все содержащиеся в ней файлыThe right to delete a directory and all files contained in it нетno нетno 0x00400x0040 FILE_READ_ATTRIBUTESFILE _ READ_ATTRIBUTES Право читать атрибуты директорииThe right to read directory attributes FILE_READ_ATTRIBUTESFILE_READ_ATTRIBUTES Право читать атрибуты файлаThe right to read file attributes 0x00800x0080 FILE_WRITE_ATTRIBUTESFILE_WRITE_ATTRIBUTES Право записывать атрибуты файлаThe right to write file attributes FILE_WRITE_ATTRIBUTESFILE_WRITE_ATTRIBUTES Право записывать атрибуты файлаThe right to write file attributes 0x01000x0100

Согласно вышеприведенной таблице заметим, что файловые системы делают принципиальные различия между файлами и директориями, по причине права, относящиеся к файлам и директориям, перекрываются на одних и тех же битах. Файловые системы задают весьма фрагментарные права, позволяющие приложениям управлять поведением на этих объектах. Например, они позволяют приложениям делать различия между атрибутами (FILE_READ/WRITE_ATTRIBUTES), расширенными атрибутами и потоком данных, связанным с файлом.According to the table above, we note that file systems make fundamental differences between files and directories, because of the rights related to files and directories that overlap on the same bits. File systems define very fragmented rights that allow applications to control behavior on these objects. For example, they allow applications to distinguish between attributes (FILE_READ / WRITE_ATTRIBUTES), extended attributes, and the data stream associated with a file.

Целью модели безопасности платформы хранения согласно настоящему изобретению является упрощение модели присвоения прав, чтобы приложениям, оперирующим статьями хранилища данных (контактами, адресами электронной почты и т.д.), в общем случае, не приходилось делать различия, например, между атрибутами, расширенными атрибутами и потоками данных. Однако для файлов и папок сохраняются фрагментарные права Win32 и задается семантика доступа посредством платформы хранения, что позволяет сохранять совместимость с приложениями Win32. Это отображение рассматривается для каждого из прав на статью, указанного ниже.The purpose of the security model of the storage platform according to the present invention is to simplify the assignment model so that applications operating with data storage articles (contacts, email addresses, etc.) generally do not have to make a distinction, for example, between attributes, extended attributes and data streams. However, Win32 fragmentary rights are saved for files and folders and access semantics are set via the storage platform, which allows maintaining compatibility with Win32 applications. This mapping is considered for each of the rights to the article listed below.

Следующие права на статью указаны совместно с соответствующими допустимыми операциями. Также предусмотрены эквивалентные права Win32, резервирующие каждое из этих прав на статью.The following rights to the article are indicated in conjunction with the corresponding permissible operations. Win32 equivalent rights are also provided that reserve each of these rights to the article.

(2) WinFSItemRead(2) WinFSItemRead

Это право позволяет осуществлять доступ для чтения ко всем эквивалентам статьи, включая статьи, связанные со статьей через отношения внедрения. Оно также допускает перечисление статей, привязанных к этой статье через отношения поддержки (наподобие отображения директории). При этом включаются имена статей, связанных отношениями ссылки. Это право отображается вThis right allows read access to all equivalents of an article, including articles related to the article through an implementation relationship. It also allows the listing of articles tied to this article through a support relationship (like displaying a directory). This includes the names of articles linked by link relationships. This right is displayed in

Файл:File:

(FILE_READ_DATA | SYNCHRONIZE)(FILE_READ_DATA | SYNCHRONIZE)

Папку:Folder:

(FILE_LIST_DIRECTORY | SYNCHRONIZE)(FILE_LIST_DIRECTORY | SYNCHRONIZE)

Семантика такова, что приложение безопасности не может задавать WinFSItemReadData и указывать маску прав как комбинацию указанных выше прав на файл.The semantics are that a security application cannot set WinFSItemReadData and specify a rights mask as a combination of the above file permissions.

(3) WinFSItemReadAttributes(3) WinFSItemReadAttributes

Это право позволяет осуществлять доступ для чтения к основным атрибутам статьи, хотя файловые системы делают различия между основными атрибутами файла и потоками данных. Предпочтительно, эти основные атрибуты это те, которые размещены в базовой статье, из которой выводятся все статьи. Это право отображается на:This right allows read access to the main attributes of the article, although file systems make a distinction between the main attributes of a file and data streams. Preferably, these basic attributes are those that are placed in the base article from which all articles are derived. This right is mapped to:

Файл:File:

(FILE_READ_ATTRIBUTES)(FILE_READ_ATTRIBUTES)

Папку:Folder:

(FILE_READ_ATTRIBUTES)(FILE_READ_ATTRIBUTES)

(4) WinFSItemWriteAttributes(4) WinFSItemWriteAttributes

Это право позволяет осуществлять доступ для записи к основным атрибутам статьи, хотя файловые системы делают различия между основными атрибутами файла и потоками данных. Предпочтительно, эти основные атрибуты это те, которые размещены в базовой статье, из которой выводятся все статьи. Это право отображается на:This right allows write access to the main attributes of the article, although file systems make a distinction between the main attributes of a file and data streams. Preferably, these basic attributes are those that are placed in the base article from which all articles are derived. This right is mapped to:

Файл:File:

(FILE_WRITE_ATTRIBUTES)(FILE_WRITE_ATTRIBUTES)

Папку:Folder:

(FILE_WRITE_ATTRIBUTES)(FILE_WRITE_ATTRIBUTES)

(5) WinFSItemWrite(5) WinFSItemWrite

Это право позволяет записывать все элементы статьи, включая статьи, связанные отношениями внедрения. Это право также дает возможность добавлять отношения внедрения в другие статьи или удалять их оттуда. Это право отображается на:This right allows you to record all the elements of an article, including articles related to implementation relationships. This right also allows you to add embedding relationships to other articles or remove them from there. This right is mapped to:

Файл:File:

(FILE_WRITE_DATA)(FILE_WRITE_DATA)

Папку:Folder:

(FILE_ADD_FILE)(FILE_ADD_FILE)

В хранилище данных платформы хранения не делается различий между статьями и папками, поскольку статьи также могут иметь отношения поддержки к другим статьям в хранилище данных. Поэтому, если вы имеете права FILE_ADD_SUBDIRECTORY (или FILE_APPEND_DATA), ваша статья может быть источником отношений к другим статьям.In the storage platform data warehouse, no distinction is made between articles and folders, since articles can also have support relationships with other articles in the data warehouse. Therefore, if you have the rights FILE_ADD_SUBDIRECTORY (or FILE_APPEND_DATA), your article may be a source of relations to other articles.

(6) WinFSItemAddLink(6) WinFSItemAddLink

Это право дает возможность добавлять отношения поддержки к статьям в хранилище. Следует заметить, что, поскольку модель безопасности для множественных отношений поддержки изменяет безопасность на статье и изменения могут обходить WRITE_DAC, если приходят из более высокой точки в иерархии, WRITE_DAC требуется на статье назначения, чтобы можно было создать отношение к ней. Это право отображается на:This right allows you to add support relationships to articles in the repository. It should be noted that since the security model for multiple support relationships changes the security on the article and the changes can bypass WRITE_DAC if they come from a higher point in the hierarchy, WRITE_DAC is required on the destination article in order to create a relationship to it. This right is mapped to:

Файл:File:

(FILE_APPEND_DATA)(FILE_APPEND_DATA)

Папку:Folder:

(FILE_ADD_SUBDIRECTORY)(FILE_ADD_SUBDIRECTORY)

(7) WinFSItemDeleteLink(7) WinFSItemDeleteLink

Это право дает возможность удалять поддержку статьи, даже если право удалять эту статью не дано принципалу. Это согласуется с моделью файловой системы и помогает осуществлять очистку. Это право отображается на:This right makes it possible to remove support for an article, even if the right to delete this article is not given to the principal. This is consistent with the file system model and helps clean up. This right is mapped to:

Файл:File:

(FILE_DELETE_CHILD) - заметим, что файловые системы не имеют файловый эквивалент этому праву, но мы имеем понятие о статьях, имеющих отношения поддержки к другим, и, следовательно, переносят это право также на непапки.(FILE _ DELETE_CHILD) - note that file systems do not have a file equivalent to this right, but we have the concept of articles that have support relationships to others, and therefore transfer this right to non-folders as well.

Папку:Folder:

(FILE_DELETE_CHILD)(FILE_DELETE_CHILD)

(8) Права на удаление статьи(8) Rights to delete an article

Статья уничтожается при устранении последнего отношения поддержки к статье. Не существует явного обозначения удаления статьи. Существует операция очистки, которая удаляет все отношения поддержки к статье, но это средство более высокого уровня, а не системный примитив.An article is destroyed when the last support relationship to the article is removed. There is no explicit designation for deleting an article. There is a cleanup operation that removes all support relationships for the article, but it is a higher-level tool, not a system primitive.

Любую статью, указанную с использованием пути, можно отвязать при удовлетворении любого из двух условий: (1) родительская статья по этому пути дает субъекту доступ для записи или (2) стандартные права на самой статье дают DELETE. При удалении последнего отношения статья исчезает из системы. Любую статью, указанную с использованием ItemID, можно отвязать, если стандартные права на самой статье дают DELETE.Any article specified using the path can be untied if either of the following conditions is met: (1) the parent article on this path gives the subject write access or (2) the standard rights on the article itself give DELETE. When you delete the last relationship, the article disappears from the system. Any article referenced using the ItemID can be untied if the standard rights on the article itself give DELETE.

(9) Права на копирование статьи(9) Rights to copy an article

Статью можно копировать из исходной папки в папку назначения, если субъекту дано WinFSItemRead на статье и WinFSItemWrite на папке назначения.An article can be copied from the source folder to the destination folder if the subject is given WinFSItemRead on the article and WinFSItemWrite on the destination folder.

(10) Права на перемещение статьи(10) Rights to Move Articles

Для перемещения файла в файловой системе требуется просто право DELETE на исходном файле и FILE_ADD_FILE на директории назначения, поскольку это сохраняет ACL на пункте назначения. Однако при вызове MoveFileEx можно задать флаг (MOVEFILE_COPY_ALLOWED), который позволяет приложению указывать, что это случай перемещения между томами, он может допускать семантику CopyFile. Есть 4 потенциальных варианта в отношении того, что происходит с описателем безопасности при перемещении:To move a file in the file system, you simply need the DELETE right on the source file and FILE_ADD_FILE on the destination directory, since this saves the ACL on the destination. However, when calling MoveFileEx, you can set the flag (MOVEFILE_COPY_ALLOWED), which allows the application to indicate that this is a case of moving between volumes, it can allow CopyFile semantics. There are 4 potential options for what happens to a move safety handle:

1. Весь ACL переносится с файлом - семантика перемещения внутри тома, принятая по умолчанию.1. The entire ACL is carried with the file - the default semantics of movement within the volume are accepted.

2. Весь ACL переносится с файлом и маркируется как защищенный.2. The entire ACL is transferred with the file and marked as protected.

3. Переносятся только явные ACE и они повторно наследуются на пункте назначения.3. Only explicit ACEs are migrated and they are re-inherited at the destination.

4. Ничто не переносится и ничто не наследуется повторно на пункте назначения - семантика перемещения между томами, принятая по умолчанию - то же самое, что копирование файла.4. Nothing is transferred and nothing is inherited repeatedly at the destination — the default semantics of moving between volumes are the same as copying a file.

В данной модели безопасности, если приложение задает флаг MOVEFILE_COPY_ALLOWED, четвертый вариант осуществляется для меж- и внутритомных случаев. Если этот флаг не задан, осуществляется второй вариант, если пункт назначения находится в той же области безопасности (т.е. одинаковые семантики наследования). Перемещение на уровне платформы хранения реализует четвертый вариант, а также требует READ_DATA на источнике, почти как копирование.In this security model, if the application sets the MOVEFILE_COPY_ALLOWED flag, the fourth option is implemented for inter- and intra-internal cases. If this flag is not set, the second option is implemented if the destination is in the same security area (i.e., the same inheritance semantics). Moving at the storage platform level implements the fourth option, and also requires READ_DATA on the source, almost like copying.

(11) Права на просмотр политики безопасности на статье(11) Rights to view security policy on an article

Безопасность статьи можно просматривать, если статья дает субъекту стандартное право READ_CONTROL.Security of an article can be viewed if the article gives the subject the standard READ_CONTROL right.

(12) Права на изменение политики безопасности на статье(12) Rights to change security policy on the article

Безопасность статьи можно изменять, если статья дает субъекту стандартное право WRITE_DAC. Однако, поскольку хранилище данных обеспечивает неявное наследование, от этого зависит, как можно изменять безопасности на иерархиях. Правило состоит в том, что, если корень иерархии дает WRITE_DAC, то политику безопасности можно изменять на всей иерархии независимо от того, дают ли конкретные статьи в иерархии (или DAG) право WRITE_DAC субъекту.The security of an article can be changed if the article gives the subject standard WRITE_DAC right. However, since the data warehouse provides implicit inheritance, it depends on how security can be changed on hierarchies. The rule is that if the root of the hierarchy gives WRITE_DAC, then the security policy can be changed throughout the hierarchy, regardless of whether specific articles in the hierarchy (or DAG) grant WRITE_DAC to the subject.

(13) Права, не имеющие прямого эквивалента(13) Rights not directly equivalent

Согласно данному варианту осуществления FILE_EXECUTE (FILE_TRAVERSE для директорий) не имеют прямого эквивалента в платформе хранения. Модель сохраняет их для совместимости с Win32, но на основании этих прав не принимаются решения на предоставление доступа. Что касается FILE_READ/WRITE_EA, поскольку статьи хранилища данных не имеют обозначений расширенных атрибутов, семантика для этого бита не предусмотрена. Однако бит остается для совместимости с Win32.According to this embodiment, FILE_EXECUTE (FILE_TRAVERSE for directories) do not have a direct equivalent in the storage platform. The model saves them for compatibility with Win32, but based on these rights no decisions are made on granting access. As for FILE_READ / WRITE_EA, since the data warehouse articles do not have extended attributes, there is no semantics for this bit. However, the bit remains for compatibility with Win32.

3. Реализация3. Implementation

Все статьи, задающие одинаково защищенные области, имеют связанные с ними ячейки в таблице безопасности. Таблица безопасности задана следующим образом:All articles defining equally protected areas have cells associated with them in the security table. The security table is defined as follows:

Идентификация статьиArticle Identification Упорядоченный путь к статьеOrdered article path Явный ACL статьиExplicit ACL Articles ACL путейACL paths ACL областейACL areas

Ячейка «Идентификация статьи» это идентификация статьи для корня одинаково защищенной области безопасности. Ячейка «Упорядоченный путь к статье» - это упорядоченный путь, связанный с корнем одинаково защищенной области безопасности. Ячейка «Явный ACL статьи» - это явный ACL, заданный для корня одинаково защищенной области безопасности. В некоторых случаях он может быть равен NULL, например, при задании новой области безопасности, поскольку статья имеет нескольких родителей, принадлежащих разным областям. Ячейка «ACL путей» - это множество ACL, унаследованных статьей, и ячейка «ACL областей» это множество ACL, заданных для одинаково защищенной области безопасности, связанной со статьей.An “Article Identification” cell is the article identification for the root of an equally protected security area. An Ordered Article Path cell is an ordered path associated with the root of an equally protected security area. An “Explicit Article ACL” cell is an explicit ACL defined for the root of an equally protected security area. In some cases, it may be NULL, for example, when defining a new security area, because the article has several parents belonging to different areas. The “path ACL” cell is the set of ACLs inherited by the article, and the “area ACL” cell is the set of ACLs defined for the equally protected security area associated with the article.

Вычисление эффективной безопасности для любой статьи в данном хранилище усиливает эту таблицу. Для определения политики безопасности, связанной со статьей, получают область безопасности, связанную со статьей, и извлекают ACL, связанные с этой областью.The calculation of effective security for any article in this repository reinforces this table. To determine the security policy associated with the article, obtain the security scope associated with the article and retrieve the ACLs associated with this scope.

При изменении политики безопасности, связанной со статьей, либо прямого, путем добавления явных ACL, либо косвенного, путем добавления отношений поддержки, что приводит к формированию новых областей безопасности, таблица безопасности обновляется, тем самым гарантируя пригодность вышеописанного алгоритма для определения эффективной безопасности статьи.When changing the security policy associated with an article, either directly, by adding explicit ACLs, or indirectly by adding support relationships, which leads to the formation of new security areas, the security table is updated, thereby ensuring the suitability of the above algorithm to determine the effective security of the article.

Опишем различные изменения, вносимые в хранилище и соответствующие алгоритмы для поддержания таблицы безопасности.We describe the various changes made to the repository and the corresponding algorithms for maintaining the security table.

а) Создание новой статьи в контейнереa) Create a new article in the container

При создании новой статьи в контейнере, она наследует все ACL, связанные с контейнером. Поскольку вновь созданная статья имеет в точности одного родителя, она принадлежит той же области, что и родитель. Таким образом, нет необходимости создавать новую ячейку в таблице безопасности.When creating a new article in a container, it inherits all the ACLs associated with the container. Since the newly created article has exactly one parent, it belongs to the same area as the parent. Thus, there is no need to create a new cell in the security table.

b) Добавление к статье явного ACLb) Adding an explicit ACL to the article

При добавлении ACL к статье, он задает новую область безопасности для всех ее потомков в иерархии включения, которые принадлежат той же области безопасности, что и сама эта статья. Для всех статей, принадлежащих другим областям безопасности, но являющихся потомками данной статьи в иерархии включения, область безопасности остается неизменной, но эффективный ACL, связанный с областью, изменяется, отражая добавление нового ACL.When you add an ACL to an article, it defines a new security scope for all its descendants in the inclusion hierarchy that belong to the same security scope as the article itself. For all articles that belong to other security domains, but are descendants of this article in the inclusion hierarchy, the security domain remains unchanged, but the effective ACL associated with the domain changes to reflect the addition of a new ACL.

Введение этой новой области безопасности может обуславливать задание дополнительных областей для всех статей, которые имеют множественные отношения поддержки с предками, которые охватывают старую область безопасности и вновь заданную область безопасности. Для всех таких статей нужно задавать новую область безопасности, и процедура повторяется.The introduction of this new security area may lead to additional areas for all articles that have multiple support relationships with ancestors that cover the old security area and the newly defined security area. For all such articles, a new security area needs to be defined and the procedure repeats.

На фиг.27(a), (b), и (c) показано, что новые одинаково защищенные области безопасности выделяются из существующей области безопасности благодаря введению нового явного ACL. Это указано узлом, обозначенным 2. Однако введение этой новой области приводит к созданию дополнительной области 3, поскольку статья имеет множественные отношения поддержки.27 (a), (b), and (c) show that new equally protected security areas are distinguished from an existing security area by introducing a new explicit ACL. This is indicated by the node indicated by 2. However, the introduction of this new area leads to the creation of additional area 3, since the article has multiple support relationships.

Следующая последовательность обновлений таблиц безопасности отражает разбиение одинаково защищенных областей безопасности.The following sequence of security table updates reflects a split of equally protected security areas.

с) Добавление к статье отношения поддержкиc) Adding a support relationship to an article

Добавление к статье отношения поддержки обуславливает одну из трех возможностей. Если цель отношения поддержки, т.е. рассматриваемая статья, является корнем области безопасности, то эффективный ACL, связанный с областью, изменяется, и никаких дополнительных изменений таблицы безопасности не требуется. Если область безопасности источника нового отношения поддержки идентична области безопасности существующих родителей статьи, то никаких изменений не требуется. Если же статья в данный момент имеет родителей, которые принадлежат другим областям безопасности, то формируется новая область безопасности, имеющая данную статью в качестве корня области безопасности. Это изменение распространяется на все статьи в иерархии включения путем изменения области безопасности, связанной со статьей. Все статьи, принадлежащие той же области безопасности, что и рассматриваемая статья и ее потомки в иерархии включения, нуждаются в изменении. После проведения изменения, все статьи, имеющие множественные отношения поддержки, должны быть проверены на предмет необходимости дальнейших изменений. Дополнительные изменения могут потребоваться, если какая-либо из этих статей имеет родителей в других областях безопасности.Adding a support relationship to an article provides one of three possibilities. If the goal is a support relationship, i.e. The article in question is the root of the security domain, the effective ACL associated with the domain is changed, and no additional changes to the security table are required. If the security domain of the source of the new support relationship is identical to the security domain of the existing article parents, then no changes are required. If the article currently has parents who belong to other security areas, a new security area is formed, which has this article as the root of the security field. This change applies to all entries in the inclusion hierarchy by changing the security scope associated with the entry. All articles that belong to the same security domain as the article in question and its descendants in the inclusion hierarchy need to be changed. After the change, all articles with multiple support relationships should be checked for the need for further changes. Additional changes may be required if any of these articles has parents in other areas of security.

d) Удаление отношения поддержки из статьиd) Removing a support relationship from an article

При удалении отношения поддержки из статьи возможно слияние области безопасности с ее родительской областью при выполнении определенных условий. В частности, это может происходить при следующих условиях: (1) если удаление отношения поддержки приводит к тому, что статья имеет одного родителя, и для этой статьи не задано ни одного явного ACL; (2) если удаление отношения поддержки приводит к тому, что все родители статьи принадлежат одной и той же области безопасности, и для этой статьи не задано ни одного явного ACL. В этих обстоятельствах область безопасности можно маркировать как идентичную родительской. Эту маркировку нужно применять ко всем статьям, чьи области безопасности соответствуют области, подвергающейся слиянию.When you remove a support relationship from an article, the security domain may merge with its parent domain if certain conditions are met. In particular, this can occur under the following conditions: (1) if the deletion of the support relationship results in the article having one parent and no explicit ACLs are specified for this article; (2) if the deletion of the support relationship results in all parents of the article belonging to the same security domain and no explicit ACLs are specified for this article. In these circumstances, the security domain can be marked as identical to the parent. This marking must be applied to all articles whose safety areas correspond to the area undergoing the merger.

е) Удаление явного ACL из статьиf) Removing an explicit ACL from an article

При удалении явного ACL из статьи возможно слияние области безопасности, конем которой является данная статья, с областями безопасности ее родителей. В частности, это происходит, если удаление явного ACL приводит к тому, что родители статьи в иерархии включения принадлежат одной и той же области безопасности. В этих обстоятельствах область безопасности можно маркировать как идентичную родительской, и изменения применяются ко всем статьям, чьи области безопасности соответствуют области, подвергающейся слиянию.When you remove an explicit ACL from an article, it is possible to merge the security domain whose horse this article is with the security domains of its parents. In particular, this happens if deleting an explicit ACL causes the parents of the article in the inclusion hierarchy to belong to the same security area. In these circumstances, the security area can be marked as identical to the parent, and the changes apply to all articles whose security areas correspond to the area being merged.

f) Изменение ACL, связанного со статьейf) Change in ACL associated with an article

В этом сценарии не требуется никаких добавлений к таблице безопасности. Эффективный ACL, связанный с областью, обновляется, и новое изменение ACL распространяется на области безопасности, подверженные его влиянию.In this scenario, no additions to the security table are required. The effective area-related ACL is updated, and a new change to the ACL extends to the security areas affected by it.

F. Извещения и отслеживание измененийF. Notification and Change Tracking

Согласно другому аспекту настоящего изобретения платформа хранения обеспечивает возможность извещения, которая позволяет приложениям отслеживать изменения данных. Эта особенность предназначена, в основном, для приложений, которые поддерживают подвижное состояние или выполняют коммерческую логику на событиях изменения данных. Приложения регистрируют извещения на статьях, расширениях статей и отношениях статей. Извещения доставляются асинхронно после осуществления изменений данных. Приложения могут фильтровать извещения по статье, расширению и типу отношения, а также по типу операции.According to another aspect of the present invention, the storage platform provides a notification capability that allows applications to track data changes. This feature is mainly intended for applications that support a mobile state or execute commercial logic on data change events. Applications register notifications on articles, article extensions, and article relations. Notifications are delivered asynchronously after data changes. Applications can filter notifications by article, extension and type of relationship, as well as by type of operation.

Согласно одному варианту осуществления API 322 платформы хранения обеспечивает две разновидности интерфейсов для извещений. В первой приложения регистрируют простые события изменения данных, обусловленные изменениями статей, расширений статей и отношений статей. Во второй приложения создают объекты «наблюдатель» для мониторинга множеств статей, расширений статей и отношений статей. Состояние объекта наблюдателя можно сохранять и повторно создавать после сбоя системы или после того, как система проработает в автономном режиме в течение продолжительного периода времени. Единичное извещение может отражать множественные обновления.In one embodiment, storage platform API 322 provides two kinds of notification interfaces. In the first application, simple data change events are recorded due to changes in articles, article extensions, and article relations. In the second application, “observer” objects are created to monitor multiple articles, article extensions, and article relationships. The state of the observer object can be saved and re-created after a system failure or after the system has been working offline for an extended period of time. A single notification may reflect multiple updates.

1. Сохранение событий изменения1. Saving change events

В данном разделе приведено несколько примеров использования интерфейсов извещения, обеспеченных API 322 платформы хранения.This section provides several examples of using the notification interfaces provided by the storage platform API 322.

а) Событияa) Events

Статьи, расширения статей и отношения статей открывают события изменения данных, которые используются приложениями для регистрации извещений изменения данных. Следующий иллюстративный код демонстрирует определение обработчиков событий ItemModified и ItemRemoved на базовом классе Item.Articles, article extensions, and article relations open data change events that are used by applications to record data change notifications. The following code illustrates the definition of the ItemModified and ItemRemoved event handlers on the base class Item.

// События// Developments

public event ItemModifiedEventHandler Item ItemModified;public event ItemModifiedEventHandler Item ItemModified ;

public event ItemRemovedEventHandler Item ItemRemoved;public event ItemRemovedEventHandler Item ItemRemoved ;

Все извещения несут достаточно данных для извлечения измененной статьи из хранилища данных. Следующий иллюстративный код демонстрирует регистрацию событий на статье, расширении статьи или отношении статей:All notifications carry enough data to retrieve the modified article from the data warehouse. The following illustrative code demonstrates the registration of events on an article, article extension, or article relation:

myItem.ItemModified += newmyItem.ItemModified + = new

ItemModifiedEventHandler(this.onItemUpdate);ItemModifiedEventHandler (this.onItemUpdate);

myItem.ItemRemoved += newmyItem.ItemRemoved + = new

ItemRemovedEventHandler(this.onItemDelete);ItemRemovedEventHandler (this.onItemDelete);

Согласно данному варианту осуществления платформа хранения гарантирует извещение приложений об изменении или удалении соответствующей статьи после последней доставки извещения или в случае новой регистрации после последней выборки из хранилища данных.According to this embodiment, the storage platform ensures that applications are notified of changes or deletions of the corresponding article after the last delivery of the notification or in the case of a new registration after the last retrieval from the data warehouse.

b) Наблюдателиb) Observers

Согласно данному варианту осуществления платформа хранения задает классы наблюдателей для мониторинга объектов, связанных с (1) папкой или иерархией папок, (2) контекстом статьи или (3) конкретной статьей. Для каждой из этих трех категорий платформа хранения обеспечивает определенные классы наблюдателей, которые отслеживают соответствующие статьи, расширения статей или отношения статей, например, платформа хранения обеспечивает соответствующие классы FolderItemWatcher, FolderRelationshipWatcher и FolderExtensionWatcher.According to this embodiment, the storage platform defines observer classes for monitoring objects associated with (1) a folder or folder hierarchy, (2) the context of an article, or (3) a specific article. For each of these three categories, the storage platform provides specific observer classes that track related articles, article extensions, or article relationships, for example, the storage platform provides the corresponding classes FolderItemWatcher, FolderRelationshipWatcher and FolderExtensionWatcher.

Для создания наблюдателя приложение может запросить извещения для ранее существующих статей, т.е. статей, расширений или отношений. Эта возможность характерна для приложений, которые поддерживают частный кэш статей. В отсутствие запроса приложения принимают извещения для всех обновлений, которые происходят после создания объекта наблюдателя.To create an observer, an application may request notifications for previously existing articles, i.e. articles, extensions, or relationships. This feature is common for applications that support a private article cache. In the absence of a request, applications receive notifications for all updates that occur after the creation of an observer object.

Совместно с доставкой извещений платформа хранения выдает объект "WatcherState" (состояние наблюдателя). WatcherState может быть преобразован к последовательному виду и сохранен на диске. После этого состояние наблюдателя можно использовать для воссоздания соответствующего наблюдателя после сбоя или после повторного соединения после периода автономной работы. Вновь воссозданный наблюдатель будет повторно генерировать неквитированные извещения. Приложения обозначают доставку извещения, вызывая метод "Exclude" на соответствующем состоянии наблюдателя, выдающий ссылку на извещение.Together with notification delivery, the storage platform issues a WatcherState object (observer state). WatcherState can be converted to sequential mode and saved to disk. After that, the state of the observer can be used to recreate the corresponding observer after a failure or after reconnecting after a period of autonomous work. The newly recreated observer will re-generate unacknowledged notifications. Applications indicate delivery of a notification by calling the "Exclude" method on the corresponding state of the observer, issuing a link to the notification.

Платформа хранения доставляет отдельные копии состояния наблюдателя на каждый обработчик событий. Состояния наблюдателя, принятые при последующих вызовах одного и того же обработчика событий, предполагают доставку всех ранее принятых извещений.The storage platform delivers separate copies of the observer state to each event handler. Observer states received on subsequent calls to the same event handler assume delivery of all previously received notifications.

В порядке примера следующий иллюстративный код демонстрирует определение FolderItemWatcher.By way of example, the following code illustrates the definition of a FolderItemWatcher.

public class FolderItemWatcher: Watcherpublic class FolderItemWatcher: Watcher

{{

// Конструкторы// Constructors

public FolderItemWatcher_Constructor(Folder folder);public FolderItemWatcher_Constructor (Folder folder);

public FolderItemWatcher_Constructor1(Folder folder,public FolderItemWatcher_Constructor1 (Folder folder,

Type itemType);Type itemType);

public FolderItemWatcher_Constructor2(ItemContext context,public FolderItemWatcher_Constructor2 (ItemContext context,

ItemId folderId);ItemId folderId);

public FolderItemWatcher_Constructor3(Folder folder,public FolderItemWatcher_Constructor3 (Folder folder,

Type itemType, FolderItemWatcherOptions options);Type itemType, FolderItemWatcherOptions options);

public FolderItemWatcher_Constructor4(ItemContext context,public FolderItemWatcher_Constructor4 (ItemContext context,

ItemId folderId, Type itemType);ItemId folderId, Type itemType);

public FolderItemWatcher_Constructor5(ItemContext context,public FolderItemWatcher_Constructor5 (ItemContext context,

ItemId folderId, TypeItemId folderId, Type

itemType, FolderItemWatcherOptions options);itemType, FolderItemWatcherOptions options);

// Свойства// Properties

public ItemId FolderItemWatcher_FolderId {get;}public ItemId FolderItemWatcher_FolderId {get;}

public Type FolderItemWatcher_ItemType {get;}public Type FolderItemWatcher_ItemType {get;}

public FolderItemWatcherOptionspublic FolderItemWatcherOptions

FolderItemWatcher_Options (get;} FolderItemWatcher_Options (get;}

// События// Developments

public event ItemChangedEventHandlerpublic event ItemChangedEventHandler

FolderItemWatcher_ItemChanged; FolderItemWatcher_ItemChanged ;

}}

Следующий иллюстративный код демонстрирует, как создавать объект наблюдатель папки для мониторинга содержимого папки. Наблюдатель генерирует извещения, т.е. события, когда добавляются новые статьи музыки или существующие статьи музыки обновляются или удаляются. Наблюдатели папок отслеживают либо конкретную папку, либо все папки в иерархии папок.The following code illustrates how to create a folder watcher object to monitor the contents of a folder. The observer generates notifications, i.e. events when new music articles are added or existing music articles are updated or deleted. Folder watchers track either a specific folder or all folders in a folder hierarchy.

myFolderItemWatcher = new FolderItemWatcher(myFolder,myFolderItemWatcher = new FolderItemWatcher (myFolder,

typeof(Music));typeof (Music));

myFolderItemWatcher.ItemChanged += newmyFolderItemWatcher.ItemChanged + = new

ItemChangedEventHandler(this.onItemChanged);ItemChangedEventHandler (this.onItemChanged);

2. Механизм отслеживания изменений и генерации извещений2. Change tracking and notification mechanism

Платформа хранения обеспечивает простой, но эффективный механизм отслеживания изменений данных и генерации извещений. Клиент извлекает извещения на том же самом соединении, которое используется для извлечения данных. Это, в общем случае, упрощает проверки безопасности, устраняет задержки и ограничения на возможных сетевых конфигурациях. Извещения извлекаются путем выдачи операторов выбора. Во избежание опроса клиенты могут использовать признак "waitfor", обеспеченный машиной 314 базы данных. На фиг.13 показана основная концепция извещения платформы хранения. Этот запрос waitfor может выполняться синхронно, и в этом случае вызывающий поток блокируется до получения результатов, или асинхронно, в этом случае поток не блокируется, и результаты возвращаются на отдельном потоке, когда они доступны.The storage platform provides a simple but effective mechanism for tracking data changes and generating alerts. The client retrieves notifications on the same connection that is used to retrieve the data. This, in general, simplifies security checks, eliminates delays and restrictions on possible network configurations. Notifications are retrieved by issuing selection statements. To avoid polling, clients can use the “waitfor” attribute provided by the database engine 314. 13 shows the basic concept of a storage platform notification. This waitfor request can be executed synchronously, in which case the calling thread is blocked until the results are received, or asynchronously, in this case the thread is not blocked, and the results are returned on a separate thread when they are available.

Комбинация "waitfor" и "select" привлекательна для мониторинга изменений данных, которые входят в конкретный диапазон данных, поскольку изменения можно отслеживать, задавая блокировку извещений на соответствующем диапазоне данных. Это поддерживается для многих общих сценариев платформы хранения. Изменения отдельных статей можно эффективно отслеживать, задавая блокировки извещений на соответствующем диапазоне данных. Изменения папок и деревьев папок можно отслеживать, задавая блокировки извещений на диапазонах путей. Изменения типов и их подтипов можно отслеживать, задавая блокировки извещений на диапазонах типов.The combination of "waitfor" and "select" is attractive for monitoring data changes that fall within a specific data range, since changes can be tracked by setting the notification block on the corresponding data range. This is supported for many common storage platform scenarios. Changes to individual articles can be effectively tracked by setting notification locks on the appropriate data range. Changes to folders and folder trees can be tracked by setting notification locks on path ranges. Changes to types and their subtypes can be monitored by setting notification locks on type ranges.

В общем случае существует три разные фазы, связанные с обработкой извещений: (1) изменение или даже обнаружение данных, (2) согласование подписок и (3) доставка извещений. Исключая синхронную доставку извещений, т.е. доставку извещений как часть транзакции, осуществляющей изменение данных, платформа хранения может реализовать две формы доставки извещений:In the general case, there are three different phases associated with the processing of notifications: (1) change or even discovery of data, (2) approval of subscriptions, and (3) delivery of notices. Excluding synchronous delivery of notifications, i.e. notification delivery as part of a data change transaction, the storage platform can implement two forms of notification delivery:

1) немедленное обнаружение событий: обнаружение событий и согласование подписки осуществляется как часть транзакции обновления; извещения вставляются в таблицу, отслеживаемую абонентом;1) immediate event detection: event detection and subscription negotiation is carried out as part of the update transaction; notifications are inserted into the table tracked by the subscriber;

2) отсроченное обнаружение событий: обнаружение событий и согласование подписки осуществляется после выполнения транзакции обновления; после этого фактический абонент или посредник обнаруживает события и генерирует извещения.2) delayed event detection: event detection and subscription approval is carried out after the update transaction; after that, the actual subscriber or intermediary detects events and generates notifications.

Немедленное обнаружение событий требует дополнительного кода для выполнения как части операций обновления. Это позволяет захватывать все интересующие события, включающие события, указывающие относительное изменение состояния.Immediate event detection requires additional code to execute as part of update operations. This allows you to capture all the events of interest, including events that indicate a relative change in state.

Отсроченное обнаружение событий устраняет необходимость в добавлении дополнительного кода для операций обновления. Отсроченное обнаружение событий, естественно, группирует обнаружение событий и доставку событий и хорошо согласуется с инфраструктурой выполнения запросов машины 314 базы данных (например, SQL Server).Delayed event detection eliminates the need to add additional code for update operations. Delayed event detection naturally groups event detection and event delivery and is consistent with the query infrastructure of database engine 314 (e.g., SQL Server).

Отсроченное обнаружение событий опирается на журнал или след, оставленный операциями обновления. Платформа хранения поддерживает множество логических меток времени совместно с надгробиями для удаленных статей данных. При сканировании хранилища данных на предмет изменений клиенты выдают метку времени, которая задает низкий водяной знак для обнаружения изменений, и множество меток времени во избежание дублирования извещений. Приложения могут принимать извещения для всех изменений, произошедших после времени, указанного низким водяным знаком.Deferred event detection relies on a log or trace left by update operations. The storage platform supports many logical timestamps along with tombstones for deleted data items. When scanning a data warehouse for changes, clients issue a time stamp that sets a low watermark to detect changes, and many time stamps to avoid duplicate notifications. Applications can accept notifications for all changes that occur after a time indicated by a low watermark.

Более сложные приложения с доступом к видам ядра могут дополнительно оптимизировать и сокращать количество операторов SQL, необходимых для мониторинга потенциально большого множества статей за счет создания частного параметра и дублирования таблиц фильтров. Приложения с особыми потребностями, например, которые должны поддерживать богатые виды, могут использовать доступную структуру отслеживания изменений для мониторинга изменений данных и обновления их частных снимков.More complex applications with access to kernel views can further optimize and reduce the number of SQL statements needed to monitor a potentially large number of articles by creating a private parameter and duplicating filter tables. Applications with special needs, for example, that must support rich views, can use the available change tracking framework to monitor data changes and update their private snapshots.

Поэтому предпочтительно, согласно одному варианту осуществления, платформа хранения реализует подход отсроченного обнаружения событий, который более подробно описан ниже.Therefore, preferably, according to one embodiment, the storage platform implements a delayed event detection approach, which is described in more detail below.

а) Отслеживание измененийa) Change tracking

Все определения статей, расширений и отношений статей несут уникальный идентификатор. Отслеживание изменений поддерживает множество логических меток времени для регистрации моментов создания, обновления и удаления для всех статей данных. Записи надгробий используются для представления удаленных статей данных.All definitions of articles, extensions, and article relations carry a unique identifier. Change tracking supports many logical timestamps for recording the creation, update, and deletion times for all data articles. Tombstone records are used to represent deleted data articles.

Приложения используют эту информацию, чтобы эффективно отслеживать, была(о) ли конкретная(ое) статья, расширение статьи или отношение статей вновь создана(о), обновлена(о) или удалена(о) после последнего обращения приложения к хранилищу данных. Следующий пример иллюстрирует этот механизм.Applications use this information to effectively track whether (a) a particular article, article extension, or article relation has been created (o), updated (o), or deleted (o) since the application last accessed the data warehouse. The following example illustrates this mechanism.

create table [item-extension-relationship-table-template] (create table [item-extension-relationship-table-template] (

identifier uniqueidentifier not null default newid()identifier uniqueidentifier not null default newid ()

created bigint, not null, -- @ @ dbts when createdcreated bigint, not null, - @ @ dbts when created

updated bigint, not null, -- @ @ dbts when last updatedupdated bigint, not null, - @ @ dbts when last updated

...

))

Все удаленные статьи, расширения статей и отношения записываются в соответствующую таблицу надгробий. Ниже показан шаблон.All deleted articles, article extensions, and relationships are recorded in the corresponding gravestone table. Below is a template.

create table [item-extension-relationship-tombstonecreate table [item-extension-relationship-tombstone

table-template] (table-template] (

identifier uniqueidentifier not null,identifier uniqueidentifier not null,

deleted bigint not null, -- @@ dbts when deleted,deleted bigint not null, - @@ dbts when deleted,

created bigint not null, -- @@ dbts when createdcreated bigint not null, - @@ dbts when created

upated bigint not null, -- @@ dbts when last updatedupated bigint not null, - @@ dbts when last updated

...

))

По соображениям эффективности, платформа хранения поддерживает набор глобальных таблиц для статей, расширений статей, отношений и имен путей. Эти глобальные таблицы поиска могут использоваться приложениями для эффективного мониторинга диапазона данных и извлечения соответствующей метки времени и информации типа.For efficiency reasons, the storage platform supports a set of global tables for articles, article extensions, relationships, and path names. These global lookup tables can be used by applications to efficiently monitor a range of data and retrieve the appropriate timestamp and type information.

b) Управление метками времениb) Time stamp management

Логические метки времени являются «локальными» по отношению к хранилищу базы данных, т.е. тому платформы хранения. Метки времени являются монотонно возрастающими 64-битовыми значениями. Для обнаружения, произошло ли изменение данных после последнего соединения с томом платформы хранения, часто бывает достаточно оставлять одну метку времени. Однако, в большинстве реалистических сценариев, приходится оставлять несколько больше меток времени, чтобы проверять дубликаты. Причины этого объяснены ниже.Logical timestamps are “local” with respect to the database storage, i.e. volume storage platforms. Timestamps are monotonically increasing 64-bit values. To detect whether a data change has occurred since the last connection to the storage platform volume, it is often sufficient to leave one time stamp. However, in most realistic scenarios, you have to leave a few more timestamps to check for duplicates. The reasons for this are explained below.

Таблицы реляционной базы данных представляют собой логические абстракции, надстроенные на множестве физических структур данных, т.е. бинарных деревьев, «куч» и т.д. Присвоение метки времени вновь созданной или обновленной записи не является элементарным действием. Вставка этой записи в нижележащие структуры данных может происходить в разные моменты времени, что позволяет приложениям видеть записи в произвольном порядке.Relational database tables are logical abstractions that are add-on to many physical data structures, i.e. binary trees, heaps, etc. Assigning a time stamp to a newly created or updated record is not an elementary action. The insertion of this record into the underlying data structures can occur at different points in time, which allows applications to see the records in random order.

На фиг.14 показаны две транзакции, обе из которых вставляют новую запись в одно и то же бинарное дерево. Поскольку транзакция Т3 вставляет свою запись до запланированной вставки транзакции Т2, приложение, сканирующее бинарное дерево, может видеть записи, вставленные транзакцией Т3, до вставленных Т2. Таким образом, читатель может неправильно предположить, что увидел все записи, созданные до времени «10». Чтобы решить этот вопрос, машина 314 базы данных обеспечивает функцию, которая возвращает низкий водяной знак, до которого все изменения были произведены и вставлены в соответствующие нижележащие структуры данных. В вышеприведенном примере, возвращенный низкий водяной знак имеет значение «5», исходя из предположения, что читатель начал до того, как была проведена транзакция Т2. Низкий водяной знак, обеспеченный машиной 314 базы данных, позволяет приложениям эффективно определять, какие статьи игнорировать при сканировании базы данных или диапазона данных на предмет изменений данных. В общем случае, предполагается, что транзакции ACID длятся очень короткое время, поэтому ожидается, что низкие водяные знаки очень близки к наиболее недавно установленной метке времени. При наличии долговременных транзакций, приложения должны оставлять индивидуальные метки времени для обнаружения и отбрасывания дубликатов.On Fig shows two transactions, both of which insert a new record in the same binary tree. Since transaction T3 inserts its record before the scheduled insertion of transaction T2, the application scanning the binary tree can see the records inserted by transaction T3 before the inserted T2. Thus, the reader may incorrectly assume that he saw all the records created before the time "10". To solve this issue, the database engine 314 provides a function that returns a low watermark until which all changes have been made and inserted into the corresponding underlying data structures. In the above example, the returned low watermark has a value of “5” based on the assumption that the reader started before transaction T2 was conducted. The low watermark provided by the database engine 314 allows applications to efficiently determine which articles to ignore when scanning a database or data range for data changes. In general, ACID transactions are supposed to last a very short time, so low watermarks are expected to be very close to the most recently set timestamp. In the presence of long-term transactions, applications must leave individual timestamps to detect and discard duplicates.

с) Обнаружение изменения данных - обнаружение событийc) Data change detection - event detection

Запрашивая хранилище данных, приложения получают низкий водяной знак. Затем приложения используют этот водяной знак для сканирования хранилища данных на предмет записей, метки времени создания, обновления или удаления которых больше, чем возвращенный низкий водяной знак. Этот процесс показан на фиг.15.By requesting a data warehouse, applications receive a low watermark. Applications then use this watermark to scan the data store for records whose timestamps for creating, updating, or deleting are larger than the returned low watermark. This process is shown in FIG.

Во избежание дублирования извещений приложения запоминают метки времени, которые больше возвращенного низкого водяного знака, и используют их для отфильтровывания дубликатов. Приложения создают локальные временные таблицы сеансов для эффективной обработки большого множества дублирующих друг друга меток времени. Перед выдачей оператора выбора приложение вставляет все дублирующие друг друга метки времени, возращенные ранее, и удаляет те из них, которые старше последнего возвращенного низкого водяного знака, что проиллюстрировано ниже.To avoid duplicate notifications, applications remember timestamps that are larger than the returned low watermark and use them to filter out duplicates. Applications create local temporary session tables to efficiently process a large number of duplicate timestamps. Before issuing a select statement, the application inserts all duplicate time stamps returned earlier and deletes those that are older than the last returned low watermark, as illustrated below.

delete from $duplicates where ts < @oldLowWaterMark;delete from $ duplicates where ts <@oldLowWaterMark;

insert into $duplicates(ts) values(…),…,(…);insert into $ duplicates (ts) values (...), ..., (...);

waitfor(select *, getLowWaterMark() as newLowWaterMarkwaitfor (select *, getLowWaterMark () as newLowWaterMark

from [global!items]from [global! items]

where updated >= @oldLowWaterMarkwhere updated> = @oldLowWaterMark

and updated not in (select * from $duplicates))and updated not in (select * from $ duplicates))

G. СинхронизацияG. Sync

Согласно другому аспекту настоящего изобретения платформа хранения обеспечивает услугу синхронизации 330, которая (i) позволяет множественным экземплярам платформы хранения (каждая из которых имеет собственное хранилище данных 302) синхронизировать части своего контента согласно гибкому множеству правил, и (ii) обеспечивает инфраструктуру для третьих сторон для синхронизации хранилища данных платформы хранения настоящего изобретения с другими источниками данных, которые реализуют собственнические протоколы.According to another aspect of the present invention, the storage platform provides a synchronization service 330, which (i) allows multiple instances of the storage platform (each with its own data store 302) to synchronize parts of its content according to a flexible set of rules, and (ii) provides infrastructure for third parties for synchronizing the data warehouse of the storage platform of the present invention with other data sources that implement proprietary protocols.

Синхронизация между платформами хранения происходит в группе участвующих копий. Например, согласно фиг.3, может быть желательно обеспечить синхронизацию между хранилищем данных 302 платформы хранения 300 с другим удаленным хранилищем данных 338 под управлением другого экземпляра платформы хранения, возможно, действующего на другой компьютерной системе. Все члены этой группы не обязательно должны быть известны любой данной копии в любое данное время.Synchronization between storage platforms occurs in a group of participating copies. For example, according to FIG. 3, it may be desirable to provide synchronization between the data store 302 of the storage platform 300 with another remote data store 338 under the control of another instance of the storage platform, possibly operating on a different computer system. All members of this group need not be known to any given copy at any given time.

Разные копии могут производить изменения независимо (т.е. одновременно). Процесс синхронизации определяется как информирование каждой копии об изменениях, произведенных другими копиями. Этой возможности синхронизации внутренне присуща множественная мастеризация.Different copies can make changes independently (i.e. at the same time). The synchronization process is defined as informing each copy of changes made by other copies. This synchronization feature is intrinsic to multiple mastering.

Возможность синхронизации настоящего изобретения позволяет копиям:The ability to synchronize the present invention allows copies:

- определять, о каких изменениях знает другая копия;- determine what changes another copy knows;

- запрашивать информацию об изменениях, о которых этой копии не известно;- request information about changes about which this copy is not known;

- переносить информацию об изменениях, о которых другой копии не известно;- transfer information about changes about which another copy is not known;

- определять, когда два изменения конфликтуют друг с другом;- determine when two changes conflict with each other;

- локально применять изменения;- apply changes locally;

- переносить разрешения конфликтов на другие копии для обеспечения сходимости;- Transfer conflict resolution to other copies to ensure convergence;

- разрешать конфликты на основании заданных политик для разрешения конфликтов.- resolve conflicts based on predefined policies to resolve conflicts.

1. Синхронизация между платформами хранения1. Synchronization between storage platforms

Основное применение услуги синхронизации 330 платформы хранения настоящего изобретения состоит в синхронизации множественных экземпляров платформы хранения (каждый из которых имеет собственное хранилище данных). Услуга синхронизации действует на уровне схем платформы хранения (а не нижележащих таблиц машины 314 базы данных). Так, например, «области действия» используются для задания множеств синхронизации, которые рассмотрены ниже.The main application of the synchronization service 330 of the storage platform of the present invention is to synchronize multiple instances of the storage platform (each of which has its own data store). The synchronization service operates at the level of the storage platform schemes (and not the underlying tables of the database engine 314). So, for example, “scopes” are used to define synchronization sets, which are discussed below.

Услуга синхронизации действует по принципу «чистых изменений». Вместо записи и передачи отдельных операций (как при транзакционном дублировании) услуга синхронизации передает конечный результат этих операций, таким образом часто консолидируя результаты множественных операций в единое результирующее изменение.The synchronization service operates on the basis of the “net change” principle. Instead of recording and transmitting individual operations (as in transactional duplication), the synchronization service transfers the final result of these operations, thus often consolidating the results of multiple operations into a single resultant change.

Услуга синхронизации, в общем случае, не признает границы транзакции. Другими словами, если два изменения произведены в хранилище данных платформы хранения в одной транзакции, нет никакой гарантии, что эти изменения автоматически применяются ко всем остальным копиям - одно может произойти без другого. Исключение из этого принципа состоит в том, что, если два изменения произведены в одной и той же статье в одной и той же транзакции, то эти изменения гарантированно передаются и автоматически применяются к другим копиям. Таким образом, статьи являются единицами согласованности для услуги синхронизации.The synchronization service, in general, does not recognize the boundaries of the transaction. In other words, if two changes are made to the storage platform data warehouse in one transaction, there is no guarantee that these changes are automatically applied to all other copies - one can happen without the other. An exception to this principle is that if two changes are made in the same article in the same transaction, then these changes are guaranteed to be transferred and automatically applied to other copies. Thus, articles are units of consistency for a synchronization service.

а) Приложения управления синхронизациейa) Synchronization management applications

Любое приложение может подключаться к услуге синхронизации и инициировать операцию синхронизации. Такое приложение обеспечивает все параметры, необходимые для осуществления синхронизации (см. профиль синхронизации ниже). Такие приложения называются здесь приложениями управления синхронизацией (SCA).Any application can connect to a synchronization service and initiate a synchronization operation. Such an application provides all the parameters necessary for synchronization (see the synchronization profile below). Such applications are referred to herein as synchronization management (SCA) applications.

При синхронизации двух экземпляров платформы хранения синхронизация инициируется на одной стороне посредством SCA. Это SCA информирует локальную услугу синхронизации для синхронизации с удаленным партнером. С другой стороны, услуга синхронизации пробуждается сообщениями, передаваемыми услугой синхронизации от машины-источника. Оно отвечает на основании информации устойчивой конфигурации (см. отображения ниже), присутствующей на машине назначения. Услуга синхронизации может действовать по расписанию или в ответ на события. В этих случаях услуга синхронизации, реализующая расписание, становится SCA.When synchronizing two instances of the storage platform, synchronization is initiated on one side through the SCA. This SCA informs the local synchronization service for synchronization with the remote partner. On the other hand, the synchronization service is awakened by messages transmitted by the synchronization service from the source machine. It responds based on the stable configuration information (see mappings below) present on the destination machine. The synchronization service can operate on a schedule or in response to events. In these cases, the synchronization service implementing the schedule becomes SCA.

Для обеспечения синхронизации нужно выполнить два этапа. Во-первых, разработчик схем должен аннотировать схему платформы хранения надлежащей семантикой синхронизации (указывающей блоки изменения, описанные ниже). Во-вторых, синхронизация должна быть правильно сконфигурирована на всех машинах, имеющих экземпляр платформы хранения, который должен участвовать в синхронизации (как описано ниже).To ensure synchronization, you need to perform two steps. First, the schema designer must annotate the storage platform schema with the proper synchronization semantics (indicating the change blocks described below). Secondly, synchronization must be properly configured on all machines that have a storage platform instance that must participate in synchronization (as described below).

b) Аннотация схемыb) Annotation of the scheme

Основным понятием услуги синхронизации является понятие блока изменения. Блок изменения - это мельчайший кусок схемы, индивидуально отслеживаемый платформой хранения. Для каждого блока изменения услуга синхронизации может определять, изменился ли он после последней синхронизации.The basic concept of a synchronization service is the concept of a change unit. A change block is the smallest piece of diagram that is individually tracked by the storage platform. For each change block, the synchronization service can determine if it has changed since the last synchronization.

Указание блоков изменения в схеме служит нескольким целям. Во-первых, это позволяет определить, насколько информативна услуга синхронизации на проводе. Когда в блоке изменения производятся изменения, весь блок изменения передается другим копиям, поскольку услуга синхронизации не знает, какая часть блока изменения подверглась изменению. Во-вторых, это позволяет определить степень фрагментарности обнаружения конфликта. Когда один и тот же блок изменения подвергается двум одновременным изменениям (эти термины подробно определены в последующих разделах), услуга синхронизации возбуждает конфликт; если же одновременные изменения производятся в разных блоках изменения, конфликт не возбуждается, и изменения автоматически сливаются. В-третьих, это сильно влияет на объем метаданных, поддерживаемых системой. Большой объем метаданных услуг синхронизации сохраняется в расчете на блок изменения; таким образом, чем меньше блок изменения, тем больше служебная нагрузка синхронизации.Specifying change blocks in a schema serves several purposes. Firstly, it allows you to determine how informative the synchronization service on the wire. When changes are made in a change block, the entire change block is transferred to other copies, because the synchronization service does not know which part of the change block has undergone a change. Secondly, it allows you to determine the degree of fragmentation of conflict detection. When the same change block undergoes two simultaneous changes (these terms are detailed in the following sections), the synchronization service causes a conflict; if simultaneous changes are made in different blocks of change, the conflict is not excited, and the changes are automatically merged. Thirdly, this greatly affects the amount of metadata supported by the system. A large amount of metadata of synchronization services is stored per block of change; thus, the smaller the change unit, the greater the synchronization overhead.

Для задания блоков изменения требуется найти правильные компромиссы. По этой причине услуга синхронизации позволяет разработчикам схем участвовать в процессе.To set change blocks, you need to find the right compromises. For this reason, the synchronization service allows circuit designers to participate in the process.

Согласно одному варианту осуществления услуга синхронизации не поддерживает блоки изменения, которые больше элемента. Однако она поддерживает способность разработчиков схем задавать блоки изменения, которые меньше элемента, а именно, группировать множественные атрибуты элемента в отдельный блок изменения. Согласно этому варианту осуществления для этого используется следующий синтаксис:According to one embodiment, the synchronization service does not support change units that are larger than an element. However, it does support the ability of schema developers to define change units that are smaller than an element, namely, group multiple attribute attributes of an element into a separate change block. According to this embodiment, the following syntax is used for this:

<Type Name="Appointment" MajorVersion="1" MinorVersion="0"<Type Name = "Appointment" MajorVersion = "1" MinorVersion = "0"

ExtendsType="Base.Item" Extends Version="1">ExtendsType = "Base.Item" Extends Version = "1">

<Field Name="MeetingStatus" Type="the storage<Field Name = "MeetingStatus" Type = "the storage

platformTypes.uniqueidentifier Nullable="False"/>platformTypes.uniqueidentifier Nullable = "False" />

<Field Name="OrganizerName" Type="the storage<Field Name = "OrganizerName" Type = "the storage

platformTypes.nvarchar(512)" Nullable="False"/>platformTypes.nvarchar (512) "Nullable =" False "/>

<Field Name="OrganizerEmail" Type="the storage<Field Name = "OrganizerEmail" Type = "the storage

platformTypes.nvarchar(512)"platformTypes.nvarchar (512) "

TypeMajorVersion="1" MultiValued="True"/>TypeMajorVersion = "1" MultiValued = "True" />

...

<ChangeUnit Name="CU_Status"><ChangeUnit Name = "CU_Status">

<Field Name="MeetingStatus"/><Field Name = "MeetingStatus" />

</ChangeUnit></ChangeUnit>

<ChangeUnit Name="CU_Organizer"/><ChangeUnit Name = "CU_Organizer" />

<Field Name="OrganizerName"/><Field Name = "OrganizerName" />

<Field Name="OrganizerEmail"/><Field Name = "OrganizerEmail" />

</ChangeUnit></ChangeUnit>

...

</Type></Type>

с) Конфигурация синхронизацииc) Sync configuration

Группа партнеров платформы хранения, которые желают поддерживать определенные части своих данных в синхронизме, называется сообществом синхронизации. Хотя члены сообщества хотят оставаться в синхронизме, им не обязательно представлять данные в точности одинаковым способом; другими словами, партнеры синхронизации могут преобразовывать данные, которые они синхронизируют.A group of storage platform partners who want to keep certain parts of their data in sync is called the synchronization community. Although community members want to stay in sync, they don't have to present the data in exactly the same way; in other words, synchronization partners can transform the data that they synchronize.

В сценарии взаимодействия равноправных устройств для равноправных устройств непрактично поддерживать отображения преобразования для всех своих партнеров. Вместо этого, услуга синхронизации пользуется подходом задания "папок сообщества". Папка сообщества - это абстракция, представляющая гипотетическую «совместно используемую папку», с которой синхронизируются все члены сообщества.In a peer-to-peer device interaction scenario, it is impractical for peer devices to maintain mapping mappings for all their partners. Instead, the synchronization service takes the approach of setting “community folders”. A community folder is an abstraction that represents a hypothetical “shared folder” with which all community members synchronize.

Это понятие лучше всего проиллюстрировать на примере. Если Джо хочет поддерживать папки My Documents на нескольких своих компьютерах в синхронизме Джо задает папку сообщества, именуемую, скажем, JoesDocuments. Затем, на каждом компьютере, Джо конфигурирует отображение между гипотетической папкой JoesDocuments и логической папкой My Documents. С этого момента, когда компьютеры Джо синхронизируются друг с другом, они говорят в терминах документов в JoesDocuments, а не их локальных статей. Таким образом, все компьютеры Джо понимают друг друга без необходимости знать, кто такие другие - Папка сообщества становится лингва-франка сообщества синхронизации.This concept is best illustrated by an example. If Joe wants to maintain My Documents folders on several of his computers in synchronism, Joe sets up a community folder called, say, JoesDocuments. Then, on each computer, Joe configures the mapping between the hypothetical JoesDocuments folder and the My Documents logical folder. From now on, when Joe's computers are synchronized with each other, they speak in terms of documents in JoesDocuments, rather than their local articles. Thus, all of Joe's computers understand each other without the need to know who the others are - Community Folder becomes lingua franca community synchronization.

Конфигурирование услуги синхронизации состоит из трех этапов: (1) задание папок между локальными папками и папками сообщества; (2) задание профилей синхронизации, которые определяют, что синхронизируется (например, с кем синхронизироваться и какие подмножества нужно передавать и какие принимать); и (3) задание расписаний, согласно которым должны запускаться профили, или запуск их вручную.Configuring the synchronization service consists of three stages: (1) setting folders between local folders and community folders; (2) setting synchronization profiles that determine what is being synchronized (for example, with whom to synchronize and which subsets to transmit and which to receive); and (3) setting schedules according to which profiles should be started, or starting them manually.

(1) Папка сообщества - отображения(1) Community Folder - Mappings

Отображения папки сообщества сохраняются на отдельных машинах как файлы конфигурации XML. Каждое отображение имеет следующую схему:Community folder mappings are saved on separate machines as XML configuration files. Each mapping has the following scheme:

/отображения/папка сообщества/ mappings / community folder

Этот элемент дает имя папке сообщества, для которой предназначено это отображение. Имя подчиняется следующему синтаксису папок.This item gives the name of the community folder for which this mapping is intended. The name obeys the following folder syntax.

/отображения/локальная папка/ display / local folder

Этот элемент дает имя локальной папке, в которую отображение преобразует. Имя подчиняется правилам синтаксиса для папок. Папка должна уже существовать, чтобы отображение было действительным. Статьи в этой папке рассматриваются для синхронизации посредством этого отображения.This item gives the name of the local folder into which the mapping will convert. The name follows the syntax rules for folders. The folder must already exist for the display to be valid. Articles in this folder are considered for synchronization through this display.

/отображения/преобразования/ display / conversion

Этот элемент задает, как преобразовывать статьи из папки сообщества в локальную папку и наоборот. В частности, это значит, что никакие ИД не отображаются. Эта конфигурация, в основном, используется для создания кэша папки.This element defines how to convert articles from a community folder to a local folder and vice versa. In particular, this means that no IDs are displayed. This configuration is mainly used to create a folder cache.

/отображения/преобразования/ИД отображений/ mappings / conversions / mappings ID

Этот элемент требует, чтобы вновь сгенерированные локальные ИД присваивались всем статьям, отображаемым из папки сообщества, вместо повторного использования ИД сообщества. Среда выполнения синхронизации будет поддерживать отображения ИД для преобразования статей в двух направлениях.This element requires that the newly generated local IDs be assigned to all articles displayed from the community folder, instead of reusing the community ID. The synchronization runtime will support ID mappings for converting articles in two directions.

/отображения/преобразования/локальный корень/ mappings / transforms / local root

Этот элемент требует, чтобы корневые статьи в папке сообщества были сделаны дочерними статьями указанного корня.This element requires that the root entries in the community folder be made child entries of the specified root.

/отображения/действовать за/ display / act for

Этот элемент управляет, от чьего имени обрабатываются запросы относительно этого отображения. Если отсутствует, предполагается отправитель.This element controls on behalf of which requests for this mapping are processed. If absent, the sender is assumed.

/отображения/ действовать за/отправитель/ display / act for / sender

Наличие этого элемента указывает, что нужно действовать за отправителя сообщений на это отображение, и запросы, обработанные под его мандатом.The presence of this element indicates that it is necessary to act for the sender of messages on this display, and requests processed under his mandate.

(2) Профили(2) Profiles

Профиль синхронизации это полный набор параметров, необходимых для начала синхронизации. Он передается SCA среде выполнения синхронизации для инициирования синхронизации. Профили синхронизации для синхронизации между платформами хранения содержат следующую информацию:A synchronization profile is a complete set of parameters necessary to start synchronization. It is passed to the SCA by the synchronization runtime to initiate synchronization. Synchronization profiles for synchronization between storage platforms contain the following information:

- локальная папка, служащая источником и пунктом назначения для изменений;- a local folder that serves as the source and destination for changes;

- имя удаленной папки, с которой нужно синхронизироваться - эта папка должна быть опубликована от удаленного партнера посредством отображения, как описано выше;- name of the remote folder with which you want to synchronize - this folder must be published from the remote partner by displaying, as described above;

- направление - услуга синхронизации поддерживает синхронизацию только передачи, только приема и передачи-приема;- direction - the synchronization service supports synchronization of only transmission, only reception and transmission-reception;

- локальный фильтр - выбирает, какую локальную информацию передавать удаленному партнеру. Выражается как запрос платформы хранения по локальной папке;- local filter - selects what local information to transmit to the remote partner. Expressed as a storage platform request for a local folder;

- удаленный фильтр - выбирает, какую удаленную информацию извлекать из удаленного партнера - выражается как запрос платформы хранения по папке сообщества;- remote filter - selects what remote information to retrieve from the remote partner - expressed as a request to the storage platform for the community folder;

- преобразования - задает, как преобразовывать статьи в локальный формат и из него;- conversions - sets how to convert articles to and from a local format;

- локальная безопасность - указывает, подлежат ли изменения, извлеченные из удаленной концевой точки, применению по разрешению удаленной концевой точки (подмененной) или пользователя, локально инициирующего синхронизацию;- local security - indicates whether the changes extracted from the remote endpoint are subject to application by permission of the remote endpoint (spoofed) or the user locally initiating synchronization;

- политика разрешения конфликтов - указывает, следует ли конфликты отбрасывать, регистрировать или автоматически разрешать - в последнем случае, указывает, какой алгоритм разрешения конфликтов использовать, а также параметры конфигурации для него.- conflict resolution policy - indicates whether conflicts should be dropped, registered or automatically resolved - in the latter case, it indicates which conflict resolution algorithm to use, as well as configuration parameters for it.

Услуга синхронизации обеспечивает класс CLR среды выполнения, который позволяет простое построение профилей синхронизации. Профили могут также преобразовывать к последовательному виду в файлы XML или из них для простоты хранения (часто рядом со схемами). Однако не существует стандартного места в платформе хранения, где хранятся все свойства; SCA могут строить профиль на пятне, даже не сохраняя его. Заметим, что для инициирования синхронизации не требуется иметь локальное отображение. Вся информация синхронизации может быть задана в профиле. Однако отображение требуется для ответа на запросы синхронизации, инициированные удаленной стороной.The synchronization service provides a runtime CLR class that allows easy construction of synchronization profiles. Profiles can also be sequentially converted to or from XML files for ease of storage (often next to schemas). However, there is no standard place in the storage platform where all properties are stored; SCAs can build a profile on a spot without even saving it. Note that initiating synchronization does not require a local mapping. All synchronization information can be specified in the profile. However, mapping is required to respond to synchronization requests initiated by the remote side.

(3) Расписания(3) Schedules

Согласно одному варианту осуществления услуга синхронизации не обеспечивает собственную инфраструктуру планирования. Напротив, она опирается на другой компонент для выполнения этой задачи - Windows Scheduler, имеющийся в операционной системе Microsoft Windows. Услуга синхронизации включает в себя утилиту командной строки, которая действует как SCA и запускает синхронизацию на основании профиля синхронизации, хранящегося в файле XML. Эта утилита позволяет очень легко конфигурировать Windows Scheduler для запуска синхронизации либо по расписанию, либо в ответ на события, например вход или выход пользователя.According to one embodiment, the synchronization service does not provide its own scheduling infrastructure. On the contrary, it relies on another component to perform this task - the Windows Scheduler, which is available in the Microsoft Windows operating system. The synchronization service includes a command line utility that acts as an SCA and starts synchronization based on the synchronization profile stored in the XML file. This utility makes it very easy to configure the Windows Scheduler to start synchronization, either on schedule or in response to events, such as user input or output.

d) Обработка конфликтовd) Conflict handling

Обработка конфликтов в услуге синхронизации делится на три стадии: (1) обнаружение конфликта, которое происходит в момент применения изменения - этот этап определяет, можно ли безопасно применить изменение; (2) автоматическое разрешение и регистрация конфликтов - на этом этапе (который имеет место сразу после обнаружения конфликта) осуществляется консультация с алгоритмами автоматического разрешения конфликтов, чтобы посмотреть, можно ли разрешить конфликт - если нет, конфликт можно в необязательном порядке зарегистрировать; и (3) инспекция и разрешение конфликта - этот этап имеет место, если некоторые конфликты были зарегистрированы, и осуществляется вне контекста сеанса синхронизации - в это время зарегистрированные конфликты можно разрешить и удалить из журнала.Conflict handling in the synchronization service is divided into three stages: (1) conflict detection that occurs at the time the change is applied - this stage determines whether the change can be applied safely; (2) automatic resolution and registration of conflicts - at this stage (which takes place immediately after the conflict is detected), consultations with automatic conflict resolution algorithms are carried out to see if the conflict can be resolved - if not, the conflict can be registered optionally; and (3) inspection and resolution of the conflict - this stage takes place if some conflicts have been registered and is carried out outside the context of the synchronization session - at this time the registered conflicts can be resolved and deleted from the journal.

(1) Обнаружение конфликта(1) Conflict Detection

Согласно данному варианту осуществления услуга синхронизации обнаруживает два типа конфликтов: на основе знания и на основе ограничения.According to this embodiment, the synchronization service detects two types of conflicts: based on knowledge and based on restriction.

(а) Конфликты на основе знания(a) Knowledge-based conflicts

Конфликт на основе знания происходит, когда две копии производят независимые изменения в одном и том же блоке изменения. Два изменения называются независимыми, если они производятся без знания друг о друге - другими словами, версия первого не покрывается знанием второго и наоборот. Услуга синхронизации автоматически обнаруживает все такие конфликты на основании вышеописанного знания копий.A knowledge-based conflict occurs when two copies make independent changes in the same change block. Two changes are called independent if they are made without knowledge of each other - in other words, the version of the first is not covered by knowledge of the second and vice versa. The synchronization service automatically detects all such conflicts based on the above knowledge of copies.

Иногда полезно рассматривать конфликты как разветвления в истории версий блока изменения. Если конфликты происходят во время жизни блока изменения, его история версий является простой цепью - каждое изменение происходит после предыдущего. В случае конфликта на основе знания два изменения происходят параллельно, вызывая расщепление цепи и ее превращение в дерево версий.It is sometimes useful to consider conflicts as branches in the version history of a change block. If conflicts occur during the life of a change block, its version history is a simple chain - each change occurs after the previous one. In the event of a knowledge-based conflict, two changes occur in parallel, causing the chain to split and turn into a version tree.

(b) Конфликты на основе ограничений(b) Conflict based conflicts

Бывают случаи, когда независимые изменения нарушают ограничения целостности при совместном применении. Например, такой конфликт может возникнуть, когда две копии создают файл с одним и тем же именем в одной и той же директории.There are times when independent changes violate integrity constraints when used together. For example, such a conflict can occur when two copies create a file with the same name in the same directory.

Конфликт на основе ограничения предусматривает два независимых изменения (как и конфликт на основе знания), но они не относятся к одному и тому же блоку изменения. Напротив, они относятся к разным блокам изменения, но с ограничением, существующим между ними.A conflict based on a constraint involves two independent changes (like a conflict based on knowledge), but they do not belong to the same block of change. On the contrary, they relate to different blocks of change, but with the restriction that exists between them.

Услуга синхронизации обнаруживает нарушения ограничений в момент применения изменения и автоматически возбуждает конфликты на основе ограничения. Для разрешения конфликтов на основе ограничения обычно требуется специальный код, который изменяет изменения таким образом, чтобы они не нарушали ограничение. Услуга синхронизации не обеспечивает универсальный механизм для этого.The synchronization service detects restrictions violations at the time the change is applied and automatically causes conflicts based on the restriction. To resolve conflicts based on a constraint, special code is usually required that modifies the changes so that they do not violate the constraint. The synchronization service does not provide a universal mechanism for this.

(2) Обработка конфликтов(2) Conflict Handling

Когда конфликт обнаружен, услуга синхронизации может совершить одно из трех действий (по выбору инициатора синхронизации в профиле синхронизации): (1) отклонить изменение, возвратив его отправителю; (2) зарегистрировать конфликт в журнале конфликтов; или (3) автоматически разрешить конфликт.When a conflict is detected, the synchronization service can perform one of three actions (at the choice of the initiator of synchronization in the synchronization profile): (1) reject the change by returning it to the sender; (2) register the conflict in the conflict log; or (3) automatically resolve the conflict.

При отклонении изменения, услуга синхронизации действует как если бы изменение не поступало на копию. Отправителю направляется отрицательное квитирование. Эта политика разрешения особенно полезна на безголовых копиях (например, файловых серверах), где регистрация конфликтов невыполнима. Напротив, такие копии заставляют других иметь дело с конфликтами, отклоняя их.If the change is rejected, the synchronization service acts as if the change did not arrive at the copy. A negative acknowledgment is sent to the sender. This resolution policy is especially useful on headless copies (e.g. file servers), where recording conflicts is not feasible. On the contrary, such copies force others to deal with conflicts, rejecting them.

Инициаторы синхронизации конфигурируют разрешение конфликтов в своих профилях синхронизации. Услуга синхронизации поддерживает объединение множественных алгоритмов разрешения конфликтов в одном профиле следующими способами - во-первых, задавая список алгоритмов разрешения конфликтов, подлежащих испытанию по очереди, пока один из них не приведет к успеху; и, во-вторых, связывая алгоритмы разрешения конфликтов с типами конфликтов, например, направляя конфликты на основе знания между обновлениями на один алгоритм разрешения конфликтов, а все остальные конфликты - в журнал.Sync initiators configure conflict resolution in their synchronization profiles. The synchronization service supports combining multiple conflict resolution algorithms in one profile in the following ways - firstly, by setting a list of conflict resolution algorithms to be tested in turn, until one of them leads to success; and, secondly, linking conflict resolution algorithms to conflict types, for example, directing conflicts based on knowledge between updates to one conflict resolution algorithm, and all other conflicts to a log.

(а) Автоматическое разрешение конфликтов(a) Automatic conflict resolution

Услуга синхронизации обеспечивает ряд алгоритмов разрешения конфликтов, принятых по умолчанию. Этот список включает в себя:The synchronization service provides a number of default conflict resolution algorithms. This list includes:

- локальный приоритет: игнорировать входящие изменения, если они конфликтуют с локально сохраненными данными;- local priority: ignore incoming changes if they conflict with locally stored data;

- удаленный приоритет: игнорировать локальные данные, если они конфликтуют с входящими изменениями;- remote priority: ignore local data if they conflict with incoming changes;

- приоритет последней записи: выбор локального приоритета или удаленного приоритета для каждого блока изменения на основании метки времени изменения (заметим, что услуга синхронизации, в общем случае, не опирается на значения часов; этот алгоритм разрешения конфликтов является единственным исключением из этого правила);- priority of the last record: choosing a local priority or remote priority for each change block based on the time stamp of the change (note that the synchronization service, in the general case, is not based on the clock values; this conflict resolution algorithm is the only exception to this rule);

- детерминистический: выбор приоритета таким образом, чтобы гарантировать, что он будет одинаковым на всех копиях, но не будет иметь смысла в других случаях - один вариант осуществления услуг синхронизации использует лексикографические сравнения ИД партнеров для реализации этого признака.- deterministic: the choice of priority in such a way as to ensure that it will be the same on all copies, but will not make sense in other cases - one option for the implementation of synchronization services uses lexicographic comparisons of partner IDs to implement this feature.

Кроме того, ISV могут реализовать и установить свои собственные алгоритмы разрешения конфликтов. Специализированные алгоритмы разрешения конфликтов могут принимать параметры конфигурации; такие параметры должны быть указаны SCA в разделе «Разрешение конфликтов» профиля синхронизации.In addition, ISVs can implement and install their own conflict resolution algorithms. Specialized conflict resolution algorithms can accept configuration parameters; such parameters should be specified by the SCA in the Conflict Resolution section of the synchronization profile.

Когда алгоритм разрешения конфликтов обрабатывает конфликт, он возвращает список операций, которые необходимо осуществить (вместо конфликтующих изменений) обратно в среду выполнения. Затем услуга синхронизации применяет эти операции, надлежащим образом отрегулировав удаленное знание, чтобы оно включало в себя решение обработчика конфликтов.When the conflict resolution algorithm processes the conflict, it returns a list of operations that must be performed (instead of conflicting changes) back to the runtime. The synchronization service then applies these operations, appropriately adjusting the remote knowledge to include a solution to the conflict handler.

Возможно, что при применении разрешения обнаруживается еще один конфликт. В этом случае новый конфликт должен быть разрешен до возобновления первоначальной обработки.It is possible that when applying permission, another conflict is detected. In this case, a new conflict must be resolved before resuming the initial processing.

Рассматривая конфликты как ответвления в истории версий статьи, разрешения конфликтов можно рассматривать как соединения - объединение двух ветвей с образованием одной точки. Таким образом, разрешения конфликтов преобразуют истории версий в DAG.Considering conflicts as branches in the history of the article’s versions, conflict resolution can be considered as connections - the union of two branches with the formation of one point. In this way, conflict resolution translates version histories into DAGs.

(b) Регистрация конфликтов(b) Conflict Records

Алгоритм регистрации конфликтов является весьма специфической разновидностью алгоритма разрешения конфликтов. Услуга синхронизации регистрирует конфликты как статьи типа ConflictRecord. Эти записи связываются с конфликтующими статьями (если сами статьи не были удалены). Каждая запись конфликта содержит: входящее изменение, вызвавшее конфликт; тип конфликта: между обновлениями, между обновлением и удалением, между удалением и обновлением, между вставками или на основе ограничения; и версию входящего изменения и знание копии, передавшего его. Зарегистрированные конфликты доступны для инспектирования и разрешения, согласно описанному ниже.The conflict registration algorithm is a very specific kind of conflict resolution algorithm. The synchronization service registers conflicts as articles of the ConflictRecord type. These entries are linked to conflicting articles (unless the articles themselves have been deleted). Each conflict record contains: an incoming change that caused the conflict; type of conflict: between updates, between updates and deletions, between deletions and updates, between inserts or based on a restriction; and the version of the incoming change and the knowledge of the copy that transmitted it. Registered conflicts are available for inspection and resolution as described below.

(с) Инспектирование и разрешения конфликтов(c) Inspection and resolution of conflicts

Услуга синхронизации обеспечивает API для приложений для проверки журнала конфликтов и для предложения разрешений конфликтов в нем. API позволяет приложению перечислять все конфликты или конфликты, связанные с данной Статьей. Он также позволяет таким приложениям разрешать зарегистрированные конфликты одним из трех способов: (1) удаленный приоритет - принятие зарегистрированного изменения и перезапись конфликтующего локального изменения; (2) локальный приоритет - игнорирование конфликтующих частей зарегистрированного изменения; и (3) предложение нового изменения - когда приложение предлагает поглощать то, что, по его мнению, разрешает конфликт. После разрешения конфликтов приложением услуга синхронизации удаляет их из журнала.The synchronization service provides an API for applications to check the conflict log and to offer conflict resolution in it. The API allows the application to list all conflicts or conflicts associated with this Article. It also allows such applications to resolve recorded conflicts in one of three ways: (1) remote priority — accepting the registered change and overwriting the conflicting local change; (2) local priority - ignoring conflicting parts of the registered change; and (3) proposing a new change - when the application offers to absorb what, in its opinion, resolves the conflict. After the application resolves conflicts, the synchronization service removes them from the log.

(d) Сходимость копий и распространение разрешений конфликтов(d) Convergence of copies and distribution of conflict resolution

В сложных сценариях синхронизации один и тот же конфликт может быть обнаружен на множественных копиях. Если это происходит, может происходить следующее: (1) конфликт может быть разрешен на одной копии, и разрешение может быть направлено на другую копию; (2) конфликт автоматически разрешается на обеих копиях; или (3) конфликт разрешается на обеих копиях вручную (посредством API инспектирования конфликтов).In complex synchronization scenarios, the same conflict can be detected on multiple copies. If this occurs, the following may occur: (1) the conflict may be resolved on one copy, and resolution may be directed to another copy; (2) the conflict is automatically resolved on both copies; or (3) a conflict is resolved on both copies manually (through the Conflict Inspection API).

Для обеспечения сходимости услуга синхронизации передает разрешения конфликтов на другие копии. Когда изменение, разрешающее конфликт, поступает на копию, услуга синхронизации автоматически находит в журнале любые записи конфликтов, которые были разрешены этим обновлением, и исключает их. В этом смысле разрешение конфликтов на одной копии связывается на всех остальных копиях.To ensure convergence, the synchronization service transfers conflict resolution to other copies. When a conflict-resolving change arrives at a copy, the synchronization service automatically finds in the log any conflict records that were resolved by this update and excludes them. In this sense, conflict resolution on one copy is linked on all other copies.

Если разные копии выбирают для разрешения одного и того же конфликта разные приоритеты, то услуга синхронизации применяет принцип связывания разрешения конфликтов и автоматически выбирает, какое из двух разрешений будет иметь приоритет над другим. Приоритетное решение выбирается детерминистическим способом, который гарантированно дает всегда одни и те же результаты (один вариант осуществления использует лексикографические сравнения ИД копий).If different copies choose different priorities to resolve the same conflict, then the synchronization service applies the principle of conflict resolution binding and automatically selects which of the two resolutions will take priority over the other. The priority solution is chosen in a deterministic way, which is guaranteed to always give the same results (one embodiment uses lexicographic comparisons of copy IDs).

Если разные копии предлагают разные «новые изменения» для одного и того же конфликта, услуга синхронизации рассматривает этот новый конфликт как особый конфликт и использует блок регистрации конфликтов для предотвращения его распространения на другие копии. Такая ситуация обычно возникает при разрешении конфликтов вручную.If different copies offer different “new changes” for the same conflict, the synchronization service considers this new conflict as a special conflict and uses the conflict registration block to prevent it from spreading to other copies. This situation usually occurs when resolving conflicts manually.

2. Синхронизация с хранилищами данных, не связанными с платформой хранения2. Synchronization with data warehouses not related to the storage platform

Согласно другому аспекту платформы хранения настоящего изобретения платформа хранения обеспечивает архитектуру для ISV, позволяющую реализовать адаптеры синхронизации, допускающие синхронизацию платформы хранения с такими известными системами, как Microsoft Exchange, AD, Hotmail и т.д. Адаптеры синхронизации имеют преимущества над многими службами синхронизации, обеспечиваемыми услугой синхронизации, что описано ниже.According to another aspect of the storage platform of the present invention, the storage platform provides an architecture for ISVs that allow synchronization adapters to be implemented that allow the storage platform to synchronize with well-known systems such as Microsoft Exchange, AD, Hotmail, etc. Synchronization adapters have advantages over many of the synchronization services provided by the synchronization service, as described below.

Несмотря на название, адаптеры синхронизации не предусматривают реализацию в виде модулей, встраиваемых в некоторую архитектуру платформы хранения. При желании «адаптер синхронизации» может представлять собой любое приложение, которое использует интерфейсы среды выполнения услуги синхронизации для получения таких услуг, как перечисление и применение изменений.Despite the name, synchronization adapters do not provide for implementation in the form of modules that are embedded in some architecture of the storage platform. If desired, the “synchronization adapter” can be any application that uses the interfaces of the synchronization service runtime to receive services such as enumerating and applying changes.

Чтобы другим было проще конфигурировать и запускать синхронизацию с данной машиной базы данных, писателям адаптеров синхронизации разрешается открывать стандартный интерфейс адаптера синхронизации, который запускает синхронизацию, заданную профилем синхронизации, который описан выше. Профиль предоставляет адаптеру информацию конфигурации, часть которой адаптеры передают среде выполнения синхронизации для управления услугами среды выполнения (например, папку, подлежащую синхронизации).To make it easier for others to configure and start synchronization of the database with this machine, synchronization adapter writers are allowed to open the standard interface of the synchronization adapter, which starts the synchronization specified by the synchronization profile described above. The profile provides the adapter with configuration information, part of which the adapters pass to the synchronization runtime to manage the services of the runtime (for example, the folder to be synchronized).

а) Службы синхронизацииa) Sync services

Услуга синхронизации предоставляет писателям адаптеров ряд служб синхронизации. До конца этого раздела удобно называть машину, на которой платформа хранения производит синхронизацию, «клиентом», а машину базы данных, не связанную с платформой хранения, с которой говорит адаптер, - «сервером».The synchronization service provides adapter writers with a number of synchronization services. Until the end of this section, it is convenient to name the machine on which the storage platform performs synchronization as “the client”, and the database machine not connected to the storage platform with which the adapter speaks as “the server”.

(1) Перечисление изменений(1) Listing Changes

На основании данных отслеживания изменений, поддерживаемых услугой синхронизации, перечисление изменений позволяет адаптерам синхронизации легко перечислять изменения, произошедшие в папке хранилища данных после последней попытки синхронизации с этим партнером.Based on the change tracking data supported by the synchronization service, enumeration of changes allows synchronization adapters to easily list the changes that have occurred in the data warehouse folder since the last attempt to synchronize with this partner.

Изменения перечисляются на основании понятия «анкера» - непрозрачной структуры, которая представляет информацию о последней синхронизации. Анкер принимает Знание от платформы хранения, что описано в последующих разделах. Адаптеры синхронизации, использующие услуги перечисления изменений, делятся на две широкие категории: использующие «сохраненные анкеры» и использующие «выданные анкеры».Changes are listed based on the concept of an anchor, an opaque structure that represents information about the latest synchronization. Anchor receives Knowledge from the storage platform, as described in the following sections. Synchronization adapters using change enumeration services fall into two broad categories: using “saved anchors” and using “issued anchors”.

Различие между ними состоит в том, где хранится информация о последней синхронизации - на клиенте или на сервере. Адаптерам часто бывает проще хранить эту информацию на клиенте - машина базы данных часто не способна удобно хранить эту информацию. С другой стороны, если несколько клиентов синхронизируются с одной и той же машиной базы данных, сохранение этой информации на клиенте неэффективно и в некоторых случаях неправильно - клиент оказывается неосведомленным об изменениях, которые другой клиент уже протолкнул на сервер. Если адаптер хочет использовать анкер, хранящийся на сервере, то адаптеру нужно подать его обратно на платформу хранения во время перечисления изменений.The difference between them is where the information about the last synchronization is stored - on the client or on the server. Adapters often find it easier to store this information on the client - the database machine is often unable to conveniently store this information. On the other hand, if several clients are synchronized with the same database machine, saving this information on the client is inefficient and in some cases incorrect - the client is not aware of the changes that the other client has already pushed to the server. If the adapter wants to use the anchor stored on the server, then the adapter needs to submit it back to the storage platform during the transfer of changes.

Чтобы платформа хранения поддерживала анкер (для локального или удаленного хранения), платформу хранения нужно уведомить об изменениях, которые были успешно применены на сервере. Эти и только эти изменения могут быть включены в анкер. В ходе перечисления изменений адаптеры синхронизации используют интерфейс квитирования, чтобы сообщать, какие изменения были успешно применены. В конце синхронизации адаптеры, использующие выданные анкеры, должны считать новый анкер (который включает в себя все успешно примененные изменения) и передать его на свою машину базы данных.In order for the storage platform to support the anchor (for local or remote storage), the storage platform must be notified of changes that have been successfully applied on the server. These and only these changes can be included in the anchor. When enumerating changes, synchronization adapters use an acknowledgment interface to report which changes have been successfully applied. At the end of synchronization, adapters using issued anchors must read the new anchor (which includes all successfully applied changes) and transfer it to their database machine.

Часто адаптеры нуждаются в сохранении данных, зависящих от адаптера, совместно со статьями, которые они вставляют в хранилище данных платформы хранения. Общими примерами таких данных являются удаленные ИД и удаленные версии (метки времени). Услуга синхронизации обеспечивает механизм хранения этих данных, и перечисление изменений обеспечивает механизм приема этих дополнительных данных совместно с возвращаемыми изменениями. Это, в большинстве случаев, исключает необходимость для адаптеров повторно запрашивать базу данных.Often adapters need to store adapter-specific data in conjunction with the articles that they insert into the storage platform data warehouse. Common examples of such data are remote IDs and remote versions (timestamps). The synchronization service provides a mechanism for storing this data, and enumeration of changes provides a mechanism for receiving this additional data together with the returned changes. This, in most cases, eliminates the need for adapters to re-query the database.

(2) Применение изменений(2) Application of changes

Применение изменений позволяет адаптерам синхронизации применять изменения, принятые от их машины базы данных, к локальной платформе хранения. Ожидается, что адаптеры преобразуют изменения в схему платформы хранения.Applying changes allows synchronization adapters to apply the changes received from their database machine to the local storage platform. Adapters are expected to translate the changes into a storage platform schema.

Основной функцией применения изменений является автоматическое обнаружение конфликтов. Как в случае синхронизации между платформами хранения, конфликт определяется как перекрывающиеся изменения, произведенные без знания друг о друге. Когда адаптеры используют применение изменений, они должны задавать анкер, относительно которого осуществляется обнаружение конфликта. Применение изменений возбуждает конфликт при обнаружении перекрывающегося локального изменения, которое не покрывается знанием адаптера. По аналогии с перечислением изменений адаптеры могут использовать либо сохраненные, либо выданные анкеры. Применение изменений поддерживает эффективное хранение метаданных, зависящих от адаптера. Такие данные могут присоединяться адаптером к применяемым изменениям и могут сохраняться услугой синхронизации. Данные могут возвращаться на следующем перечислении изменений.The main function of applying changes is automatic conflict detection. As in the case of synchronization between storage platforms, a conflict is defined as overlapping changes made without knowledge of each other. When adapters use the application of changes, they must specify the anchor against which a conflict is detected. The application of changes causes a conflict when it detects an overlapping local change that is not covered by the knowledge of the adapter. By analogy with the enumeration of changes, adapters can use either saved or issued anchors. Applying changes supports efficient storage of adapter-specific metadata. Such data can be connected by the adapter to the applied changes and can be saved by the synchronization service. Data may be returned on the following listing of changes.

(3) Разрешение конфликтов(3) Conflict Resolution

Вышеописанные механизмы разрешения конфликтов (возможности регистрации и автоматического разрешения) также доступны адаптерам синхронизации. Адаптеры синхронизации могут задавать политику для разрешения конфликтов при применении изменений. Если указано, конфликты можно передавать на указанный обработчик конфликтов и разрешать (если возможно). Конфликты также можно регистрировать. Возможно, что адаптер может обнаружить конфликт при попытке применить локальное изменение к машине базы данных. В этом случае адаптер может все равно передать конфликт в среду выполнения синхронизации для разрешения согласно политике. Кроме того, адаптеры синхронизации могут требовать, чтобы любые конфликты, обнаруженные услугой синхронизации, обратно передавались им для обработки. Это особенно удобно в случае, когда машина базы данных способна сохранять или разрешать конфликты.The conflict resolution mechanisms described above (registration and automatic resolution options) are also available for synchronization adapters. Sync adapters can set policies to resolve conflicts when changes are applied. If specified, conflicts can be passed to the specified conflict handler and resolved (if possible). Conflicts can also be recorded. It is possible that the adapter might detect a conflict when trying to apply a local change to the database machine. In this case, the adapter may still transmit the conflict to the synchronization runtime for resolution according to the policy. In addition, synchronization adapters may require that any conflicts detected by the synchronization service be sent back to them for processing. This is especially useful when the database engine is capable of storing or resolving conflicts.

b) Реализация адаптераb) adapter implementation

Хотя некоторые «адаптеры» являются просто приложениями, использующими интерфейсы среды выполнения, адаптерам разрешается реализовывать стандартные интерфейсы адаптера. Эти интерфейсы позволяют приложениям управления синхронизацией: требовать, чтобы адаптер осуществлял синхронизацию согласно данному профилю синхронизации; отменял выполняющуюся синхронизацию; принимал отчет о ходе выполнения (процент готовности) выполняющейся синхронизации.Although some “adapters” are simply applications that use runtime interfaces, adapters are allowed to implement standard adapter interfaces. These interfaces allow synchronization management applications to: require the adapter to synchronize according to a given synchronization profile; Canceled the ongoing synchronization; Received a progress report (percentage of readiness) of the synchronization in progress.

3. Безопасность3. Security

Услуга синхронизации стремится вносить как можно меньше в модель безопасности, реализованную платформой хранения. Вместо того, чтобы задавать новые права на синхронизацию, используются существующие права. В частности:The synchronization service seeks to contribute as little as possible to the security model implemented by the storage platform. Instead of setting new synchronization rights, existing rights are used. In particular:

- любой, кто может читать статью хранилища данных, может перечислять изменения к этой статье;- anyone who can read the data warehouse article can list the changes to this article;

- любой, кто может писать в статью хранилища данных, может применять изменения к этой статье; и- anyone who can write to a data warehouse article can apply changes to this article; and

- любой, кто может расширять статью хранилища данных, может связывать с этой статьей метаданные синхронизации.- anyone who can expand a data warehouse article can associate synchronization metadata with this article.

Услуга синхронизации не поддерживает защищенную информацию авторства. Когда изменение производится на копии А пользователем U и переносится на копию В, тот факт, что изменение первоначально произведено на А (или пользователем U), утрачивается. Если В переносит это изменение на копию С, это делается от имени В, а не А. Это приводит к следующему ограничению: если копии не доверено вносить в статью собственные изменения, она не может переносить изменения, сделанные другими.The synchronization service does not support protected authorship information. When a change is made to copy A by user U and transferred to copy B, the fact that the change was originally made to A (or by user U) is lost. If B transfers this change to copy C, this is done on behalf of B, not A. This leads to the following restriction: if the copy is not trusted to make its own changes to the article, it cannot transfer the changes made by others.

При инициировании услуги синхронизации это делает приложение управления синхронизацией. Услуга синхронизации подменяет идентификацию SCA и осуществляет все операции (как локально, так и удаленно) от его имени. Для примера, предположим, что пользователь U не может предписать локальной услуге синхронизации извлечь из удаленной платформы хранения изменения для статей, к которым пользователь U не имеет доступа для чтения.When initiating the synchronization service, this makes the synchronization management application. The synchronization service replaces the SCA identification and performs all operations (both locally and remotely) on its behalf. For example, suppose that user U cannot instruct the local synchronization service to retrieve changes from the remote storage platform for articles to which user U does not have read access.

4. Управляемость4. Manageability

Мониторинг распределенной общности копий является сложной задачей. Услуга синхронизации может использовать алгоритм «заметания» для сбора и распространения информации о состоянии копий. Свойства алгоритма заметания гарантируют, что информация обо всех сконфигурированных копиях, в итоге, будет собрана и что будут обнаружены сбойные (не отвечающие) копии.Monitoring distributed community of copies is challenging. The synchronization service may use the “sweep” algorithm to collect and disseminate information about the status of copies. The properties of the sweeping algorithm ensure that information about all configured copies is ultimately collected and that bad (non-responding) copies are detected.

Эта информация мониторинга в масштабе общности становится доступной каждой копии. Инструменты мониторинга можно запускать на произвольно выбранной копии, чтобы проверять эту информацию мониторинга и принимать административные решения. Любые изменения конфигурации должны производиться непосредственно на копиях, подлежащих изменению.This community-wide monitoring information is made available to each copy. Monitoring tools can be run on a randomly selected copy to verify this monitoring information and make administrative decisions. Any configuration changes must be made directly to the copies to be changed.

Н. Возможность взаимодействия с традиционными файловыми системамиH. Interoperability with traditional file systems

Как отмечено выше, платформа хранения настоящего изобретения, по меньшей мере, в некоторых вариантах осуществления предусматривает реализацию в виде неотъемлемой части системы программно-аппаратного интерфейса компьютерной системы. Например, платформа хранения настоящего изобретения может быть реализована как неотъемлемая часть операционной системы, например, принадлежащей семейству операционных систем Microsoft Windows. В этой связи API платформы хранения становится частью API операционной системы, посредством которых прикладные программы взаимодействуют с операционной системой. Таким образом, платформа хранения становится средством, с помощью которого прикладные программы сохраняют информацию на операционной системе, благодаря чему модель данных на основе статей платформы хранения заменяет традиционную файловую систему такой операционной системы. Например, будучи реализована в семействе операционных систем Microsoft Windows, платформа хранения может заменить файловую систему NTFS, реализованную в этой операционной системе. В настоящее время прикладные программы осуществляют доступ к услугам файловой системы NTFS через API Win32, открытые семейством операционных систем Windows.As noted above, the storage platform of the present invention, in at least some embodiments, provides for the implementation as an integral part of the system of the hardware-software interface of a computer system. For example, the storage platform of the present invention can be implemented as an integral part of an operating system, for example, belonging to the Microsoft Windows family of operating systems. In this regard, the storage platform API becomes part of the operating system API through which applications interact with the operating system. Thus, the storage platform becomes the means by which application programs store information on the operating system, so the data model based on the articles of the storage platform replaces the traditional file system of such an operating system. For example, being implemented in the Microsoft Windows family of operating systems, the storage platform can replace the NTFS file system implemented in this operating system. Currently, applications access the NTFS file system services through the Win32 APIs that are open by the Windows operating system family.

Понимая, однако, что полная замена файловой системы NTFS платформой хранения настоящего изобретения потребовала бы перекодирования существующих прикладных программ на основе Win32 и что такое перекодирование может быть нежелательно, было бы полезно, если бы платформа хранения настоящего изобретения обеспечивала некоторую возможность взаимодействия с существующими файловыми системами, например NTFS. Согласно одному варианту осуществления настоящего изобретения платформа хранения позволяет прикладным программам, которые опираются на модель программирования Win32, осуществлять доступ к содержимому как хранилища данных платформы хранения, так и традиционной файловой системы NTFS. Для этого платформа хранения использует соглашение именования, которое является супермножеством соглашений именования Win32, для облегчения возможности взаимодействия. Кроме того, платформа хранения поддерживает доступ к файлам и директориям, хранящимся в томе платформы хранения, через API Win32.Understanding, however, that a complete replacement of the NTFS file system with the storage platform of the present invention would require transcoding of existing Win32-based applications and that such transcoding might not be desirable, it would be useful if the storage platform of the present invention provided some interoperability with existing file systems, e.g. NTFS. According to one embodiment of the present invention, the storage platform allows applications that rely on the Win32 programming model to access the contents of both the storage platform data store and the traditional NTFS file system. For this, the storage platform uses a naming convention, which is a superset of Win32 naming conventions, to facilitate interoperability. In addition, the storage platform supports access to files and directories stored in the volume of the storage platform through the Win32 API.

1. Модель возможности взаимодействия1. Interaction model

Согласно этому аспекту настоящего изобретения и согласно рассмотренному выше иллюстративному варианту осуществления платформа хранения реализует одно пространство имен, в котором могут быть организованы нефайловые и файловые статьи. В этой модели достигаются следующие преимущества:According to this aspect of the present invention, and according to the above illustrative embodiment, the storage platform implements one namespace in which non-file and file entries can be organized. The following benefits are achieved in this model:

1. Папки в хранилище данных могут содержать как файловые, так и нефайловые статьи, тем самым представляя единое пространство имен для файловых и схематизированных данных. Кроме того, она также обеспечивает универсальную модель безопасности, совместного использования и администрирования для всех пользовательских данных.1. Folders in the data warehouse can contain both file and non-file articles, thereby representing a single namespace for file and schematized data. In addition, it also provides a universal security, sharing and administration model for all user data.

2. Поскольку файловые и нефайловые статьи доступны с использованием API платформы хранения и этот подход не предусматривает применение каких-либо особых правил для файлов, он представляет разработчикам приложений более ясную модель программирования для работы.2. Since file and non-file articles are accessible using the storage platform API and this approach does not provide for the application of any special rules for files, it provides application developers with a clearer programming model for work.

3. Все операции пространства имен проходят через платформу хранения и потому обрабатываются синхронно. Важно отметить, что глубокое продвижение свойств (выводимых из содержимого файлов) по-прежнему происходит асинхронно, но синхронные операции обеспечивают гораздо более предсказуемую среду для пользователей и приложений.3. All namespace operations go through the storage platform and are therefore processed synchronously. It is important to note that the deep promotion of properties (output from the contents of files) still occurs asynchronously, but synchronous operations provide a much more predictable environment for users and applications.

Вследствие этой модели, согласно данному варианту осуществления, могут не предоставляться возможности поиска по источникам данных, которые не мигрируют в хранилище данных платформы хранения. Они включают в себя сменные носители, удаленные серверы и файлы на локальном диске. Обеспечен адаптер синхронизации, который объявляет статьи-посредники (сокращенные клавиатурные команды + продвинутые метаданные) в платформе хранения для статей, находящихся в сторонних файловых системах. Статьи-посредники не пытаются выдавать себя за файлы либо в терминах иерархии пространства имен источника данных, либо в терминах безопасности.Due to this model, according to this embodiment, it may not be possible to search for data sources that do not migrate to the storage platform data warehouse. These include removable media, remote servers, and files on the local drive. A synchronization adapter is provided that announces intermediary articles (abbreviated keyboard commands + advanced metadata) in the storage platform for articles located on third-party file systems. Mediation articles do not attempt to impersonate files either in terms of the hierarchy of the data source namespace or in terms of security.

Симметрия, достигнутая в пространстве имен и модели программирования между файловым и нефайловым контентом, обеспечивает приложениям лучший путь для перемещения контента из файловых систем в более структурированные статьи в хранилище данных платформы хранения с течением времени. Благодаря обеспечению родного типа статьи «файл» в хранилище данных платформы хранения прикладные программы могут переносить данные файлов в платформу хранения, в то же время сохраняя возможность манипулировать этими данными посредством Win32. В конце концов, прикладные программы смогут полностью перейти к API платформы хранения и структурировать свои данные в терминах статей платформы хранения, а не файлов.Symmetry achieved in the namespace and programming model between file and non-file content provides applications with a better way to move content from file systems to more structured articles in the storage platform data warehouse over time. By providing a native type of “file” article in the storage platform data warehouse, applications can transfer file data to the storage platform, while still retaining the ability to manipulate this data through Win32. In the end, applications can go all the way to the storage platform API and structure their data in terms of storage platform articles rather than files.

2. Особенности хранилища данных2. Data Warehouse Features

Для обеспечения нужного уровня взаимодействия, согласно одному варианту осуществления, реализованы следующие особенности хранилища данных платформы хранения.To provide the desired level of interaction, according to one embodiment, the following features of the storage platform data warehouse are implemented.

а) Не томa) Not that

Хранилище данных платформы хранения не открывается как отдельный том файловой системы. Платформа хранения усиливает «потоки файлов», непосредственно базирующиеся на NTFS. Таким образом, формат «на диске» не подвергается изменениям, что избавляет от необходимости открывать платформу хранения как новую файловую систему на уровне томов.The storage platform data warehouse does not open as a separate file system volume. The storage platform leverages NTFS-based file streams. Thus, the “on disk” format is not subject to change, which eliminates the need to open the storage platform as a new file system at the volume level.

Вместо этого строится хранилище данных (пространство имен), соответствующее тому NTFS. База данных и «потоки файлов», резервирующие эту часть пространство имен, находятся в томе NTFS, с которым связано хранилище данных платформы хранения. Также обеспечено хранилище данных, соответствующее системному тому.Instead, a data warehouse (namespace) is built corresponding to the NTFS volume. The database and file streams that reserve this part of the namespace are located in the NTFS volume that the storage platform data warehouse is associated with. A data warehouse corresponding to the system volume is also provided.

b) Структура хранилищаb) Storage structure

Структуру хранилища лучше всего проиллюстрировать на примере. Рассмотрим, например, дерево директории на системном томе машины под названием HomeMachine, как показано на фиг.16. Согласно с признаком возможности взаимодействия с файловой системой, согласно настоящему изобретению, соответствующим c:\привод, существует хранилище данных платформы хранения, открытое API Win32 через совместно используемое UNC, например, "WinFSOnC". Это делает соответствующее хранилище данных доступным через следующее имя UNC: \\HomeMachine\WinFSOnC.The storage structure is best illustrated with an example. Consider, for example, a directory tree on a system volume of a machine called HomeMachine , as shown in FIG. According to the sign of the possibility of interacting with the file system according to the present invention corresponding to c: \ drive, there is a storage platform data store open by the Win32 API via a shared UNC, for example, “WinFSOnC”. This makes the corresponding data store accessible through the following UNC name: \\ HomeMachine \ WinFSOnC.

В данном варианте осуществления файлы и/или папки должны в явном виде переходить из NTFS в платформу хранения. Поэтому, если пользователь желает переместить папку My Documents в хранилище данных платформы хранения, чтобы воспользоваться всеми дополнительными особенностями поиска/категоризации, обеспечиваемыми платформой хранения, иерархия будет выглядеть, как показано на фиг.17. Важно заметить, что эти папки действительно перемещаются в данном примере. Надо также отметить, что пространство имен перемещается в платформу хранения, фактические потоки переименовываются как «потоки файлов» с соответствующими указателями, подключенными в платформе хранения.In this embodiment, files and / or folders must explicitly migrate from NTFS to the storage platform. Therefore, if the user wishes to move the My Documents folder to the storage platform data warehouse in order to take advantage of all the additional search / categorization features provided by the storage platform, the hierarchy will look as shown in FIG. It is important to note that these folders really move in this example. It should also be noted that the namespace moves to the storage platform, the actual streams are renamed as “file streams” with the corresponding pointers connected in the storage platform.

с) Не все файлы мигрируютc) Not all files migrate

Файлы, которые соответствуют пользовательским данным или которые нуждаются в поиске/категоризации, обеспечиваемым платформой хранения, являются кандидатами на миграцию в хранилище данных платформы хранения. Предпочтительно, для ограничения вопросов совместимости прикладной программы с платформой хранения, набор файлов, которые мигрируют в платформу хранения настоящего изобретения, в контексте операционной системы Microsft Windows, ограничивается файлами в папке MyDocuments, Internet Explorer (IE) Favorites, IE History и файлами Desktop.ini в директории Documents and Settings. Предпочтительно, миграция системных файлов Windows не разрешена.Files that match user data or that need to be searched / categorized by the storage platform are candidates for migration to the storage platform data warehouse. Preferably, to limit the compatibility of the application with the storage platform, the set of files that migrate to the storage platform of the present invention, in the context of the Microsft Windows operating system, is limited to the files in the MyDocuments, Internet Explorer (IE) Favorites, IE History and Desktop.ini files in the Documents and Settings directory. Preferably, the migration of Windows system files is not allowed.

d) Доступ из пространства имен NTFS к файлам платформы храненияd) Access from the NTFS namespace to storage platform files

Согласно описанному здесь варианту осуществления желательно, чтобы файлы, мигрировавшие в платформу хранения, не были доступны через пространство имен NTFS даже, если фактические потоки файлов хранятся в NTFS. Это позволяет избежать сложных вопросов блокировки и безопасности, возникающих из многоголовой реализации.According to an embodiment described herein, it is desirable that files migrating to the storage platform are not accessible through the NTFS namespace even if the actual file streams are stored in NTFS. This avoids the complex blocking and security issues that arise from a multi-headed implementation.

е) Ожидаемые буквы пространства имен/приводаe) The expected namespace / drive letters

Доступ к файлам и папкам в платформе хранения обеспечивается через имя UNC в виде \\<имя машины>\<совместно используемое имя Winfs>. Для класса приложений, которым для работы требуются буквы приводов, буква привода может отображаться в это имя UNC.Access to files and folders in the storage platform is provided through the UNC name in the form \\ <machine name> \ <shared name Winfs>. For an application class that requires drive letters to operate, the drive letter can be mapped to this UNC name.

I. API ПЛАТФОРМЫ ХРАНЕНИЯI. STORAGE PLATFORM API

Согласно отмеченному выше, платформа хранения содержит API, который позволяет прикладным программам осуществлять доступ к особенностям и возможностям платформы хранения, рассмотренной выше, и осуществлять доступ к статьям, хранящимся в хранилище данных. В этом разделе описан один вариант осуществления API платформы хранения для платформы хранения настоящего изобретения.As noted above, the storage platform contains an API that allows applications to access the features and capabilities of the storage platform discussed above and access articles stored in the data warehouse. This section describes one embodiment of a storage platform API for a storage platform of the present invention.

На фиг.19 показана основная архитектура API платформы хранения, согласно данному варианту осуществления. API платформы хранения использует SQLClient 1900 для разговора с локальным хранилищем данных 302, и также может использовать SQLClient 1900 для разговора с удаленным хранилищем данных (например, хранилищем данных 340). Локальное хранилище 302 также может разговаривать с удаленным хранилищем данных 340 с использованием либо DQP (процессора распределенного запроса) или посредством вышеописанной услуга синхронизации ("Sync") платформы хранения. API 322 платформы хранения также действует как API моста для извещений хранилища данных, передавая подписки приложения машине 332 извещения и маршрутизируя извещения на приложение (например, приложение 350a, 350b или 350c), что также описано выше. В одном варианте осуществления, API 322 платформы хранения может также задавать ограниченную архитектуру «провайдер», так чтобы она могла осуществлять доступ к данным в Microsoft Exchange и AD.FIG. 19 shows a basic architecture of a storage platform API according to this embodiment. The storage platform API uses the SQLClient 1900 to talk to the local data store 302, and can also use the SQLClient 1900 to talk to the remote data store (e.g., data store 340). Local storage 302 can also talk to remote data storage 340 using either DQP (Distributed Request Processor) or through the Sync service of the storage platform described above. Storage platform API 322 also acts as a bridge API for data warehouse notifications by passing application subscriptions to notification engine 332 and routing notifications to the application (e.g., application 350a, 350b or 350c), which is also described above. In one embodiment, storage platform API 322 may also define a limited provider architecture so that it can access data in Microsoft Exchange and AD.

1. Обзор1. Overview

Механизм доступа к данным согласно данному варианту осуществления API платформы хранения настоящего изобретения относится к четырем областям: запрос, навигация, действия, события.The data access mechanism according to this embodiment of the storage platform API of the present invention relates to four areas: request, navigation, actions, events.

ЗапросInquiry

Согласно одному варианту осуществления, хранилище данных платформы хранения реализовано на машине 314 реляционной базы данных; в результате, полная выразительная сила языка SQL присуща платформе хранения. Объекты запроса высокого уровня обеспечивают упрощенную модель для запрашивания хранилища, но могут не инкапсулировать полную выразительную силу хранения.According to one embodiment, the storage platform data warehouse is implemented on a relational database engine 314; as a result, the full expressive power of SQL is inherent in the storage platform. High-level query objects provide a simplified model for querying storage, but may not encapsulate the full expressive power of storage.

НавигацияNavigation

Модель данных платформы хранения строит богатую, расширяемую систему типов на абстракциях нижележащей базы данных. Для разработчика, данные платформы хранения являются сетью статей. API платформы хранения обеспечивает навигацию от статьи к статье посредством фильтрации, отношений, папок и т.д. Это более высокий уровень абстракции, чем базовые запросы SQL; в то же время, это допускает богатые возможности фильтрации и навигации для использования с привычными шаблонами кодирования CLR.The storage platform data model builds a rich, extensible type system on the abstractions of the underlying database. For the developer, storage platform data is a network of articles. The storage platform API provides navigation from article to article through filtering, relationships, folders, etc. This is a higher level of abstraction than basic SQL queries; at the same time, it allows rich filtering and navigation capabilities for use with familiar CLR coding patterns.

ДействияActions

API платформы хранения открывает общие действия на всех статьях - Create, Delete, Update; они открываются как методы на объектах. Кроме того, действия, зависящие от домена, например, SendMail, CheckFreeBusy, и т.д. также доступны как методы. Структура API использует строго определенные шаблоны, которые ISV могут использовать для добавления значения путем задания дополнительных действий.Storage platform API opens common actions on all articles - Create, Delete, Update; they open as methods on objects. In addition, domain-specific actions like SendMail, CheckFreeBusy, etc. also available as methods. The API structure uses strictly defined patterns that ISVs can use to add value by setting additional actions.

СобытияDevelopments

Данные в платформе хранения являются динамическими. Чтобы приложения могли реагировать на изменение данных в хранилище, API открывает богатые возможности формирования событий, подписки и извещения.The data in the storage platform is dynamic. To enable applications to respond to data changes in the repository, the API provides rich opportunities for event generation, subscription and notifications.

2. Именование и области действия2. Naming and scopes

Полезно различать пространство имен и именование. Термин «пространство имен», в обычном использовании, означает множество всех имен, доступных в некоторой системе. Система может быть схемой XML, программой, сетью, множеством всех сайтов ftp (и их содержимого) и т.д. «Именование» - это процесс или алгоритм, используемый для присвоения уникальных имен всем сущностям, представляющим интерес в пространстве имен. Таким образом, именование представляет интерес, поскольку желательно однозначно ссылаться на данный элемент в пространстве имен. Таким образом, используемый термин "пространство имен" означает множество всех имен, доступных во всех экземплярах платформы хранения в универсуме. Статьи называются сущностями в пространстве имен платформы хранения. Соглашение именования UNC используется для обеспечения уникальности имен статей. Каждая статья в каждом хранилище платформы хранения в универсуме адресуема по имени UNC.It is useful to distinguish between namespace and naming. The term "namespace", in common use, means the set of all names available on some system. A system can be an XML schema, a program, a network, the set of all ftp sites (and their contents), etc. Naming is a process or algorithm used to assign unique names to all entities of interest in a namespace. Thus, naming is of interest because it is desirable to uniquely refer to a given element in the namespace. Thus, the term “namespace” is used to mean the set of all names available in all instances of the storage platform in the universe. Articles are called entities in the storage platform namespace. The UNC naming convention is used to ensure that article names are unique. Each article in each repository storage platform repository in the universe is addressed by UNC.

Наивысшим уровнем организации в пространстве имен платформы хранения является «услуга» - которая является просто экземпляром платформы хранения. Следующим уровнем организации является «том». Том - это наибольший автономный контейнер статей. Каждый экземпляр платформы хранения содержит один или более томов. В томе существуют «статьи». Статьи являются единицами данных в платформе хранения.The highest level of organization in the storage platform namespace is the “service” - which is simply an instance of the storage platform. The next level of organization is the “volume”. Tom is the largest standalone article container. Each storage platform instance contains one or more volumes. There are “articles” in the volume. Articles are data units in a storage platform.

Данные в реальном мире почти всегда организованы согласно некоторой системе, которая имеет смысл в данном домене. На более низком уровне все такие схемы организации данных представляют идею деления универсального множества наших данных в поименованные группы. Согласно рассмотренному выше, это понятие моделируется в платформе хранения посредством понятия «папки». Папка является особым типом папки; существует 2 типа папок: Папки включения и Виртуальные папки.Data in the real world is almost always organized according to some system that makes sense in a given domain. At a lower level, all such data organization schemes represent the idea of dividing the universal set of our data into named groups. As discussed above, this concept is modeled in the storage platform through the concept of a “folder”. A folder is a special type of folder; There are 2 types of folders: Power Folders and Virtual Folders.

Согласно фиг.18 Папка включения - это статья, которая содержит отношения поддержки к другим статьям и является эквивалентным общего понятия папки файловой системы. Каждая статья «содержится» в, по меньшей мере, одну папку включения.18, an inclusion folder is an article that contains support relationships for other articles and is equivalent to the general concept of a file system folder. Each article is “contained” in at least one inclusion folder.

Виртуальная папка - это более динамический способ организации коллекции статей; это просто имя, данное множеству статей - множество либо перечисляется в явном виде, либо задается посредством запроса. Виртуальная папка сама является статьей и может рассматриваться как представляющая множество отношений (не поддержки) к множеству статей.A virtual folder is a more dynamic way to organize a collection of articles; it’s just the name given to many articles - the set is either listed explicitly or specified by query. A virtual folder itself is an article and can be considered as representing many relationships (not support) to many articles.

Иногда существует необходимость моделировать идею более тесного включения; например, документ Word, внедренный в сообщение электронной почты, в этом смысле, более тесно связан со своим контейнером, чем, например, файл, содержащийся в папке. Эта идея выражается понятием внедренных статей. Внедренная статья имеет отношение особого рода, которое ссылается на другую статью; ссылочную статью можно привязывать или иначе манипулировать только в контексте содержащей статьи.Sometimes there is a need to model the idea of closer inclusion; for example, a Word document embedded in an email message, in this sense, is more closely related to its container than, for example, a file contained in a folder. This idea is expressed by the concept of embedded articles. An embedded article has a special kind of relationship that refers to another article; A reference article can be anchored or otherwise manipulated only in the context of the containing article.

Наконец, платформа хранения обеспечивает понятие категорий как способ классификации статей и элементов. С каждой(ым) статьей или элементом в платформе хранения может быть связана одна или несколько категорий. Категория, в сущности, является просто именем, присвоенным статье/категории. Это имя можно использовать в поисках. Модель данных платформы хранения позволяет задавать иерархию категорий, и, таким образом, обеспечивать древовидную классификацию данных.Finally, the storage platform provides the concept of categories as a way to classify articles and items. One or more categories may be associated with each article or item in the storage platform. A category, in essence, is simply the name assigned to the article / category. This name can be used in searches. The data model of the storage platform allows you to specify a hierarchy of categories, and thus provide a tree-like classification of data.

Однозначное имя статьи представляет собой триплет: (<имя услуги>, <ИД тома>, <ИД статьи>). Некоторые статьи (в частности, папки и виртуальные папки) являются коллекциями других статей. Это дает возможность идентифицировать статьи альтернативным способом: (<имя услуги>, <ИД тома>, <путь к статье>).The unique name of the article is a triple: (<service name>, <volume ID>, <article ID>). Some articles (in particular folders and virtual folders) are collections of other articles. This makes it possible to identify articles in an alternative way: (<service name>, <volume ID>, <path to article>).

Имена платформы хранения включают в себя обозначение контекста услуги: контекст услуги это имя, которое отображается в пару (<имя тома>, <путь>). Он идентифицирует статью или множество статей - например, папку, виртуальную папку, и т.д. Благодаря понятию контекстов услуги, имя UNC для любой статьи в пространстве имен платформы хранения становится:Storage platform names include a service context designation: a service context is a name that maps to a pair (<volume name>, <path>). It identifies an article or many articles - for example, a folder, virtual folder, etc. Thanks to the concept of service contexts, the UNC name for any entry in the storage platform namespace becomes:

\\<имя услуги>\<контекст услуги>\<путь к статье>.\\ <service name> \ <service context> \ <article path>.

Пользователи могут создавать и удалять контексты услуги. Кроме того, корневая директория в каждом томе имеет заранее заданный контекст: volume-name$.Users can create and delete service contexts. In addition, the root directory in each volume has a predefined context: volume-name $.

ItemContext определяет область действия запроса (например, операции Find) путем ограничения результатов, возвращаемых этими статьями, которые существуют на указанном пути.An ItemContext defines the scope of a query (for example, a Find operation) by restricting the results returned by these articles that exist on the specified path.

3. Компоненты API платформы хранения3. Storage Platform API Components

На фиг.20 схематически представлены различные компоненты API платформы хранения согласно данному варианту осуществления изобретения. API платформы хранения состоит из следующих компонентов: (1) классов данных 2002, которые представляют типы элементов и статей платформы хранения, (2) структуры среды выполнения 2004, которая регулирует живучесть объекта и обеспечивает классы поддержки 2006; и (3) инструменты 2008, которые используются для генерации классов CLR из схем платформы хранения.20 schematically illustrates various components of a storage platform API according to this embodiment of the invention. The storage platform API consists of the following components: (1) data classes 2002, which represent the types of elements and articles of the storage platform, (2) the structure of the 2004 runtime environment, which regulates the survivability of an object and provides support classes 2006; and (3) 2008 tools that are used to generate CLR classes from storage platform schemas.

Согласно одному аспекту настоящего изобретения в среде разработки автор схемы передает документ 2010 схемы и код для методов 2012 домена набору инструментов 2008 среды разработки API платформы хранения. Эти инструменты генерируют классы данных 2002 клиентской стороны и сохраняют схему 2014 и сохраняют определения 2016 классов для этой схемы. «Доменом» называется конкретная схема; например, мы говорим о методах домена, но не о классах в Схеме контактов, и т.д. Эти классы данных 2002 используются разработчиком приложения в среде выполнения совместно с классами 2006 структуры среды выполнения API платформы хранения для манипулирования данными платформы хранения.According to one aspect of the present invention, in a development environment, a schema author submits a schema document 2010 and code for domain methods 2012 to a toolbox 2008 of a storage platform API development environment. These tools generate client-side data classes 2002 and save the 2014 schema and save the 2016 class definitions for this schema. A “domain” is a specific scheme; for example, we are talking about domain methods, but not about classes in the Contact Scheme, etc. These 2002 data classes are used by the application developer in the runtime in conjunction with the 2006 storage platform API runtime structure classes to manipulate the storage platform data.

В целях иллюстрации различных аспектов API платформы хранения настоящего изобретения представлены примеры, основанные на иллюстративной Схеме контактов. Графическое представление этой иллюстративной схемы показано на фиг.21A и 21B.In order to illustrate various aspects of the storage platform API of the present invention, examples based on an illustrative Contact Diagram are provided. A graphical representation of this illustrative diagram is shown in FIGS. 21A and 21B.

4. Классы данных4. Data classes

Согласно аспекту настоящего изобретения каждый тип статьи, расширения статьи и элемента, а также каждое отношение в хранилище данных платформы хранения имеет соответствующий класс в API платформы хранения. Грубо говоря, поля типа отображаются в поля класса. Каждая статья, расширение статьи и элемент в платформе хранения доступна(о) как объект соответствующего класса в API платформы хранения. Разработчик может делать запрос на создание, изменение или удаление этих объектов.According to an aspect of the present invention, each type of article, article and item extension, and also each relation in the storage platform data warehouse has a corresponding class in the storage platform API. Roughly speaking, type fields are mapped to class fields. Each article, article extension, and item in the storage platform is available (o) as an object of the corresponding class in the storage platform API. The developer can make a request to create, modify or delete these objects.

Платформа хранения содержит начальное множество схем. Каждая схема задает множество типов статьи и элемента и множество отношений. Ниже приведен один вариант осуществления алгоритма для генерации классов данных из этих схемных сущностей:The storage platform contains an initial set of circuits. Each schema defines many types of article and element and many relationships. The following is one embodiment of an algorithm for generating data classes from these schematic entities:

Для схемы S:For circuit S:

Для каждой статьи I в S генерируется класс названием System.Storage.S.I. Этот класс имеет следующие члены:For each article I in S, a class is generated called System.Storage.S.I. This class has the following members:

- Перегруженные конструкторы, включая конструкторы, позволяющие задавать начальную папку и имя новой статьи.- Overloaded constructors, including constructors that allow you to specify the initial folder and the name of the new article.

- Свойство каждого поля в I. Если поле является многозначным, свойство будет коллекцией соответствующего типа элемента.- The property of each field in I. If the field is multi-valued, the property will be a collection of the corresponding element type.

- Перегруженный статический метод для нахождения множественных статей, отвечающих фильтру (например, метод под названием "FindAll").- An overloaded static method for finding multiple articles matching a filter (for example, a method called "FindAll").

- Перегруженный статический метод для нахождения единичной статьи, отвечающей фильтру (например, метод под названием "FindOne").- Overloaded static method to find a single article matching the filter (for example, a method called "FindOne").

- Статический метод для нахождения статьи по ее идентификатору (например, метод под названием "FindByID").- A static method for finding an article by its identifier (for example, a method called "FindByID").

- Статический метод для нахождения статьи по ее имени относительно ItemContext (например, метод под названием "FindByName").- A static method for finding an article by its name relative to ItemContext (for example, a method called "FindByName").

- Метод для сохранения изменений статьи (например, метод под названием "Update").- A method for saving article changes (for example, a method called "Update").

- Перегруженные статические методы Create для создания новых экземпляров статьи. Эти методы позволяют различными способами задавать начальную папку статьи.- Overloaded Create static methods to create new article instances. These methods allow you to set the initial folder of the article in various ways.

Для каждого элемента Е в S генерируется класс под названием System.Storage.S.E. Этот класс имеет следующие члены:For each element E in S, a class called System.Storage.S.E is generated. This class has the following members:

- Свойство каждого поля в Е. Если поле является многозначным, свойство будет коллекцией соответствующего типа элемента.- The property of each field in E. If the field is multi-valued, the property will be a collection of the corresponding element type.

Для каждого элемента Е в S генерируется класс под названием System.Storage.S.Ecollection. Этот класс следует общим руководящим принципам структуры. NET для сильно типизированной коллекции классов. Для типов элементов на основе отношений этот класс также будет включать в себя следующие члены:For each element E in S, a class called System.Storage.S.Ecollection is generated. This class follows the general guidelines of the structure. NET for a strongly typed collection of classes. For relationship-based item types, this class will also include the following members:

- Перегруженный метод для нахождения множественных объектов статьи, которые отвечают фильтру, который неявно включает в себя статью, в которой коллекция играет роль источника. Перегрузки включают в себя некоторые допускающие фильтрацию на основании подтипа статьи (например, метод под названием "FindAllTargetItems").- An overloaded method for finding multiple article objects that correspond to a filter that implicitly includes an article in which the collection plays the role of a source. Overloads include some that can be filtered based on the subtype of the article (for example, a method called "FindAllTargetItems").

- Перегруженный метод для нахождения объектов типа вложенного элемента, которые отвечают фильтру, который неявно включает в себя статью, в которой коллекция играет роль источника (например, метод под названием "FindAllRelationships").- An overloaded method for finding objects of the type of a nested element that correspond to a filter, which implicitly includes an article in which the collection plays the role of a source (for example, a method called "FindAllRelationships").

- Перегруженный метод для нахождения объектов типа вложенного элемента, которые отвечают фильтру, который неявно включает в себя статью, в которой коллекция играет роль источника (например, метод под названием "FindAllRelationshipsForTarget").- An overloaded method for finding objects of the type of a nested element that correspond to a filter, which implicitly includes an article in which the collection acts as a source (for example, a method called "FindAllRelationshipsForTarget").

- Перегруженный метод для нахождения единичного объекта типа вложенного элемента, который отвечает фильтру, который неявно включает в себя статью, в которой коллекция играет роль источника (например, метод под названием "FindOneRelationship").- An overloaded method for finding a single object such as a nested element that matches a filter that implicitly includes an article in which the collection acts as a source (for example, a method called "FindOneRelationship").

- Перегруженный метод для нахождения единичного объекта типа вложенного элемента, которые отвечают фильтру, который неявно включает в себя статью, в которой коллекция играет роль источника (например, метод под названием "FindOneRelationshipForTarget").- An overloaded method for finding a single object such as a nested element that matches a filter that implicitly includes an article in which the collection acts as a source (for example, a method called "FindOneRelationshipForTarget").

Для отношения R в S генерируется класс под названием System.Storage.S.R. Этот класс имеет один или два подкласса в зависимости от того, если роли одного или более отношений указывают поле концевой точки.For the R relation, a class called System.Storage.S.R is generated in S. This class has one or two subclasses, depending on if the roles of one or more relationships indicate the endpoint field.

Классы также генерируются таким образом для каждого Расширения статьи, которое было создано.Classes are also generated this way for each Article Extension that was created.

Классы данных существуют в пространстве имен System.Storage.<имя схемы>, где <имя схемы> - это имя соответствующей схемы, например, Contacts, Files и т.д. Например, все классы, соответствующие Схеме контактов, находятся в пространстве имен System.Storage.Contacts.Data classes exist in the System.Storage namespace. <Schema name>, where <schema name> is the name of the corresponding schema, for example, Contacts, Files, etc. For example, all classes that correspond to the Contact Schema are in the System.Storage.Contacts namespace.

Например, согласно фиг.21A и 21B, схема контактов дает следующие классы, содержащиеся в пространстве имен System.Storage.Contact:For example, according to FIGS. 21A and 21B, the contact diagram gives the following classes contained in the System.Storage.Contact namespace:

- Статьи: Item, Folder, WellKnownFolder, LocalMachineDataFolder, UserDataFolder, Principal, Service, GroupService, PersonService, PresenceService, ContactService, ADService, Person, User, Group, Organization, HouseHold- Articles: Item, Folder, WellKnownFolder, LocalMachineDataFolder, UserDataFolder, Principal, Service, GroupService, PersonService, PresenceService, ContactService, ADService, Person, User, Group, Organization, HouseHold

- Элементы: NestedElementBase, NestedElement, IdentityKey, SecurityID, EAddress, ContactEAddress, TelehoneNumber, SMTPEAddress, InstantMessagingAddress, Template, Profile, FullName, FamilyEvent, BasicPresence, WindowsPresence, Relationship, TemplateRelationship, LocationRelationship, FamilyEventLocationRelationship, HouseHoldLocationRelationship, RoleOccupancy, EmployeeData, GroupMemberShip, OrganizationLocationRelationship, HouseHoldMemberData, FamilyData, SpouseData, ChildData- Elements: NestedElementBase, NestedElement, IdentityKey, SecurityID, EAddress, ContactEAddress, TelehoneNumber, SMTPEAddress, InstantMessagingAddress, Template, Profile, FullName, FamilyEvent, BasicPresence, WindowsPresence, Relationship, TemplateRelationship, Relation, Relation, Relation, Relation, Relation, Relation, Relation, Relation , HouseHoldMemberData, FamilyData, SpouseData, ChildData

В качестве следующего примера подробная структура типа Person, заданного в Схеме контактов, показана ниже в виде XML:As the following example, the detailed structure of the Person type specified in the Contact Scheme is shown below in XML:

<Type Name="Person" MajorVersion="1" MinorVersion="0"<Type Name = "Person" MajorVersion = "1" MinorVersion = "0"

ExtendsType="Core.Principal" ExtendsVersion=”1"/>ExtendsType = "Core.Principal" ExtendsVersion = ”1" />

<Field Name="Birthdate" Type="the storage<Field Name = "Birthdate" Type = "the storage

platformTypes.datetime" Nullable="true"platformTypes.datetime "Nullable =" true "

TypeMajorVersion="1"/>TypeMajorVersion = "1" />

<Field Name="Gender" Type="Base.CategoryRef"<Field Name = "Gender" Type = "Base.CategoryRef"

Nullable="true"MultiValued="false"Nullable = "true" MultiValued = "false"

TypeMajorVersion="1"/>TypeMajorVersion = "1" />

<Field Name="PersonalNames" Type="Contact.FullName"<Field Name = "PersonalNames" Type = "Contact.FullName"

Nullable="true" MultiValued="true"Nullable = "true" MultiValued = "true"

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="PersonalEAddresses" Type="Core.EAddress"<Field Name = "PersonalEAddresses" Type = "Core.EAddress"

Nullable="true" MultiValued="true"Nullable = "true" MultiValued = "true"

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="PersonalPostalAddresses"<Field Name = "PersonalPostalAddresses"

Type="Core.PostalAddress" Nullable="true"Type = "Core.PostalAddress" Nullable = "true"

MultiValued="true" TypeMajorVersion="1"/>MultiValued = "true" TypeMajorVersion = "1" />

<Field Name="PersonalPicture" Type="the storage<Field Name = "PersonalPicture" Type = "the storage

platformTypes.image" Nullable="true"platformTypes.image "Nullable =" true "

TypeMajorVersion="1"/>TypeMajorVersion = "1" />

<Field Name="Notes" Type="Core.RichText" Nullable="true"<Field Name = "Notes" Type = "Core.RichText" Nullable = "true"

MultiValued="true" TypeMajorVersion="1”/>MultiValued = "true" TypeMajorVersion = "1” />

<Field Name="Profession" Type="Base.CategoryRef"<Field Name = "Profession" Type = "Base.CategoryRef"

Nullable="true" MultiValued="true"Nullable = "true" MultiValued = "true"

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="DataSource" Type="Base.IdentityKey"<Field Name = "DataSource" Type = "Base.IdentityKey"

Nullable="true"MultiValued="true"Nullable = "true" MultiValued = "true"

TypeMajorVersion="1"/>TypeMajorVersion = "1" />

<Field Name="ExpirationDate" Type="the storage<Field Name = "ExpirationDate" Type = "the storage

platformTypes.datetime" Nullable="true"platformTypes.datetime "Nullable =" true "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="HasAllAddressBookData" Type="the storage<Field Name = "HasAllAddressBookData" Type = "the storage

platformTypes.bit" Nullable="true"platformTypes.bit "Nullable =" true "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="EmployeeOf" Type="Contact.EmployeeData"<Field Name = "EmployeeOf" Type = "Contact.EmployeeData"

Nullable="true" MultiValued="true"Nullable = "true" MultiValued = "true"

TypeMajorVersion="1"/>TypeMajorVersion = "1" />

</Type></Type>

Этот тип порождает следующий класс (показаны только публичные члены):This type spawns the following class (only public members are shown):

partial public class Person:partial public class Person:

System.Storage.Core.Principal,System.Storage.Core.Principal,

System.Windows.Data.IDataUnitSystem.Windows.Data.IDataUnit

{{

public System.Data.SqlTypes.SqlDateTimepublic System.Data.SqlTypes.SqlDateTime

Birthdate {get; set;}Birthdate {get; set;}

public System.Storage.Base.CategoryRefpublic System.Storage.Base.CategoryRef

Gender {get; set;}Gender {get; set;}

public System.Storage.Contact.FullNameCollectionpublic System.Storage.Contact.FullNameCollection

PersonalNames {get;}PersonalNames {get;}

public System.Storage.Core.EAddressCollectionpublic System.Storage.Core.EAddressCollection

PersonalEAddresses {get;}PersonalEAddresses {get;}

public System.Storage.Core.PostalAddressCollectionpublic System.Storage.Core.PostalAddressCollection

PersonalPostalAddresses {get;}PersonalPostalAddresses {get;}

public System.Data.SqlTypes.SqlBinarypublic System.Data.SqlTypes.SqlBinary

PersonalPicture {get; set;}PersonalPicture {get; set;}

public System.Storage.Core.RichTextCollectionpublic System.Storage.Core.RichTextCollection

Notes {get;)Notes {get;)

public System.Storage.Base.CategoryRefCollectionpublic System.Storage.Base.CategoryRefCollection

Profession {get;}Profession {get;}

public System.Storage.Base.IdentityKeyCollectionpublic System.Storage.Base.IdentityKeyCollection

DataSource {get;}DataSource {get;}

public System.Data.SqlTypes.SqlDateTimepublic System.Data.SqlTypes.SqlDateTime

Expiration Date {get; set;}Expiration Date {get; set;}

public System.Data.SqlTypes.SqlBooleanpublic System.Data.SqlTypes.SqlBoolean

HasAllAddressBookData {get; set;}HasAllAddressBookData {get; set;}

public System.Storage.Contact.EmployeeDataCollectionpublic System.Storage.Contact.EmployeeDataCollection

EmployeeOf {get;}EmployeeOf {get;}

public Person();public Person ();

public Person(System.Storage.Base.Folder folder, string name);public Person (System.Storage.Base.Folder folder, string name);

public static new System.Storage.FindResultpublic static new System.Storage.FindResult

FindAll(System.Storage.ItemStore store);FindAll (System.Storage.ItemStore store);

public static new System.Storage.FindResultpublic static new System.Storage.FindResult

FindAll(FindAll (

System.Storage.ItemStore store, string filter);System.Storage.ItemStore store, string filter);

public static new Personpublic static new Person

FindOne(FindOne (

System.Storage.ItemStore store,System.Storage.ItemStore store,

string filter);string filter);

public new eventpublic new event

System.Windows.Data.PropertyChangedEventHandlerSystem.Windows.Data.PropertyChangedEventHandler

PropertyChangedHandler;PropertyChangedHandler;

public static new Personpublic static new Person

FindByID(FindByID (

System.Storage.ItemStore store, long item_key);System.Storage.ItemStore store, long item_key);

}}

В порядке еще одного примера, подробная структура типа TelephoneNumber, заданного в Схеме контактов, показана ниже в виде XML:As another example, the detailed structure of the TelephoneNumber type specified in the Contact Scheme is shown below as XML:

<Type Name="TelephoneNumber" ExtendsType="Core.EAddress"<Type Name = "TelephoneNumber" ExtendsType = "Core.EAddress"

MajorVersion="1" MinorVersion="0"MajorVersion = "1" MinorVersion = "0"

ExtendsVersion="1"/>ExtendsVersion = "1" />

<Field Name="CountryCode" Type="the storage<Field Name = "CountryCode" Type = "the storage

platformTypes.nvarchar(50)" Nullable="true"platformTypes.nvarchar (50) "Nullable =" true "

MultiValued="TypeMajorVersion="1”/>MultiValued = "TypeMajorVersion =" 1 ”/>

<Field Name="AreaCode" Type="the storage<Field Name = "AreaCode" Type = "the storage

platformTypes.nvarchar(256)" Nullable="true"platformTypes.nvarchar (256) "Nullable =" true "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="Number" Type="the storage<Field Name = "Number" Type = "the storage

platformTypes.nvarchar(256)" Nullable="true"platformTypes.nvarchar (256) "Nullable =" true "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="Extension" Type="the storage<Field Name = "Extension" Type = "the storage

platformTypes.nvarchar(256)" Nullable="true"platformTypes.nvarchar (256) "Nullable =" true "

TypeMajorVersion=1”/>TypeMajorVersion = 1 ”/>

<Field Name="PIN" Type="the storage<Field Name = "PIN" Type = "the storage

platformTypes.nvarchar(50)" Nullable="true"platformTypes.nvarchar (50) "Nullable =" true "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

</Type></Type>

Этот тип порождает следующий класс (показаны только публичные члены):This type spawns the following class (only public members are shown):

partial public class TelephoneNumber:partial public class TelephoneNumber:

System.Storage.Core.EAddress,System.Storage.Core.EAddress,

System.Windows.Data.IDataUnitSystem.Windows.Data.IDataUnit

{{

public System.Data.SglTypes.SqlString CountryCodepublic System.Data.SglTypes.SqlString CountryCode

{get; set;}{get; set;}

public System.Data.SqlTypes.SqlString AreaCodepublic System.Data.SqlTypes.SqlString AreaCode

{get; set;}{get; set;}

public System.Data.SqlTypes.SqlString Numberpublic System.Data.SqlTypes.SqlString Number

{get; set;}{get; set;}

public System.Data.SqlTypes.SqlString Extensionpublic System.Data.SqlTypes.SqlString Extension

{get; set;}{get; set;}

public System.Data.SqlTypes.SqlString PINpublic System.Data.SqlTypes.SqlString PIN

{get; set;}{get; set;}

public TelephoneNumber();public TelephoneNumber ();

public new eventpublic new event

System.Windows.Data.PropertyChangedEventHandlerSystem.Windows.Data.PropertyChangedEventHandler

PropertyChangedHandler;PropertyChangedHandler;

}}

Иерархия классов, полученных из данной схемы, непосредственно отражает иерархию типов в этой схеме. Например, рассмотрим типы статьи, заданные в Схеме контактов (см. фиг.21A и 21B). Иерархия классов, соответствующая этому в API платформы хранения будет выглядеть следующим образом:The hierarchy of classes derived from this schema directly reflects the type hierarchy in this schema. For example, consider the article types defined in the Contact Scheme (see FIGS. 21A and 21B). The class hierarchy corresponding to this in the storage platform API will look like this:

ObjectObject

DataClassDataClass

ElementBaseElementbase

RootItemBaseRootoottase

ItemItem

PrincipalPrincipal

GroupGroup

HouseholdHousehold

OrganizationOrganization

PersonPerson

UserUser

ServiceService

PresenceServicePresence service

ContactServiceContactService

ADServiceADService

RootNestedBaseRootootbase

… (классы элементов)... (element classes)

Еще одна схема, схема, которая позволяет представлять все аудио/видео-среды в системе (разрезанные на аудио-файлы, аудио- CD, DVD, домашнее видео и т.д.), позволяет пользователям/приложениям сохранять, организовывать, осуществлять поиск и манипулировать разными видами аудио/видео-средами. Базовая схема мультимедийного документа достаточно общая для представления любых сред, и расширения этой базовой схемы предназначены для обработки свойств, связанных с доменом, отдельно для аудио- и видео-сред. Представляется, что эта и многие, многие другие схемы действуют прямо или косвенно под Схемой ядра.Another scheme, a scheme that allows you to represent all the audio / video environments in the system (cut into audio files, audio CDs, DVDs, home videos, etc.), allows users / applications to save, organize, search and to manipulate different types of audio / video environments. The basic layout of a multimedia document is general enough to represent any medium, and extensions to this basic layout are designed to handle domain-related properties separately for audio and video environments. It seems that this and many, many other schemes operate directly or indirectly under the Kernel Scheme.

5. Структура среды выполнения5. The structure of the runtime environment

Основной моделью программирования API платформы хранения является живучесть объекта. Прикладные программы (или «приложения») выполняют поиск в хранилище и возвращают объекты, представляющие данные в хранилище. Приложения изменяют возвращаемые объекты или создают новые объекты, в результате чего эти изменения распространяются в хранилище. Этим процессом управляет объект ItemContext. Механизмы поиска выполняются с использованием объекта ItemSearcher, и результаты поиска становятся доступными через объект FindResult.The main programming model of the storage platform API is object survivability. Application programs (or “applications”) search the store and return objects that represent the data in the store. Applications modify returned objects or create new objects, as a result of which these changes are propagated to the repository. This process is controlled by the ItemContext. Search engines are performed using the ItemSearcher object, and search results are made available through the FindResult object.

а) Классы структуры среды выполненияa) Runtime structure classes

Согласно другому аспекту изобретения API платформы хранения структура среды выполнения реализует ряд классов для поддержки операции классов данных. Эти классы структуры задают общее множество поведений для классов данных и, совместно с классами данных обеспечивают основную модель программирования для API платформы хранения. Классы в структуре среды выполнения принадлежат пространству имен System.Storage. Согласно данному варианту осуществления классы структуры содержат следующие главные классы: ItemContext, ItemSearcher, и FindResult. Также могут быть предусмотрены другие младшие классы, значения перечисления и делегаты.According to another aspect of the invention, the storage platform API the runtime framework implements a number of classes to support the operation of data classes. These structure classes define a common set of behaviors for data classes and, together with data classes, provide a basic programming model for the storage platform APIs. The classes in the runtime structure belong to the System.Storage namespace. According to this embodiment, the structure classes comprise the following main classes: ItemContext, ItemSearcher, and FindResult. Other elementary classes, enumeration values, and delegates may also be provided.

(1) ItemContext(1) ItemContext

Объект ItemContext (i) представляет множество доменов статьи, в котором прикладная программа хочет осуществить поиск, (ii) поддерживает информацию состояния для каждого объекта, который представляет состояние данных, извлекаемых из платформы хранения, и (iii) управляет транзакциями, используемыми при взаимодействии с платформой хранения и любой файловой системой, с которой может взаимодействовать платформа хранения.An ItemContext object (i) represents a plurality of domains of an article in which the application wants to search, (ii) maintains state information for each object that represents the state of data retrieved from the storage platform, and (iii) manages the transactions used in interacting with the platform storage and any file system with which the storage platform can interact.

В качестве машины живучести объекта ItemContext обеспечивает следующие услуги:As an object survivability machine, ItemContext provides the following services:

1. Преобразование из последовательного вида данных, считанных из хранилища в объекты.1. Conversion from a sequential view of data read from storage to objects.

2. Поддержание идентификации объекта (один и тот же объект используется для представления данной статьи независимо от того, сколько раз эта статья включена в результат запросов).2. Maintaining the identification of the object (the same object is used to represent this article regardless of how many times this article is included in the query result).

3. Отслеживание состояния объектов.3. Tracking the status of objects.

ItemContext также осуществляет ряд услуг, уникальных для платформы хранения:ItemContext also provides a number of services unique to the storage platform:

1. Генерирует и выполняет операции апдейтграммы платформы хранения, необходимые для продления жизни изменений.1. Generates and performs updates of the storage platform necessary to extend the life of the changes.

2. Создает соединения с множественными хранилищами данных при необходимости обеспечения гладкой навигации отношений ссылки и разрешения изменения и сохранения объектов, извлеченных из многодоменного поиска.2. Creates connections to multiple data storages, if necessary, to ensure smooth navigation of link relationships and allow changes and preservation of objects extracted from multi-domain search.

3. Гарантирует, что статьи, зарезервированные в файле, надлежащим образом обновляются при сохранении изменений объекта(ов), представляющих эту статью.3. Ensures that the articles reserved in the file are properly updated while saving changes to the object (s) representing this article.

4. Управляет транзакциями по множественным соединениям платформы хранения и, при обновлении данных, хранящихся в статьях, зарезервированных в файле, и свойств потоков файлов, по файловой системе, подвергнутой транзакции.4. Manages transactions across multiple connections of the storage platform and, when updating data stored in articles reserved in a file, and properties of file streams, over the file system subjected to the transaction.

5. Осуществляет операции создания, копирования, перемещения и удаления статей, которые учитывают семантику отношений платформы хранения, статьи, зарезервированные в файле, и типизированные свойства потока.5. Carries out operations of creating, copying, moving and deleting articles that take into account the semantics of relations of the storage platform, articles reserved in the file, and typed flow properties.

В Приложении А представлен исходный код класса ItemContext согласно одному варианту его осуществления.Appendix A presents the source code for the ItemContext class according to one embodiment.

(2) ItemSearcher(2) ItemSearcher

Класс ItemSearcher поддерживает простые поиски, которые возвращают объекты статьи целиком, потоки объектов статьи или потоки значений, проецируемых из статьи. ItemSearcher инкапсулирует функциональные возможности ядра, общие для: понятия целевого типа и параметризованных фильтров, которые применяются к этому целевому типу. ItemSearcher также позволяет предварительно компилировать или подготавливать механизмы поиска в порядке оптимизации, когда один и тот же поиск будет выполняться для множественных типов. В Приложении В представлен исходный код класса ItemSearcher и несколько тесно связанных классов согласно одному варианту их осуществления.The ItemSearcher class supports simple searches that return entire article objects, article object streams, or value streams projected from an article. ItemSearcher encapsulates kernel functionality that is common to: concepts of the target type and parameterized filters that apply to this target type. ItemSearcher also allows you to precompile or prepare search engines in optimization order when the same search is performed for multiple types. Appendix B presents the source code for the ItemSearcher class and several closely related classes according to one embodiment.

(a) Целевой тип(a) Target type

Целевой тип поиска задается при конструировании ItemSearcher. Целевой тип является типом CLR, который отображается в запрашиваемое расширение хранилищем данных. В частности, это тип CLR, который отображается в типы статьи, отношения и расширения статьи, а также схематизированные виды.The target search type is specified when constructing the ItemSearcher. The target type is the CLR type that maps to the requested extension by the data warehouse. In particular, it is a CLR type that maps to article types, article relationships and extensions, and schematized views.

При извлечении механизма поиска с использованием метода ItemContext.GetSearcher, целевой тип механизма поиска задается как параметр. При вызове метода GetSearcher на типе статьи, отношения или расширения статьи (например, Person.GetSearcher), целевым типом является тип статьи, отношения или расширения статьи.When retrieving a search engine using the ItemContext.GetSearcher method, the target type of the search engine is specified as a parameter. When you call the GetSearcher method on the type of the article, relationship or extension of the article (for example, Person.GetSearcher), the target type is the type of the article, relationship, or extension of the article.

Выражения поиска, обеспеченные в ItemSearcher (например, фильтр поиска и опции сквозного нахождения или определения проекции) всегда относятся к целевому типу поиска. Эти выражения могут задавать свойства целевого типа (включая свойства вложенных элементов) и могут задавать соединения с отношением и расширениями статьи, как описано в другом месте.The search expressions provided in ItemSearcher (for example, a search filter and options for finding through or defining a projection) always refer to the target type of search. These expressions can specify properties of the target type (including properties of nested elements) and can specify connections with the relation and extensions of the article, as described elsewhere.

Целевой тип поиска делается доступным через свойство только для чтения (например, свойство ItemSearcher.Type)The target search type is made available through a read-only property (for example, the ItemSearcher.Type property)

(b) Фильтры(b) Filters

ItemSearcher содержит свойство для задания фильтров (например, свойство под названием "Filters" как коллекция объектов SearchExpression), которое задает фильтр, используемый при поиске. Все фильтры в коллекции объединяются с использованием логического оператора AND при выполнении поиска. Фильтр может содержать ссылки на параметры. Значения параметров указаны посредством свойства Parameters.ItemSearcher contains a property for defining filters (for example, a property called "Filters" as a collection of SearchExpression objects) that sets the filter used in the search. All filters in the collection are combined using the logical AND operator when performing a search. The filter may contain links to parameters. Parameter values are specified using the Parameters property.

(с) Подготовка поисков(c) Preparing searches

В ситуациях, когда один и тот же поиск подлежит неоднократному выполнению, возможно, только с изменением параметров, некоторого улучшения выполнения можно добиться путем предварительной компиляции или подготовки поиска. Это осуществляется с помощью множества методов подготовки на ItemSearcher (например, метод для подготовки Find, который возвращает одну или несколько статей, возможно, под названием "PrepareFind", и метод для подготовки Find, который возвращает проекцию, возможно, под названием "PrepareProject"). Например:In situations where the same search is subject to repeated execution, possibly only with a change in parameters, some improvement in performance can be achieved by preliminary compilation or preparation of the search. This is accomplished using a variety of preparation methods on ItemSearcher (for example, a method for preparing Find that returns one or more articles, possibly called “PrepareFind”, and a method for preparing Find, which returns a projection, possibly called “PrepareProject”) . For example:

ItemSearcher searcher =...;ItemSearcher searcher = ...;

PreparedFind pf = searcher.PrepareFind();PreparedFind pf = searcher.PrepareFind ();

...

result = pf.FindAll();result = pf.FindAll ();

...

result = pf.FindAll();result = pf.FindAll ();

(d) Опции Find(d) Find options

Существует ряд опций, которые можно применять к простому поиску. Они могут быть заданы, например, в объекте FindOptions и переданы методам Find. Например:There are a number of options that can be applied to a simple search. They can be set, for example, in the FindOptions object and passed to Find methods. For example:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

FindOptions options = new FindOptions();FindOptions options = new FindOptions ();

options.MaxResults = 10;options.MaxResults = 10;

options.SortOptions.Add("PersonalNames.Surname",options.SortOptions.Add ("PersonalNames.Surname",

SortOrder.Ascending);SortOrder.Ascending);

FindResult result = searcher.FindAll(options);FindResult result = searcher.FindAll (options);

Для удобства опции сортировки также могут передаваться непосредственно методам Find:For convenience, sorting options can also be passed directly to Find methods:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

FindResult result = searcher.FindAll(FindResult result = searcher.FindAll (

new SortOption("PersonalNames.Surname",new SortOption ("PersonalNames.Surname",

SortOrder.Ascending));SortOrder.Ascending));

Опция DelayLoad определяет, загружаются ли значения больших бинарных свойств при извлечении результатов поиска или задерживается ли загрузка до получения ссылки на них. Опция MaxResults определяет максимальное количество возвращаемых результатов. Это эквивалентно заданию TOP в запросе SQL. Она чаще всего используется совместно с сортировкой.The DelayLoad option determines whether large binary property values are loaded when the search results are retrieved or whether the load is delayed until a link to them is received. The MaxResults option determines the maximum number of returned results. This is equivalent to specifying TOP in the SQL query. It is most often used in conjunction with sorting.

Можно задать последовательность объектов SortOption (например, с использованием свойства FindOptions.SortOptions). Результаты поиска сортируются, как указано первым объектом SortOption, затем, как указано вторым объектом SortOption, и т.д. SortOption задает выражение поиска, которое указывает свойство, используемое для сортировки. Выражение задает одно из следующих:You can specify a sequence of SortOption objects (for example, using the FindOptions.SortOptions property). Search results are sorted as indicated by the first SortOption object, then as indicated by the second SortOption object, etc. SortOption defines a search expression that indicates the property used for sorting. The expression specifies one of the following:

1) скалярное свойство в целевом типе поиска;1) scalar property in the target search type;

2) скалярное свойство во вложенном элементе, достижимое от целевого типа поиска путем обхода однозначных свойств; или2) a scalar property in a nested element, achievable from the target search type by traversing unique properties; or

3) результат функции агрегирования с пригодным аргументом (например, Max, применяемое к скалярному свойству во вложенном элементе, которое достижимо от целевого типа поиска путем обхода многозначного свойства или отношения).3) the result of the aggregation function with a suitable argument (for example, Max applied to a scalar property in a nested element that is achievable from the target search type by traversing a multi-valued property or relation).

Пусть, например, целевой тип поиска это System.Storage.Contact.Person:Let, for example, the target search type be System.Storage.Contact.Person:

1. "Birthdate" - пригодно, дата рождения это скалярное свойство типа Person.1. "Birthdate" - suitable, the date of birth is a scalar property of type Person.

2. "PersonalNames.Surname" - непригодно, PersonalNames это многозначное свойство и никакая функция агрегирования не используется.2. "PersonalNames.Surname" - unsuitable, PersonalNames is a multi-valued property and no aggregation function is used.

3. "Count(PersonalNames)" - пригодно, счетчик для PersonalNames.3. "Count (PersonalNames)" - suitable, the counter for PersonalNames.

4. "Case(Contact.MemberOfHousehold).Household.HouseholdEAddresses.StartDate" - непригодно, использует отношение и многозначные свойства без функции агрегирования.4. "Case (Contact.MemberOfHousehold) .Household.HouseholdEAddresses.StartDate" - unsuitable, uses a relation and multi-valued properties without an aggregation function.

5. "Max(Cast(Contact.MemberOfHousehold).Household.HouseholdEAddresses.StartDate)" - пригодное, наиболее последняя начальная дата домашнего электронного адреса.5. "Max (Cast (Contact.MemberOfHousehold) .Household.HouseholdEAddresses.StartDate)" - a suitable, most recent start date for the home email address.

(3) Поток результатов статьи ("FindResult")(3) Stream of article results ("FindResult")

ItemSearcher (например, посредством метода FindAll) возвращает объект, который можно использовать для доступа к объектам, возращенных поиском (например, объекту "FindResult"). В Приложении С представлен исходный код класса FindResult и нескольких тесно связанных классов согласно одному варианту их осуществления.ItemSearcher (for example, using the FindAll method) returns an object that can be used to access objects returned by the search (for example, the FindResult object). Appendix C presents the source code for the FindResult class and several closely related classes according to one embodiment of their implementation.

Имеются два разных метода получения результатов из объекта FindResult: использование шаблона читателя, заданного посредством IObjectReader (и IAsyncObjectReader) и использование шаблона перечислителя, заданного посредством IEnumerable и IEnumerator. Шаблон перечислителя является стандартным в CLR и поддерживает языковые конструкции наподобие foreach в C#. Например:There are two different methods for retrieving results from a FindResult object: using a reader template specified by IObjectReader (and IAsyncObjectReader) and using an enumerator template specified by IEnumerable and IEnumerator. An enumerator pattern is standard in the CLR and supports language constructs like foreach in C #. For example:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

searcher.Filters.Add("PersonalNames.Surname = 'Smith'");searcher.Filters.Add ("PersonalNames.Surname = 'Smith'");

FindResult result = searcher.FindAll();FindResult result = searcher.FindAll ();

foreach(Person person in result)...;foreach (Person person in result) ...;

Шаблон читателя поддерживается, потому что это во многих случаях позволяет более эффективно обрабатывать результат за счет исключения копирования данных. Например:The reader template is supported because in many cases it allows more efficient processing of the result due to the exclusion of data copying. For example:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

searcher.Filters.Add("PersonalNames.SurName = 'Smith'”);searcher.Filters.Add ("PersonalNames.SurName = 'Smith'”);

FindResult result = searcher.FindAll();FindResult result = searcher.FindAll ();

while(result.Read())while (result.Read ())

{{

Person person = (Person)result.Current;Person person = (Person) result.Current;

...

}}

Кроме того, шаблон читателя поддерживает асинхронную операцию:In addition, the reader template supports asynchronous operation:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

searcher.Filters.Add("PersonalNames.SurName = 'Smith'”);searcher.Filters.Add ("PersonalNames.SurName = 'Smith'”);

FindResult result = searcher.FindAll();FindResult result = searcher.FindAll ();

IAysncResult asyncResult = result.BeginRead(newIAysncResult asyncResult = result.BeginRead (new

AsyncCallback(MyCallback));AsyncCallback (MyCallback));

void MyCallback(IAsyncResult asyncResult)void MyCallback (IAsyncResult asyncResult)

{{

if( result.EndRead( asyncResult))if (result.EndRead (asyncResult))

{{

Person person = (Person)resuIt.Current;Person person = (Person) resuIt.Current;

...

}}

}}

Согласно данному варианту осуществления FindResult должен быть закрыт, когда он больше не нужен. Это можно делать, вызывая метод Close или используя языковые конструкции, например, оператор использования C#. Например:According to this embodiment, FindResult should be closed when it is no longer needed. This can be done by calling the Close method or using language constructs, such as the C # use statement. For example:

ItemSearcher searcher = Person.GetSearcher(context);ItemSearcher searcher = Person.GetSearcher (context);

searcher.Filters.Add( "PersonalNames.SurName = 'Smith'”);searcher.Filters.Add ("PersonalNames.SurName = 'Smith'”);

using(FindResult result = searcher.FindAll())using (FindResult result = searcher.FindAll ())

{{

while(result.Read())while (result.Read ())

{{

Person person = (Person)result.Current;Person person = (Person) result.Current;

...

}}

}}

b) Структура среды выполнения в процессе работыb) Runtime structure during work

На фиг.22 показана структура среды выполнения в процессе работы. Структура среды выполнения действует следующим образом:On Fig shows the structure of the runtime in the process. The runtime structure acts as follows:

1. Приложение 350a, 350b, или 350c связывается со статьей в платформе хранения.1. Application 350a, 350b, or 350c links to an article in a storage platform.

2. Структура 2004 создает объект ItemContext 2202, соответствующий связанной статье и возвращает его приложению.2. Structure 2004 creates an ItemContext 2202 object corresponding to the associated article and returns it to the application.

3. Приложение передает Find в этом ItemContext для получения коллекции статей; возвращенная коллекция в принципе является объектным графом 2204 (вследствие отношений).3. The application passes Find in this ItemContext to obtain a collection of articles; the returned collection is in principle an object graph 2204 (due to a relationship).

4. Приложение изменяет, удаляет и вставляет данные.4. The application modifies, deletes and inserts data.

5. Приложение сохраняет изменения, вызывая метод Update().5. The application saves the changes by calling the Update () method.

с) Общие шаблоны программированияc) General programming patterns

В этом разделе представлены различные примеры того, как можно использовать классы структуры API платформы хранения для манипуляции статьями в хранилище данных.This section provides various examples of how you can use storage platform API structure classes to manipulate articles in a data warehouse.

(1) Открытие и закрытие объектов ItemContext(1) Opening and closing ItemContext objects

Приложение получает объект ItemContext, который оно будет использовать для взаимодействия с хранилищем данных, например, вызывая статический метод ItemContext.Open и обеспечивая путь или пути, которые идентифицируют домены статей, которые будут связаны с ItemContext. Домены статей рассматривают механизмы поиска, выполняемые с использованием ItemContext, так что только одна статья домена и статьи, содержащиеся в этой статье, будут подлежать поиску. Рассмотрим примеры:The application receives an ItemContext object that it will use to interact with the data store, for example, by calling the static ItemContext.Open method and providing a path or paths that identify the article domains that will be associated with the ItemContext. Article domains consider search engines using ItemContext, so only one domain article and the articles contained in this article will be searched. Consider the following examples:

Открыть ItemContext с помощью совместно используемого ресурса платформы хранения DefaultStore на локальном компьютереOpen ItemContext using the shared resource of the DefaultStore storage platform on the local computer

ItemContext ic = ItemContext.Open();ItemContext ic = ItemContext.Open ();

Открыть ItemContext с помощью данного совместно используемого ресурса платформы храненияOpen ItemContext with this shared storage platform resource

ItemContext ic = ItemContext.Open(@"\\myserver1\DefaultStore");ItemContext ic = ItemContext.Open (@ "\\ myserver1 \ DefaultStore");

Открыть ItemContext с помощью статьи используемого ресурса платформы храненияOpen ItemContext using article of used storage platform resource

ItemContext ic = ItemContext.Open(@"\\myserver1\WinFSSpecs\api\m6");ItemContext ic = ItemContext.Open (@ "\\ myserver1 \ WinFSSpecs \ api \ m6");

Открыть ItemContext с помощью множественных доменов статейOpen ItemContext with Multiple Article Domains

ItemContext ic = ItemContext.Open(@"\\myserver1\My Documents",ItemContext ic = ItemContext.Open (@ "\\ myserver1 \ My Documents",

@”\\jane1\My Documents",@ ”\\ jane1 \ My Documents",

@"\\jane2\My Documents");@ "\\ jane2 \ My Documents");

Когда ItemContext больше не нужен, его нужно закрыть.When an ItemContext is no longer needed, it needs to be closed.

В явном виде закрыть ItemContextExplicitly close ItemContext

ItemContext ic = ItemContext.Open();ItemContext ic = ItemContext.Open ();

...

ic.Close();ic.Close ();

Закрыть с использованием утверждения с ItemContextClose using statement with ItemContext

using( ItemContext ic = ItemContext.Open())using (ItemContext ic = ItemContext.Open ())

{{

…;...;

}}

(2) Поиск объектов(2) Object Search

Согласно другому аспекту настоящего изобретения API платформы хранения обеспечивает упрощенную модель запроса, которая позволяет разработчикам прикладных программ формировать запросы на основании различных свойств статей в хранилище данных, при этом разработчик прикладной программы изолирован от подробностей языка запроса нижележащей машины базы данных.According to another aspect of the present invention, the storage platform API provides a simplified query model that allows application developers to query based on various properties of articles in a data warehouse, while the application developer is isolated from the details of the query language of the underlying database machine.

Приложения могут выполнять поиск по доменам, указанным при открытии ItemContext с использованием объекта ItemSearcher, возвращенного методом ItemContext.GetSearcher. Доступ к результатам поиска осуществляется с использованием объекта FindResult. Предположим следующие декларации для примеров, приведенных ниже:Applications can search the domains specified when opening the ItemContext using the ItemSearcher returned by the ItemContext.GetSearcher method. Access to the search results is carried out using the FindResult object. Assume the following declarations for the examples below:

ItemContext ic =...;ItemContext ic = ...;

ItemSearcher searcher = null;ItemSearcher searcher = null;

FindResult result = null;FindResult result = null;

Item item = null;Item item = null;

Relationship relationship = null;Relationship relationship = null;

ItemExtension itemExtension = null;ItemExtension itemExtension = null;

Основной шаблон поиска предполагает использование объекта ItemSearcher, извлеченного из ItemContext путем вызова метода GetSearcher.The basic search pattern involves using the ItemSearcher object retrieved from the ItemContext by calling the GetSearcher method.

Поиск всех статей данного типаSearch for all articles of this type

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

result = searcher.FindAll();result = searcher.FindAll ();

foreach(Person p in result)...;foreach (Person p in result) ...;

Поиск статей данного типа, которые удовлетворяют фильтруSearch for articles of this type that match the filter

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames.Surname = 'Smith'”);searcher.Filters.Add ("PersonalNames.Surname = 'Smith'”);

result = searcher.FindAll();result = searcher.FindAll ();

foreach(Person p in result)...;foreach (Person p in result) ...;

Использовать параметр в строке фильтраUse parameter in filter string

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("Birthdate < @Date");searcher.Filters.Add ("Birthdate <@Date");

searcher. Parameters["Date"] = someDate;searcher. Parameters ["Date"] = someDate;

result = searcher.FindAll();result = searcher.FindAll ();

foreach(Person p in result)…;foreach (Person p in result) ...;

Поиск отношений данного типа и удовлетворяющих фильтруSearch for relations of this type and satisfying the filter

searcher = ic.GetSearcher(typeof(EmployeeEmployer));searcher = ic.GetSearcher (typeof (EmployeeEmployer));

searcher.Filters.Add( "StartDate <= @Date AND (EndDate >=searcher.Filters.Add ("StartDate <= @Date AND (EndDate> =

@Date OR isnull(EndDate))");@Date OR isnull (EndDate)) ");

searcher.Parameters["Date"] = someDate;searcher.Parameters ["Date"] = someDate;

result = searcher.FindAll();result = searcher.FindAll ();

Foreach(EmployeeEmployer ee in result)...;Foreach (EmployeeEmployer ee in result) ...;

Поиск статей с отношениями данного типа и удовлетворяющих фильтруSearch for articles with relationships of this type and satisfying the filter

searcher = ic.GetSearcher(typeof(Folder));searcher = ic.GetSearcher (typeof (Folder));

searcher.Filters.Add("MemberRelationships.Name like 'A%'");searcher.Filters.Add ("MemberRelationships.Name like 'A%'");

// См. [ApiRel]// See [ApiRel]

result = searcher.FindAll();result = searcher.FindAll ();

Foreach(Folder f in result)...;Foreach (Folder f in result) ...;

Поиск расширений статьи данного типа и удовлетворяющих фильтруSearch for article extensions of this type and matching the filter

searcher = ic.GetSearcher(typeof(ShellExtension));searcher = ic.GetSearcher (typeof (ShellExtension));

searcher.Filters.Add( "Keywords.Value = 'Foo'”);searcher.Filters.Add ("Keywords.value = 'foo'”);

result = searcher.FindAll();result = searcher.FindAll ();

foreach(ShellExtension se in result)…;foreach (ShellExtension se in result) ...;

Поиск статей с расширениями данного типа и удовлетворяющих фильтруSearch for articles with extensions of this type and matching the filter

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("Extensions.Cast(@Type).Keywords.Valuesearcher.Filters.Add ("Extensions.Cast (@Type) .Keywords.Value

= 'Foo"'); // См. [ApiExt]= 'Foo "'); // See [ApiExt]

searcher.Parameters["Type"] = typeof(ShellExtension);searcher.Parameters ["Type"] = typeof (ShellExtension);

result = searcher.FindAll();result = searcher.FindAll ();

foreach(Person p in result)…;foreach (Person p in result) ...;

(а) Опции поиска(a) Search options

При выполнении поиска можно задавать различные опции, включая сортировку, загрузку с задержкой и ограничение количества результатов.When performing a search, you can set various options, including sorting, delayed loading, and limiting the number of results.

Сортировка результатов поискаSort Search Results

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames.Surname = 'Smith'");searcher.Filters.Add ("PersonalNames.Surname = 'Smith'");

SearchOptions options = new SearchOptions();SearchOptions options = new SearchOptions ();

options.SortOptions.Add(new SortOption("Birthdate",options.SortOptions.Add (new SortOption ("Birthdate",

SortOrder.Ascending));SortOrder.Ascending));

result = searcher.FindAll(options);result = searcher.FindAll (options);

foreach(Person p in result)...;foreach (Person p in result) ...;

// Доступен короткий вызов:// Short call available:

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames.Surname = 'Smith'”);searcher.Filters.Add ("PersonalNames.Surname = 'Smith'”);

result = searcher.FindAll(new SortOption("Birthdate",result = searcher.FindAll (new SortOption ("Birthdate",

SortOrder.Ascending));SortOrder.Ascending));

foreach(Person p in result)...;foreach (Person p in result) ...;

Ограничение количества результатовLimit the number of results

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames.Surname = 'Smith'”);searcher.Filters.Add ("PersonalNames.Surname = 'Smith'”);

SearchOptions options = new SearchOptions();SearchOptions options = new SearchOptions ();

options.MaxResults = 10;options.MaxResults = 10;

result = searcher.FindAll(options);result = searcher.FindAll (options);

foreach(Person p in result)...;foreach (Person p in result) ...;

(b) FindOne и FindOnly(b) FindOne and FindOnly

В случае, когда полезным является извлечение только одного результата, особенно при задании мягких критериев. Кроме того, ожидается, что некоторые поиски возвращают только один объект, и не ожидается, что они не возвратят ни одного объекта.In the case where it is useful to extract only one result, especially when setting soft criteria. In addition, it is expected that some searches return only one object, and it is not expected that they will not return a single object.

Поиск одного объектаSingle Object Search

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames.Surname = 'Smith'");searcher.Filters.Add ("PersonalNames.Surname = 'Smith'");

Person p = searcher.FindOne(new SortOption("Birthdate"Person p = searcher.FindOne (new SortOption ("Birthdate"

SortOrder.Ascending)) as Person;SortOrder.Ascending)) as Person;

if(p != null)...;if (p! = null) ...;

Поиск одного объекта, который, как ожидается, всегда существуетSearch for one object that is expected to always exist

searcher = ic.GetSearcher(typeof(Person));searcher = ic.GetSearcher (typeof (Person));

searcher.Filters.Add("PersonalNames[Surname = 'Smith' ANDsearcher.Filters.Add ("PersonalNames [Surname = 'Smith' AND

Givenname 'John']");Givenname 'John'] ");

trytry

{{

Person p = searcher.FindOnly();Person p = searcher.FindOnly ();

…;...;

}}

catch(Exception e)catch (Exception e)

{{

…;...;

}}

(с) Короткие вызовы поиска на ItemContext(c) Short search calls on ItemContext

Существует также ряд методов короткого вызова на ItemContext, которые, насколько возможно, упрощают выполнение поисков.There are also a number of shortcuts to ItemContext that make search as easy as possible.

Поиск с использованием короткого вызова ItemContext.FindAllSearch using the ItemContext.FindAll shortcut

result = ic.FindAll(typeof(Person),result = ic.FindAll (typeof (Person),

"PersonalNames.Surname = 'Smith'");"PersonalNames.Surname = 'Smith'");

foreach(Person p in result)...;foreach (Person p in result) ...;

Поиск с использованием короткого вызова ItemContext.FindOneSearch Using the ItemContext.FindOne Shortcut

Person p = ic.FindOne(typeof(Person),Person p = ic.FindOne (typeof (Person),

"PersonalNames.Surname = 'Smith'") as Person;"PersonalNames.Surname = 'Smith'") as Person;

(d) Нахождение по ИД или пути(d) Finding by ID or path

Кроме того, статьи, отношения и расширения статей можно извлекать, обеспечивая их идентификаторы. Статьи также можно извлекать с помощью пути.In addition, articles, relationships, and article extensions can be retrieved by providing their identifiers. Articles can also be retrieved using the path.

Получение статей, отношений и расширений статей по их идентификаторамRetrieving articles, relationships, and article extensions by their identifiers

item = ic.FindItemById(iid);item = ic.FindItemById (iid);

relationship = ic.FindRelationshipById(iid, rid);relationship = ic.FindRelationshipById (iid, rid);

itemExtension = ic.FindItemExtensionById(iid, eid);itemExtension = ic.FindItemExtensionById (iid, eid);

Получение статей по путиGetting articles along the way

// Только один домен// Only one domain

item = ic.FindItemByPath(@"temp\foo.txt");item = ic.FindItemByPath (@ "temp \ foo.txt");

// Один или несколько доменов// One or more domains

result = ic.FindAllItemsByPath(@"temp\foo.txt”);result = ic.FindAllItemsByPath (@ "temp \ foo.txt”);

foreach(Item I in result)...;foreach (Item I in result) ...;

(е) Шаблон GetSearcher(f) GetSearcher Template

В API платформы хранения есть много мест, где желательно обеспечить метод помощника, который выполняет поиск в контексте другого объекта или с конкретными параметрами. Шаблон GetSearcher обеспечивает эти сценарии. В API существует много методов GetSearcher. Каждый из них возвращает ItemSearcher, заранее сконфигурированный, на осуществление данного поиска. Например:There are many places in the storage platform API where it is desirable to provide a helper method that searches in the context of another object or with specific parameters. The GetSearcher template provides these scenarios. There are many GetSearcher methods in the API . Each of them returns an ItemSearcher , preconfigured, to perform this search. For example:

searcher = itemContext.GetSearcher();searcher = itemContext.GetSearcher ();

searcher = Person.GetSearcher();searcher = Person.GetSearcher ();

searcher =searcher =

EmployeeEmployer.GetSearcherGivenEmployer(organization);EmployeeEmployer.GetSearcherGivenEmployer (organization);

searcher = person.GetSearcherForReports();searcher = person.GetSearcherForReports ();

Перед выполнением поиска можно задать дополнительные фильтры:Before performing a search, you can set additional filters:

searcher = person.GetSearcherForReports();searcher = person.GetSearcherForReports ();

searcher.Filters.Add("PersonalNames.Surname='Smith'");searcher.Filters.Add ("PersonalNames.Surname = 'Smith'");

Вы можете выбрать вид представления результата:You can choose the type of presentation of the result:

FindResult findResult = searcher.FindAll();FindResult findResult = searcher.FindAll ();

Person person = searcher.FindOne();Person person = searcher.FindOne ();

(3) Обновление хранилища(3) Storage update

После извлечения объекта путем поиска, приложение, при необходимости, может его изменить. Можно также создавать новые объекты и связывать их с существующими объектами. После того как приложение произведет все изменения, образующие логическую группу, приложение вызывает ItemContext.Update для сохранения этих изменений в хранилище. Согласно еще одному аспекту API платформы хранения настоящего изобретения, API собирает изменения статьи, сделанные прикладной программой, после чего организует их в правильные обновления, необходимые машине базы данных (или машине хранения любого рода), на которой реализовано хранилище данных. Это позволяет разработчикам прикладных программ совершать изменения статьи в памяти, оставляя API сложные аспекты обновления хранилища данных.After extracting the object by searching, the application, if necessary, can change it. You can also create new objects and associate them with existing objects. After the application makes all the changes that make up the logical group, the application calls ItemContext.Update to save these changes to the repository. According to another aspect of the storage platform API of the present invention, the API collects the article changes made by the application program, and then organizes them into the correct updates required by the database machine (or storage machine of any kind) on which the data warehouse is implemented. This allows application developers to make changes to the article in memory, leaving the API complex aspects of updating the data warehouse.

Сохранение изменений в одной статьеSaving changes in one article

Person p = ic.FindltemById(pid) as Person;Person p = ic.FindltemById (pid) as Person;

p.DisplayName = "foo";p.DisplayName = "foo";

p.TelephoneNumbers.Add(new TelephoneNumber("425-555-1234"));p.TelephoneNumbers.Add (new TelephoneNumber ("425-555-1234"));

ic.Update();ic.Update ();

Сохранение изменений в нескольких статьяхSaving changes to multiple articles

Household h1 = ic.FindItemById(hid1) as Household;Household h1 = ic.FindItemById (hid1) as Household;

Household h2 = ic.FindItemById(hid2) as Household;Household h2 = ic.FindItemById (hid2) as Household;

Person p = ic.FindItemById(pid) as Person;Person p = ic.FindItemById (pid) as Person;

h1.MemberRelationships.Remove(p);h1.MemberRelationships.Remove (p);

h2.MemberRelationships.Add(p);h2.MemberRelationships.Add (p);

ic.Update();ic.Update ();

Создание новой статьиCreate a new article

Folder f = ic.FindItemById(fid) as Folder;Folder f = ic.FindItemById (fid) as Folder;

Person p = new Person();Person p = new Person ();

p.DisplayName = "foo";p.DisplayName = "foo";

f.Relationships.Add(new FolderMember(p, "foo"));f.Relationships.Add (new FolderMember (p, "foo"));

ic.Update();ic.Update ();

// Или с использованием короткого вызова...// Or using a short call ...

Folder f = ic.FindItemById(fid) as Folder;Folder f = ic.FindItemById (fid) as Folder;

Person p = new Person();Person p = new Person ();

p.DisplayName = “foo”;p.DisplayName = “foo”;

f.MemberRelationships.Add(p, "foo");f.MemberRelationships.Add (p, "foo");

ic.Update();ic.Update ();

Удаление отношений (и, возможно, целевой статьи)Deleting relationships (and possibly the target article)

searcher = ic.GetSearcher(typeof(FolderMember));searcher = ic.GetSearcher (typeof (FolderMember));

searcher.Filters.Add("SourceItemId=@fid");searcher.Filters.Add ("SourceItemId = @ fid");

searcher.Filters.Add("TargetItemId=@pid");searcher.Filters.Add ("TargetItemId = @ pid");

searcher.Parameters.Add("fid", fid);searcher.Parameters.Add ("fid", fid);

searcher.Parameters.Add("pid", pid);searcher.Parameters.Add ("pid", pid);

foreach(FolderMember fm in searcher.FindAll())foreach (FolderMember fm in searcher.FindAll ())

fm.MarkForDelete();fm.MarkForDelete ();

ic.Update();ic.Update ();

// Или с использованием короткого вызова…// Or using a short call ...

Folder f = ic.FindItemById(fid) as Folder;Folder f = ic.FindItemById (fid) as Folder;

f.MemberRelationships.Remove(pid);f.MemberRelationships.Remove (pid);

ic.Update();ic.Update ();

Добавление расширения статьиAdding an article extension

Item item = ic.FindItemById(iid);Item item = ic.FindItemById (iid);

MyExtension me = new MyExtension();MyExtension me = new MyExtension ();

me.Foo = "bar";me.Foo = "bar";

item.Extensions.Add(me);item.Extensions.Add (me);

ic.Update();ic.Update ();

Удаление расширений статейRemoving Article Extensions

searcher = ic.GetSearcher(typeof( MyExtension));searcher = ic.GetSearcher (typeof (MyExtension));

searcher.Filters.Add("ItemId=@iid");searcher.Filters.Add ("ItemId = @ iid");

searcher.Parameters.Add( "iid", iid);searcher.Parameters.Add ("iid", iid);

foreach(MyExtension me in searcher.FindAll())foreach (MyExtension me in searcher.FindAll ())

me.MarkForDelete();me.MarkForDelete ();

ic.Update();ic.Update ();

// Или с использованием короткого вызова...// Or using a short call ...

Item i = ic.FindltemById(iid);Item i = ic.FindltemById (iid);

i.Extensions.Remove(typeof(MyExtension));i.Extensions.Remove (typeof (MyExtension));

ic.Update();ic.Update ();

6. Безопасность6. Security

Согласно предыдущему разделу II.E (Безопасность), согласно данному варианту осуществления API платформы хранения, существует пять методов, доступных на контексте статьи для извлечения и изменения политики безопасности, связанной со статьей в хранилище. Перечислим их:According to the previous section II.E (Security), according to this embodiment of the storage platform API, there are five methods available in the context of the article to retrieve and modify the security policy associated with the article in the repository. We list them:

1. GetItemSecurity;1. GetItemSecurity;

2. SetItemSecurity;2. SetItemSecurity;

3. GetPathSecurity;3. GetPathSecurity;

4. SetPathSecurity;4. SetPathSecurity;

5. GetEffectiveItemSecurity.5. GetEffectiveItemSecurity.

GetItemSecurity и SetItemSecurity обеспечивают механизм для извлечения и изменения явного ACL, связанного со статьей. Этот ACL не зависит от существующих путей к статье и будет в игре независимым от отношений поддержки, для которых эта статья является целевой. Это позволяет администраторам, при желании, делать безопасность независимой от существующих путей к статье.GetItemSecurity and SetItemSecurity provide a mechanism for retrieving and modifying the explicit ACL associated with an article. This ACL is independent of existing article paths and will be in-game independent of the support relationship for which this article is the target. This allows administrators, if desired, to make security independent of existing article paths.

GetPathSecunty и SetPathSecurity обеспечивают механизм для извлечения и изменения ACL, существующего на статье вследствие отношения поддержки от другой папки. Этот ACL состоит из ACL различных предков статьи совместно с рассматриваемым путем совместно с явным ACL, если какие-либо обеспечены для этого пути. Разница между этим ACL и ACL в предыдущем случае состоит в том, что этот ACL остается в игре только пока существует отношение поддержки, в то время как явный ACL статьи не зависит от любого отношения поддержки к статье.GetPathSecunty and SetPathSecurity provide a mechanism for retrieving and modifying the ACL existing on an article due to a support relationship from another folder. This ACL consists of ACLs of various article ancestors together with the path in question together with an explicit ACL, if any are provided for this path. The difference between this ACL and the ACL in the previous case is that this ACL remains in the game only as long as the support relationship exists, while the explicit ACL of the article does not depend on any support relationship for the article.

ACL, который може быть задан на статье с помощью SetItemSecurity и SetPathSecurity, ограничивается наследуемыми и зависящими от объекта ACE. Они не могут содержать никаких ACE, помеченных как унаследованные.ACLs that can be set on an article using SetItemSecurity and SetPathSecurity are limited to inherited and object-specific ACEs. They cannot contain any ACEs marked as inherited.

GetEffectiveItemSecurity извлекает различные ACL, основанные на пути, а также явный ACL на статье. Это отражает политику авторизации в сущности на данной статье.GetEffectiveItemSecurity retrieves the various path-based ACLs as well as the explicit ACLs on the article. This reflects the authorization policy in essence in this article.

7. Поддержка отношений7. Relationship support

Согласно рассмотренному выше модель данных платформы хранения задает «отношения», которые позволяет связывать статьи друг с другом. При генерации классов данных для схемы для каждого типа отношения формируются следующие классы:According to the above, the storage platform data model defines “relationships” that allow articles to be linked together. When generating data classes for a schema, the following classes are formed for each relationship type:

1. Класс, который представляет отношение само по себе. Этот класс выводится из Класса отношений и содержит члены, зависящие от типа отношения.1. A class that represents a relationship in itself. This class derives from the Relationship Class and contains members that depend on the type of relationship.

2. Сильно типизированный «виртуальный» класс коллекций. Этот класс извлекается из VirtualRelationshipCollection и позволяет создавать и удалять экземпляры отношения.2. A strongly typed “virtual” collection class. This class is retrieved from VirtualRelationshipCollection and allows you to create and delete instances of the relationship.

В этом разделе описана поддержка отношений в API платформы хранения.This section describes relationship support in the storage platform API.

а) Базовые типы отношенийa) Basic types of relationships

API платформы хранения обеспечивает ряд типов в пространстве имен System.Storage, которые образуют основу API отношений. Вот они:The storage platform API provides a number of types in the System.Storage namespace that form the basis of the relationship API. Here they are:

1. Relationship - базовый тип всех классов отношений1. Relationship - the basic type of all relationship classes

2. VirtualRelationshipCollection - базовый тип для всех коллекций отношений2. VirtualRelationshipCollection - the base type for all relationship collections

3. ItemReference, ItemIdReference, ItemPathReference - представляют типы ссылок на статью; отношение между этими типами показано на фиг.11.3. ItemReference, ItemIdReference, ItemPathReference - represent types of article links; the relationship between these types is shown in Fig.11.

(1) Класс Relationship(1) Relationship class

Ниже приведен базовый класс для классов отношений.The following is the base class for relationship classes.

public abstract class Relationship: StoreObjectpublic abstract class Relationship: StoreObject

{{

// Создать с помощью значений по умолчанию.// Create using default values.

protected Relationship(ItemIDReferenceprotected Relationship (ItemIDReference

targetItemReference);targetItemReference);

// Сообщает отношению, что оно добавлено в коллекцию// Tells the relation that it has been added to the collection

//отношений. Объект будет опрашивать коллекцию, чтобы// relationships. The object will poll the collection to

// определить исходную статью, контекст статьи и т.д.// define the source article, article context, etc.

internal AddedToCollection(VirtualRelationshipCollectioninternal AddedToCollection (VirtualRelationshipCollection

collection);collection);

// ИД отношения.// relationship id.

public Relationshipld RelationshipId {get;}public Relationshipld RelationshipId {get;}

// ИД исходной статьи.// ID of the source article.

public Itemld SourceItemId {get;}public Itemld SourceItemId {get;}

// Получить исходную статью.// Get the original article.

public Item SourceItem {get;}public Item SourceItem {get;}

// Ссылка на целевую статью.// Link to the target article.

public ItemIdReference TargetItemReference {get;}public ItemIdReference TargetItemReference {get;}

// Получить целевую статью// Get the target article

//(calls TargetItemReference.GetItem()).// (calls TargetItemReference.GetItem ()).

public Item TargetItem {get;}public Item TargetItem {get;}

// Определяет, имеет ли уже ItemContext соединение с// Determines if ItemContext already has a connection to

// доменом целевой статьи (вызывает// domain of the target article (calls

//TargetItemReference.IsDomainConnected).//TargetItemReference.IsDomainConnected).

public bool IsTargetDomainConnected {get;}public bool IsTargetDomainConnected {get;}

// Имя целевой статьи в пространстве имен. Имя должно// Name of the target article in the namespace. Name must

// быть уникальным по всем отношениям поддержки// be unique across all support relationships

// исходной статьи.// source article.

public OptionalValue<строка> Name {get; set;}public OptionalValue <string> Name {get; set;}

// Определяет, является ли оно отношением поддержки// Determines if it is a support relationship

// или ссылки.// or links.

public OptionalValue<булево> IsOwned {get; set;}public OptionalValue <boolean> IsOwned {get; set;}

}}

(2) Класс ItemReference(2) ItemReference Class

Ниже приведен базовый класс для типов ссылок на статью.The following is the base class for article link types.

public abstract class ItemReference: NestedElementpublic abstract class ItemReference: NestedElement

{{

// Создать с помощью значений по умолчанию.// Create using default values.

protected ItemReference();protected ItemReference ();

// Возвращает ссылочную статью.// Returns a reference article.

public virtual Item GetItem();public virtual Item GetItem ();

// Определить, установлено ли соединение с доменом// Determine if a connection is made to the domain

//ссылочной статьи.// reference article.

public virtual bool IsDomainConnected();public virtual bool IsDomainConnected ();

}}

Объекты ItemReference могут идентифицировать статьи, которые существуют в хранилище, отличном от того, где размещена сама ссылка на статью. Каждый производный тип указывает, как строится и используется ссылка на удаленное хранилище. Реализации GetItem и IsDomainConnected в производных классах используют многодоменную поддержку контекста статьи для загрузки статей из нужного домена и для определения, установлено соединение с доменом.ItemReference objects can identify articles that exist in a repository other than where the link to the article is located. Each derived type indicates how the link to the remote store is built and used. The GetItem and IsDomainConnected implementations in the derived classes use multi-domain article context support to load articles from the desired domain and to determine if a connection to the domain has been established.

(3) Класс ItemIdReference(3) Class ItemIdReference

Ниже представлен класс ItemIdRefrence - ссылка на статью, которая использует ИД статьи для идентификации целевой статьи.The following is the ItemIdRefrence class, a link to an article that uses the article ID to identify the target article.

public class ItemIdReference: ItemReferencepublic class ItemIdReference: ItemReference

{{

// Построить новую ItemIdReference с помощью// Build A New ItemIdReference Using

// значений по умолчанию.// default values.

public ItemIdReference();public ItemIdReference ();

// Построить новую ItemIdReference для указанной статьи.// Build a new ItemIdReference for the specified article.

// Домен, связанный со статьей, используется как указатель.// The domain associated with the article is used as a pointer.

public ItemIdReference(Item item);public ItemIdReference (Item item);

// Построить новую ItemIdReference с пустым указателем и// Build a new ItemIdReference with a null pointer and

// и ИД данной целевой статьи.// and the ID of this target article.

public ItemIdReference(ItemId itemid);public ItemIdReference (ItemId itemid);

// Построить новую ItemIdReference с данными значениями// Build a new ItemIdReference with the given values

// указателя и ИД статьи.// pointer and article id.

public ItemIdReference(string locator, ItemId itemid);public ItemIdReference (string locator, ItemId itemid);

// ИД целевой статьи.// ID of the target article.

public ItemId ItemId {get; set;)public ItemId ItemId {get; set;)

// Путь, указывающий статью WinFS, которая содержит// Path specifying a WinFS article that contains

// целевую статью в своем домене. Если пустой, то// target article in your domain. If empty, then

// домен, содержащий статью, неизвестен.// the domain containing the article is unknown.

public OptionalValue<строка> Locator {get; set;}public OptionalValue <string> Locator {get; set;}

// Определить, установлено ли соединение с доменом// Determine if a connection is made to the domain

// ссылочной статьи.// reference article.

public override bool IsDomainConnected();public override bool IsDomainConnected ();

// Извлекает ссылочную статью.// Retrieves the reference article.

public override Item GetItem();public override Item GetItem ();

}}

GetItem и IsDomainConnected используют многодоменную поддержку контекста статьи для загрузки статей из нужного домена и для определения, установлено соединение с доменом. Этот признак еще не реализован.GetItem and IsDomainConnected use multi-domain article context support to download articles from the desired domain and to determine if a connection to the domain has been established. This feature has not yet been implemented.

(4) Класс ItemPathReference(4) Class ItemPathReference

Класс ItemPathReference является ссылкой на статью, которая использует путь для идентификации целевой статьи. Ниже приведен код для этого класса:The ItemPathReference class is a link to an article that uses the path to identify the target article. Below is the code for this class:

public class ItemPathReference: ItemReferencepublic class ItemPathReference: ItemReference

{{

// Построить ссылку на статью по пути с помощью значений// Build a link to the article along the way using the values

// по умолчанию.// default.

public ItemPathReference();public ItemPathReference ();

// Построить ссылку на статью по пути без помощи указателя// Build a link to the article along the path without the help of a pointer

// и данного пути.// and this path.

public ItemPathReference(string path);public ItemPathReference (string path);

// Построить ссылку на статью по пути с помощью данных// Build a link to the article along the way using data

// указателя и пути.// pointer and path.

public ItemPathReference(string locator, string path);public ItemPathReference (string locator, string path);

// Путь, указывающий статью WinFS, которая содержит// Path specifying a WinFS article that contains

// целевую статью в своем домене.// target article in your domain.

public OptionalValue<строка> Locator {get; set;}public OptionalValue <string> Locator {get; set;}

// Путь к целевой статье относительно домена статьи// Path to the target article relative to the domain of the article

// заданного указателем.// specified by the pointer.

public string Path {get; set;}public string Path {get; set;}

// Определить, установлено ли соединение с доменом// Determine if a connection is made to the domain

// ссылочной статьи.// reference article.

public override bool IsDomainConnected();public override bool IsDomainConnected ();

// Извлекает ссылочную статью.// Retrieves the reference article.

public override Item GetItem();public override Item GetItem ();

}}

GetItem и IsDomainConnected используют многодоменную поддержку контекста статьи для загрузки статей из нужного домена и для определения, установлено соединение с доменом.GetItem and IsDomainConnected use multi-domain article context support to download articles from the desired domain and to determine if a connection to the domain has been established.

(5) Структура RelationshipId(5) RelationshipId Structure

Структура RelationshipId инкапсулирует GUID ИД отношения.The RelationshipId structure encapsulates the GUID of the relationship ID.

public class RelationshipIdpublic class RelationshipId

{{

// Генерирует новый GUID ИД отношения.// Generates a new GUID for the relationship ID.

public static RelationshipId NewRelationshipId();public static RelationshipId NewRelationshipId ();

// Инициализировать с новым GUID ИД отношения.// Initialize the relationship ID with the new GUID.

public RelationshipId();public RelationshipId ();

// Инициализировать с указанным GUID.// Initialize with the specified GUID.

public RelationshipId(Guid id);public RelationshipId (Guid id);

// Инициализировать со строковым представлением GUID.// Initialize with the string representation of the GUID.

public RelationshipId(string id);public RelationshipId (string id);

// Возвращает строковое представление GUID ИД отношения.// Returns a string representation of the GUID of the relationship ID.

public override string ToString();public override string ToString ();

// Преобразует экземпляр System.Guid в экземпляр// Convert an instance of System.Guid to an instance

// RelationshipId.// RelationshipId.

public static implicit operator RelationshipId(Guid guid);public static implicit operator RelationshipId (Guid guid);

// Преобразует экземпляр RelationshipId в// Converts an instance of RelationshipId to

// экземпляр System.Guid// instance of System.Guid

public static implicit operator Guid(RelationshipIdpublic static implicit operator Guid (RelationshipId

relationshipId);relationshipId);

}}

Этот тип значения инкапсулирует GUID так, чтобы параметры и свойства могли быть сильно типизированы как ИД отношения. OptionalValue<RelationshipId> следует использовать, когда ИД отношения обнуляемо. Значение Empty (пусто), например, обеспечиваемое System.Guid.Empty, не открывается. RelationshipId нельзя построить с помощью пустого значения. При использовании конструктора, принятого по умолчанию, для создания RelationshipId, создается новый GUID.This value type encapsulates the GUID so that parameters and properties can be strongly typed as relationship IDs. OptionalValue <RelationshipId> should be used when the relationship ID is nullified. A value of Empty, such as that provided by System.Guid.Empty, does not open. RelationshipId cannot be built using an empty value. When using the default constructor to create the RelationshipId, a new GUID is created.

(6) Класс VirtualRelationshipCollection(6) VirtualRelationshipCollection class

Класс VirtualRelationshipCollection реализует коллекцию объектов отношения, которая включает в себя объекты из хранилища данных, плюс новые объекты, добавленные к коллекции, но не включает в себя объекты, удаленные из хранилища. Объекты указанного типа отношения с данным ИД исходной статьи включаются в коллекцию.The VirtualRelationshipCollection class implements a collection of relationship objects, which includes objects from the data store, plus new objects added to the collection, but does not include objects deleted from the store. Objects of the specified relationship type with the given ID of the source article are included in the collection.

Это исходная статья для класса коллекций отношений, которая генерируется для каждого типа отношения. Этот класс можно использовать как тип свойства в типе исходной статьи для обеспечения доступа и простоты манипуляций отношениями данной статьи.This is the source article for a relationship collection class that is generated for each type of relationship. This class can be used as a property type in the type of the source article to provide access and ease of manipulation of the relationships of this article.

Перечисление содержимого VirtualRelationshipCollection требует загрузки из хранилища потенциально большого количества объектов отношений. Приложения должны использовать свойство Count для определения, сколько отношений можно загрузить прежде, чем они будут перечислять содержимое коллекции. Добавление и удаление объектов в/из коллекции не требует загрузки отношений из хранилища.Enumerating the contents of a VirtualRelationshipCollection requires loading potentially large numbers of relationship objects from the repository. Applications should use the Count property to determine how many relationships can be loaded before they list the contents of the collection. Adding and removing objects to / from the collection does not require loading relationships from the repository.

Для эффективности предпочтительно, чтобы эти приложения искали отношения, удовлетворяющие конкретным критериям, а не перечисляли все отношения статьи с использованием объекта VirtualRelationshipCollection. Добавление объектов отношений в коллекцию приводит к созданию представленных отношений в хранилище при вызове ItemContext.Update. Удаление объектов отношений из коллекции приводит к удалению представленного отношения из хранилища при вызове ItemContext.Update. Виртуальная коллекция содержит правильное множество объектов независимо от того, добавляется/удаляется ли объект отношения посредством коллекции Item.Relationships или любой другой коллекции отношений на этой статье.For efficiency, it is preferable that these applications look for relationships that meet specific criteria, rather than listing all the relationship of the article using the VirtualRelationshipCollection object. Adding relationship objects to the collection creates the presented relationships in the store when ItemContext.Update is called. Removing relationship objects from the collection removes the presented relationship from the store when ItemContext.Update is called. A virtual collection contains the correct set of objects, regardless of whether a relationship object is added / deleted through the Item.Relationships collection or any other relationship collection in this article.

Класс VirtualRelationshipCollection задан следующим кодом:The VirtualRelationshipCollection class is defined by the following code:

public abstract class VirtualRelationshipCollection:public abstract class VirtualRelationshipCollection:

ICollectionIcollection

{{

// Коллекция будет содержать отношения указанного типа,// The collection will contain relationships of the specified type,

// которыми владеет статья, указанная itemId.// owned by the article specified by itemId.

protected VirtualRelationshipCollection(ItemContextprotected VirtualRelationshipCollection (ItemContext

itemContext,itemContext,

ItemId itemId,ItemId itemId,

Type relationshipType);Type relationshipType);

// Перечислитель возвратит все объекты, извлеченные// The enumerator will return all objects retrieved

// из хранилища за минусом объекта, который// from the storage minus the object that

// с состоянием Deleted помимо объектов, имеющих// with Deleted state besides objects that have

// состояние Inserted.// state Inserted.

public IEnumerator GetEnumerator();public IEnumerator GetEnumerator ();

// Возвращает счетчик количества объектов отношения,// Returns the count of the number of relationship objects,

// которые будут возвращены перечислителем. Этот счетчик// to be returned by the enumerator. This counter

// вычисляется без необходимости извлекать все// computed without having to retrieve everything

// объекты из хранилища.// objects from the repository.

public int Count {get;}public int Count {get;}

// Всегда возвращает ложь.// Always returns false.

public bool ICollection.IsSynchronized() {get;}public bool ICollection.IsSynchronized () {get;}

// Всегда возвращает этот объект.// Always returns this object.

public object ICollection.SyncRoot {get;}public object ICollection.SyncRoot {get;}

// Ищет в хранилище нужные объекты.// Searches for objects in the repository.

public void Refresh();public void Refresh ();

// Добавляет указанное отношение в коллекцию. Объект// Adds the specified relation to the collection. An object

// должен иметь состояние Constructed или Removed.// must have the state Constructed or Removed.

// Если состояние - Constructed, оно меняется на Added.// If the state is Constructed, it changes to Added.

// Если состояние - Removed, оно меняется на Retrieved или// If the state is Removed, it changes to Retrieved or

// изменяется как нужно. ИД исходной статьи отношения// changes as needed. ID of the original relationship article

// должен совпадать с ИД исходной статьи,// must match the ID of the source article,

// обеспеченным при построении коллекции.// provided when building the collection.

protected void Add(Relationship relationship);protected void Add (Relationship relationship);

// Удаляет указанное отношение из коллекции. Состояние// Removes the specified relation from the collection. condition

// объекта должно быть Added, Retrieved или Modified. Если// object must be Added, Retrieved or Modified. If

// состояние объекта - Added, его нужно изменить на// the state of the object is Added, it needs to be changed to

// Constructed. Если состояние объекта - Retrieved или// Constructed. If the state of the object is Retrieved or

// Modified, его нужно изменить на Removed.// Modified, it needs to be changed to Removed.

// ИД исходной статьи отношения должно совпадать с ИД// The ID of the source relationship article must match the ID

// исходной статьи, обеспеченным// original article provided

// при построении коллекции.// when building the collection.

protected void Remove(Relationship relationship);protected void Remove (Relationship relationship);

// Объекты, которые были удалены из коллекции.// Objects that have been removed from the collection.

public ICollection RemovedRelationships {get;}public ICollection RemovedRelationships {get;}

// Объекты, которые были добавлены в коллекцию.// Objects that have been added to the collection.

public ICollection AddedRelationships {get;}public ICollection AddedRelationships {get;}

// Объекты, которые извлечены из хранилища.// Objects that are retrieved from storage.

// Эта коллекция будет пустой до перечисления// This collection will be empty until listing

// VirtualRelationshipCollection или вызова Refresh// VirtualRelationshipCollection or call Refresh

// (если значение этого свойства не// (if the value of this property is not

// приводит к заполнению коллекции).// causes the collection to fill).

public ICollection StoredRelationships {get;}public ICollection StoredRelationships {get;}

// Асинхронные методы.// Asynchronous methods.

public IAsyncResult BeginGetCount(IAsyncCallback callback,public IAsyncResult BeginGetCount (IAsyncCallback callback,

object state );object state);

public int EndGetCount(IAsyncResult asyncResult);public int EndGetCount (IAsyncResult asyncResult);

public IAsyncResult BeginRefresh(IAsyncCallback callback,public IAsyncResult BeginRefresh (IAsyncCallback callback,

object state);object state);

public void EndRefresh( IAsyncResult asyncResult);public void EndRefresh (IAsyncResult asyncResult);

}}

b) Сгенерированные типы отношенийb) Generated relationship types

При генерации классов для схемы платформы хранения, для каждой декларации отношения генерируется класс. Помимо класса, который представляет само отношение, для каждого отношения также генерируется класс коллекции отношений. Эти классы используются как тип свойств в классах исходной и целевой статьи отношения.When generating classes for a storage platform schema, a class is generated for each relationship declaration. In addition to the class that represents the relationship itself, a relationship collection class is also generated for each relationship. These classes are used as the type of properties in the classes of the source and target relationship articles.

В этом разделе описаны классы, которые генерируются с использованием ряда классов «прототипов». Таким образом, когда задана декларация отношения, описывается класс, который генерируется. Важно заметить, что имена классов, типов и концевых точек в классах прототипов являются заполнителями для имен, указанных в схеме для отношения, их не следует понимать буквально.This section describes the classes that are generated using a number of “prototype” classes. Thus, when a relationship declaration is specified, the class that is generated is described. It is important to note that the names of classes, types, and endpoints in prototype classes are placeholders for the names specified in the schema for the relationship; they should not be taken literally.

(1) Сгенерированные типы отношений(1) Generated Relationship Types

В этом разделе описаны классы, которые генерируются для каждого типа отношения. Например:This section describes the classes that are generated for each type of relationship. For example:

<Relationship Name="RelationshipPrototype" BaseType="Holding"><Relationship Name = "RelationshipPrototype" BaseType = "Holding">

<Source Name="Head” ItemType="Foo"/><Source Name = "Head” ItemType = "Foo" />

<Target Name="Tail” ItemType="Bar"<Target Name = "Tail” ItemType = "Bar"

ReferenceType="ItemIDReference"/>ReferenceType = "ItemIDReference" />

<Property Name="SomeProperty" Type="WinFSTypes.String"/><Property Name = "SomeProperty" Type = "WinFSTypes.String" />

</Relationship></Relationship>

Для данного определения отношения будут сгенерированы классы RelationshipPrototype и RelationshipPrototypeCollection. Класс RelationshipPrototype представляет само отношение. Класс RelationshipPrototypeCollection обеспечивает доступ к экземплярам RelationshipPrototype, для которых указанная статья является исходной концевой точкой.For this definition of relationship, the classes RelationshipPrototype and RelationshipPrototypeCollection will be generated. The RelationshipPrototype class represents the relationship itself. The RelationshipPrototypeCollection class provides access to RelationshipPrototype instances for which the specified article is the origin endpoint.

(2) Класс RelationshipPrototype(2) RelationshipPrototype class

Это прототипический класс отношений для отношения поддержки под названием "HoldingRelationshipPrototype", где исходная концевая точка называется "Head" (голова) и задает тип статьи "Foo", и целевая концевая точка называется "Tail" (хвост) и задает тип статьи "Bar". Это задается следующим образом:This is a prototypical relationship class for a support relationship called "HoldingRelationshipPrototype" , where the source endpoint is named "Head" and sets the type of article to "Foo", and the target endpoint is called "Tail" (tail) of and sets the type of article "Bar" . This is set as follows:

public class RelationshipPrototype: Relationshippublic class RelationshipPrototype: Relationship

{{

public RelationshipPrototype(Bar tailItem);public RelationshipPrototype (Bar tailItem);

public RelationshipPrototype(Bar tailItem, string name);public RelationshipPrototype (Bar tailItem, string name);

public RelationshipPrototype(Bar tailItem, string name,public RelationshipPrototype (Bar tailItem, string name,

bool IsOwned);bool IsOwned);

public RelationshipPrototype(Bar tailItem, bool IsOwned);public RelationshipPrototype (Bar tailItem, bool IsOwned);

public RelationshipPrototype(ItemidReferencepublic RelationshipPrototype (ItemidReference

tailItemReference);tailItemReference);

// Получить головную статью (вызывает base.SourceItem).// Get the head article (calls base.SourceItem).

ublic Foo HeadItem {get;}ublic Foo HeadItem {get;}

// Получить хвостовую статью (вызывает base.TargetItem).// Get the tail article (calls base.TargetItem).

public Bar TailItem {get;}public Bar TailItem {get;}

// Представляет дополнительные свойства, объявленные// Represents additional properties declared

// в схеме для отношения. Они генерируются просто как// in the schema for the relationship. They are generated simply as

// свойства в статье или типе вложенного элемента.// properties in the article or type of the nested element.

public string SomeProperty {get; set;}public string SomeProperty {get; set;}

public static ItemSearcher GetSearcher(ItemContextpublic static ItemSearcher GetSearcher (ItemContext

itemContext);itemContext);

public static ItemSearcher GetSearcher(Foo headItem);public static ItemSearcher GetSearcher (Foo headItem);

public static FindResult FindAll(string filter);public static FindResult FindAll (string filter);

public static RelationshipPrototype FindOne(string filter);public static RelationshipPrototype FindOne (string filter);

public static RelationshipPrototype FindOnly(stringpublic static RelationshipPrototype FindOnly (string

filter);filter);

}}

(3) Класс RelationshipPrototypeCollection(3) RelationshipPrototypeCollection Class

Это прототипический класс, генерируемый с классом RelationshipPrototype, который поддерживает коллекцию экземпляров отношения RelationshipPrototype, которыми владеет указанная статья. Он задан следующим образом:This is a prototype class generated with the RelationshipPrototype class, which maintains a collection of RelationshipPrototype instance instances owned by the specified article. It is defined as follows:

public class RelationshipPrototypeCollection:public class RelationshipPrototypeCollection:

VirtualRelationshipCollectionVirtualRelationshipCollection

{{

public RelationshipPrototypeCollection(ItemContextpublic RelationshipPrototypeCollection (ItemContext

itemContext, ItemId headItemId);itemContext, ItemId headItemId);

public void Add(RelationshipPrototype relationship);public void Add (RelationshipPrototype relationship);

public RelationshipPrototype Add(Bar bar);public RelationshipPrototype Add (Bar bar);

public RelationshipPrototype Add(Bar bar, string name);public RelationshipPrototype Add (Bar bar, string name);

public RelationshipPrototype Add(Bar bar, string name,public RelationshipPrototype Add (Bar bar, string name,

bool IsOwned);bool IsOwned);

public RelationshipPrototype Add(Bar bar, bool IsOwned);public RelationshipPrototype Add (Bar bar, bool IsOwned);

public void Remove(RelationshipPrototype relationship);public void Remove (RelationshipPrototype relationship);

public void Remove(Bar bar);public void Remove (Bar bar);

public void Remove(Itemld barItemId);public void Remove (Itemld barItemId);

public void Remove(Relationshipld relationshipId);public void Remove (Relationshipld relationship relationshipId);

public void Remove(string name);public void Remove (string name);

}}

c) Поддержка отношений в классе Itemc) Relationship support in the class Item

Класс Item содержит свойство Relationships, которое обеспечивает доступ к отношениям, в которых статья является источником отношения. Свойство Relationships имеет тип RelationshipCollection.The Item class contains the Relationships property, which provides access to the relationships in which the article is the source of the relationship. The Relationships property is of type RelationshipCollection.

(1) Класс Item(1) Item class

Ниже показан код, представляющий свойства контекста отношения для класса Item:The following code shows the relationship context properties for the Item class:

public abstract class Item: StoreObjectpublic abstract class Item: StoreObject

{{

...

// Коллекция отношений, в которой эта статья является// A collection of relationships in which this article is

// источником.// source.

public RelationshipCollection Relationships {get;}public RelationshipCollection Relationships {get;}

...

}}

(2) Класс RelationshipCollection(2) RelationshipCollection class

Этот класс обеспечивает доступ к экземплярам отношения, в которых данная статья является источником отношения. Он задан следующим образом:This class provides access to instances of relationships in which this article is the source of the relationship. It is defined as follows:

public class RelationshipCollection:public class RelationshipCollection:

VirtualRelationshipCollectionVirtualRelationshipCollection

{{

public RelationshipCollection(ItemContext itemContext,public RelationshipCollection (ItemContext itemContext,

ItemId headItemId);ItemId headItemId);

public void Add(Relationship relationship);public void Add (Relationship relationship);

public Relationship Add(Bar bar);public Relationship Add (Bar bar);

public Relationship Add(Bar bar, string name);public Relationship Add (Bar bar, string name);

public Relationship Add(Bar bar, string name,public Relationship Add (Bar bar, string name,

bool IsOwned);bool IsOwned);

public Relationship Add(Bar bar, bool IsOwned);public Relationship Add (Bar bar, bool IsOwned);

public void Remove(Relationship relationship);public void Remove (Relationship relationship);

public void Remove(Bar bar);public void Remove (Bar bar);

public void Remove(Itemld barItemId);public void Remove (Itemld barItemId);

public void Remove(RelationshipId relationshipId);public void Remove (RelationshipId relationshipId);

public void Remove(string name);public void Remove (string name);

}}

d) Поддержка отношений в выражениях поискаd) Relationship support in search expressions

Можно задать прохождение связи между отношениями и статьями, связанными отношениями, в выражении поиска.You can specify the relationship between relationships and articles related to relationships in a search expression.

(1) Переход от статей к отношениям(1) Transition from articles to relationships

Когда текущий контекст выражения поиска является множеством статей, связь между статьями и экземплярами отношения, в которых статья является источником, можно сделать с использованием свойства Item.Relationships. Связь с отношениями конкретного типа можно задать с использованием оператора Cast выражения поиска.When the current context of the search expression is a set of articles, the relationship between the articles and the relationship instances in which the article is the source can be made using the Item.Relationships property. Relationships with relationships of a particular type can be specified using the Cast operator of a search expression.

В выражении поиска также можно использовать сильно типизированные коллекции отношений (например, Folder.MemberRelationships). Приведение к типу отношения может быть неявным.You can also use strongly typed relationship collections in the search expression (for example, Folder.MemberRelationships). Casting to a relationship type can be implicit.

После задания множества отношений свойства этого отношения доступны для использования в предикатах или в качестве цели проекции. При использовании для задания цели проекции будет возвращено множество отношений. Например, следующее утверждение будет находить все персоны, относящиеся к организации, где свойство StartDate отношений имело значение, большее или равное '1/1/2000'.After defining many relations, the properties of this relation are available for use in predicates or as a projection target. When used to set a projection target, many relationships will be returned. For example, the following statement will find all persons related to the organization where the StartDate property of the relationship had a value greater than or equal to '1/1/2000'.

FindResult result = Person.FindAll(context,FindResult result = Person.FindAll (context,

"Relationships.Cast(Contact.EmployeeOfOrganization).StartDate"Relationships.Cast (Contact.EmployeeOfOrganization) .StartDate

> '1/1/2000'”);> '1/1/2000' ”);

Если тип Person имело свойство EmployerContext типа EmployeeSideEmployerEmployeeRelationships (сгенерированного для типа отношения EmployeeEmployer), это можно записать в виде:If the Person type had an EmployerContext property of the EmployeeSideEmployerEmployeeRelationships type (generated for the EmployeeEmployer relationship type), this can be written as:

FindResult result = Person.FindAll(context,FindResult result = Person.FindAll (context,

"EmployerRelationships.StartDate > '1/1/2000'”);"EmployerRelationships.StartDate> '1/1/2000'”);

(2) Переход от отношений к статьям(2) Transition from relationship to articles

Когда текущий контекст выражения поиска является множеством отношений, связь от отношения к любой концевой точке отношения можно пройти, указав имя концевой точки. После задания множества статей, связанных отношением, свойства этих статей доступны для использования в предикатах или как цель проекции. При использовании для задания цели проекции будет возвращено множество статей. Например, следующее утверждение будет найдено для всех отношений EmployeeOfOrganization (независимо от организации), где фамилия работника - "Smith":When the current context of the search expression is a set of relationships, the relationship from the relationship to any endpoint of the relationship can be passed by specifying the name of the endpoint. After defining many articles related by a relation, the properties of these articles are available for use in predicates or as a projection target. When used for projection purposes, many articles will be returned. For example, the following statement will be found for all EmployeeOfOrganization relationships (regardless of organization), where the employee's last name is "Smith":

FindResult result = EmployeeOfOrganization.FindAll(context,FindResult result = EmployeeOfOrganization.FindAll (context,

"Employee.PersonalNames[SurName='Smith']");"Employee.PersonalNames [SurName = 'Smith']");

Для фильтрации типа статьи концевой точки можно использовать оператор Cast выражения поиска. Например, чтобы найти все экземпляры отношения MemberOfFolder, где членом является статья Person с фамилией "Smith":You can use the Cast operator of a search expression to filter the type of endpoint article. For example, to find all instances of the MemberOfFolder relationship, where the member is a Person article with the last name "Smith":

FindResult result = MemberOfFolder.FindAll(context,FindResult result = MemberOfFolder.FindAll (context,

"Member.Cast(Contact.Person).PersonalNames[Surname='Smith']");"Member.Cast (Contact.Person) .PersonalNames [Surname = 'Smith']");

(3) Комбинирование обхода отношений(3) Combination of circumvention

Два предыдущих шаблона, перехода от статей к отношениям и от отношений к статьям, можно комбинировать для достижения произвольных сложных переходов. Например, чтобы найти все организации с работником по фамилии "Smith":The two previous patterns, the transition from articles to relationships and from relationships to articles, can be combined to achieve arbitrary complex transitions. For example, to find all organizations with an employee named "Smith":

FindResult result = Organization.FindAll(context,FindResult result = Organization.FindAll (context,

"EmployeeRelationships." +"EmployeeRelationships." +

"Employee." +"Employee." +

"PersonalNames[SurName = 'Smith']");"PersonalNames [SurName = 'Smith']");

В нижеследующем примере будут найдены все статьи Person, представляющие людей, живущих в доме, находящемся в области "New York" (TODO: это больше не поддерживается … что является альтернативой).In the following example, all Person articles representing people living in a house located in the New York area will be found (TODO: this is no longer supported ... which is an alternative).

FindResult result = Person.FindAll(context,FindResult result = Person.FindAll (context,

"Relationships.Cast(Contact.MemberOfHousehold)." +"Relationships.Cast (Contact.MemberOfHousehold)." +

"Household." +"Household." +

"Relationships.Cast(Contact.LocationOfHousehold)." +"Relationships.Cast (Contact.LocationOfHousehold)." +

"MetropolitonRegion = 'New York'”);"MetropolitonRegion = 'New York'”);

е) Примеры использования поддержки отношенийe) Examples of using relationship support

Ниже приведены примеры того, как можно использовать поддержку отношений в API платформы хранения для манипулирования отношениями. Для нижеприведенных примеров предположим следующие декларации:The following are examples of how you can use relationship support in a storage platform API to manipulate relationships. For the examples below, suppose the following declarations:

ItemContext ic =...;ItemContext ic = ...;

ItemId fid =...; // ИД статьи папкиItemId fid = ...; // folder article id

Folder folder = Folder.FindById(ic, fid);Folder folder = Folder.FindById (ic, fid);

ItemId sid =...;// ИД статьи источника.ItemId sid = ...; // ID of the source article.

Item source = Item.FindById(ic, sid);Item source = Item.FindById (ic, sid);

ItemId tid =...; // ИД целевой статьи.ItemId tid = ...; // ID of the target article.

Item target = Item.FindById(ic, tid);Item target = Item.FindById (ic, tid);

ItemSearcher searcher = null;ItemSearcher searcher = null;

(1) Поиск отношений(1) Relationship search

Можно искать отношения по источнику или цели. Для выбора отношений указанного типа и тех, кому даны значения свойств, можно использовать фильтры. Фильтры также можно использовать для выбора отношений, основанных на связанном типе статьи или значениях свойства. Например, можно осуществлять следующие поиски:You can search for relationships by source or goal. You can use filters to select relationships of the specified type and those to whom property values are given. Filters can also be used to select relationships based on the associated article type or property values. For example, you can perform the following searches:

Все отношения, где данная статья является источникомAll relationships where this article is the source

searcher = Relationship. GetSearcher(folder);searcher = Relationship. GetSearcher (folder);

foreach(Relationship relationship in searcher.FindAll())...;foreach (Relationship relationship in searcher.FindAll ()) ...;

Все отношения, где данная статья является источником, имя которой совпадает с "A%"All relationships where this article is the source whose name matches "A%"

searcher = Relationship.GetSearcher(folder);searcher = Relationship.GetSearcher (folder);

searcher.Filters.Add("Name like 'A%'");searcher.Filters.Add ("Name like 'A%'");

foreach(Relationship reiationship in searcher.FindAll())...;foreach (Relationship reiationship in searcher.FindAll ()) ...;

Все отношения FolderMember, где данная статья является источникомAll FolderMember relationships where this article is the source

searcher = FolderMember.GetSearcher(folder);searcher = FolderMember.GetSearcher (folder);

foreach(FolderMember folderMember in searcher.FindAll())...;foreach (FolderMember folderMember in searcher.FindAll ()) ...;

Все отношения FolderMember, где данная статья является источником и имеет имя наподобие 'A%'All FolderMember relationships, where this article is the source and has a name like 'A%'

searcher = FolderMember.GetSearcher(folder);searcher = FolderMember.GetSearcher (folder);

searcher.Filters.Add("Name like 'A%'");searcher.Filters.Add ("Name like 'A%'");

foreach(FolderMember folderMember in searcher.FindAll())...;foreach (FolderMember folderMember in searcher.FindAll ()) ...;

Все отношения FolderMember, где целевая статья является PersonAll FolderMember relationships where the target article is Person

searcher = FolderMember.GetSearcher(folder);searcher = FolderMember.GetSearcher (folder);

searcher.Filters.Add("MemberItem.Cast(Person)");searcher.Filters.Add ("MemberItem.Cast (Person)");

foreach(FolderMember folderMember in searcher.FindAll())...;foreach (FolderMember folderMember in searcher.FindAll ()) ...;

Все отношения FolderMember, где целевая статья является Person с Surname "Smith"All FolderMember relationships where the target article is Person with Surname "Smith"

searcher = FolderMember.GetSearcher(folder);searcher = FolderMember.GetSearcher (folder);

searcher.Filters.Add("MemberItem.Cast(Person).PersonalNamessearcher.Filters.Add ("MemberItem.Cast (Person) .PersonalNames

Surname='Smith'");Surname = 'Smith' ");

foreach(FolderMember folderMember inforeach (FolderMember folderMember in

searcher.FindAll())...;searcher.FindAll ()) ...;

Помимо API GetSearcher, показанного выше, каждый класс отношений поддерживает статические API FindAll, FindOne и FindOnly. Кроме того, тип отношения можно задавать, вызывая ItemContext.GetSearcher, ItemContext.FindAll, ItemContext.FindOne или ItemContext.FindOnly.In addition to the GetSearcher API shown above, each relationship class supports the static FindAll, FindOne, and FindOnly APIs. In addition, the relationship type can be set by calling ItemContext.GetSearcher, ItemContext.FindAll, ItemContext.FindOne or ItemContext.FindOnly.

(2) Навигация от отношения к исходной и целевой статьям(2) Navigation from relationship to source and target articles

После извлечения объекта отношения посредством поиска, можно осуществлять «навигацию» к целевой или исходной статье. Базовый класс отношений обеспечивает свойства SourceItem и TargetItem, которые возвращают объект Item. Сгенерированный класс отношений обеспечивает эквивалентные сильно типизированные и именованные свойства (например, FolderMember.FolderItem и FolderMember.MemberItem). Например:After retrieving the relationship object through a search, you can “navigate” to the target or source article. The base relationship class provides the SourceItem and TargetItem properties that return an Item. The generated relationship class provides equivalent strongly typed and named properties (for example, FolderMember.FolderItem and FolderMember.MemberItem). For example:

Навигация к исходной и целевой статье для отношения с именем "Foo"Navigate to source and destination article for relationship named "Foo"

searcher = Relationship.GetSearcher();searcher = Relationship.GetSearcher ();

searcher.Filters.Add("Name='Foo'");searcher.Filters.Add ("Name = 'Foo'");

foreach(Relationship relationship in searcher.FindAll())foreach (Relationship relationship in searcher.FindAll ())

{{

Item source = relationship.SourceItem;Item source = relationship.SourceItem;

Item target = relationship.TargetItem;Item target = relationship.TargetItem;

}}

Навигация к целевой статьеTarget article navigation

searcher = FolderMember.GetSearcher(folder);searcher = FolderMember.GetSearcher (folder);

searcher.Filters.Add("Name like 'A%'");searcher.Filters.Add ("Name like 'A%'");

foreach(FolderMember folderMember in searcher.FindAll())foreach (FolderMember folderMember in searcher.FindAll ())

{{

Item member = folderMember.TargetItem;Item member = folderMember.TargetItem;

...

}}

Навигация к целевой статье работает даже, если целевая статья не находится в домене, где было найдено отношение. В таких случаях API платформы хранения, при необходимости, открывает соединение с целевым доменом. Приложения могут определять, потребуется ли соединение, до извлечения целевой статьи.Navigating to the target article works even if the target article is not in the domain where the relationship was found. In such cases, the storage platform API, if necessary, opens a connection to the target domain. Applications can determine if a connection is required before retrieving the target article.

Проверка целевой статьи в несоединенном доменеChecking destination article in an unconnected domain

searcher = Relationship.GetSearcher(source);searcher = Relationship.GetSearcher (source);

foreach(Relationship relationship in searcher.FindAll())foreach (Relationship relationship in searcher.FindAll ())

{{

if(reltionship.IsTargetDomainConnected)if (reltionship.IsTargetDomainConnected)

{{

Item member = relationship.TargetItem;Item member = relationship.TargetItem;

...

}}

}}

(3) Навигация от исходных статей к отношениям(3) Navigation from source articles to relationships

При данном объекте статьи можно осуществлять навигацию к отношениям, для которых статья является источником, без выполнения явного поиска. Это делается с использованием свойства коллекции Item.Relationships или сильно типизированного свойства коллекции, например, Folder.MemberRelationships. От отношения можно осуществлять навигацию к целевой статье. Такая навигация работает даже, если целевая статья не находится в домене статьи, связанном с ItemContext исходной статьи, в том числе, когда исходная статья не находится в том же хранилище, что и целевая статья. Например:With this article object, you can navigate to relationships for which the article is the source, without performing an explicit search. This is done using the collection property Item.Relationships or a strongly typed collection property, such as Folder.MemberRelationships. From the relationship, you can navigate to the target article. Such navigation works even if the target article is not in the article domain associated with the ItemContext of the source article, including when the source article is not in the same storage as the target article. For example:

Навигация от исходной статьи к отношению и далее к целевым статьямNavigation from source article to relationship and further to target articles

Console.WriteLine("Item {0} is the source of the followingConsole.WriteLine ("Item {0} is the source of the following

relationships:", source.ItemId);relationships: ", source.ItemId);

foreach(Relationship relationship in source.Relationships)foreach (Relationship relationship in source.Relationships)

{{

Item target = relationship.TargetItem;Item target = relationship.TargetItem;

Console.WriteLine("{0} ==> {1}",Console.WriteLine ("{0} ==> {1}",

relationship.RelationshipId, target.ItemId);relationship.RelationshipId, target.ItemId);

}}

Навигация от статьи папки к отношениям Foldermember и далее к целевым статьямNavigating from a folder article to Foldermember relationships and further to target articles

Console.WriteLine("Item {0} is the source of the followingConsole.WriteLine ("Item {0} is the source of the following

relationships:", folder.ItemId);relationships: ", folder.ItemId);

foreach(FolderMember folderMember inforeach (FolderMember folderMember in

folder.MemberRelationships)folder.MemberRelationships)

{{

Item target = folderMember.GetMemberItem();Item target = folderMember.GetMemberItem ();

Console.WriteLine("{0} ==> {1}",Console.WriteLine ("{0} ==> {1}",

folderMember.RelationshipId, target.ItemId);folderMember.RelationshipId, target.ItemId);

}}

Статья может иметь много отношений, поэтому приложения должны использовать предостережение при перечислении коллекции отношений. В общем случае поиск нужно использовать для идентификации конкретных отношений, представляющих интерес, вместо перечисления всей коллекции. Все же, если модель программирования для отношений на основе коллекции достаточно ценна и статьи со многими отношениями достаточно редки, риск совершения неправильного действия со стороны разработчика оправдан. Приложения могут проверять ряд отношений в коллекции и, при необходимости, использовать другую модель программирования. Например:An article can have many relationships, so applications should use caution when listing collections of relationships. In general, searches should be used to identify specific relationships of interest, rather than listing the entire collection. Nevertheless, if the programming model for collection-based relationships is valuable enough and articles with many relationships are rare enough, the risk of committing the wrong action by the developer is justified. Applications can check a number of relationships in a collection and, if necessary, use a different programming model. For example:

Проверка размера коллекции отношенийChecking the size of a relationship collection

if(folder.MemberRelationships.Count > 1000 )if (folder.MemberRelationships.Count> 1000)

{{

Console.WriteLine("Too many relationships!");Console.WriteLine ("Too many relationships!");

}}

elseelse

{{

...

}}

Вышеописанные коллекции отношений являются «виртуальными» в том смысле, что они в действительности не заполняются объектами, которые представляют каждое отношение, пока приложение не предпринимает попытку перечислить коллекцию. Если коллекция перечисляется, результаты отражают то, что находится в хранилище, плюс то, что добавлено приложением, но пока не сохранено, но не любые отношения, которые были удалены приложением, но не сохранены.The relationship collections described above are “virtual” in the sense that they are not actually populated with objects that represent each relationship until the application makes an attempt to list the collection. If the collection is listed, the results reflect what is in the repository, plus what is added by the application, but not yet saved, but not any relationship that was deleted by the application but not saved.

(4) Создание отношений (и статей)(4) Creating relationships (and articles)

Новые отношения создаются путем создания объекта отношения, добавления его в коллекцию отношений в исходной статье и обновления ItemContext. Для создания новой статьи нужно создать отношение поддержки или внедрения. Например:New relationships are created by creating a relationship object, adding it to the relationship collection in the original article, and updating the ItemContext. To create a new article, you need to create a support or implementation relationship. For example:

Добавление новой статьи к существующей старойAdding a new article to an existing old

Bar bar = new Bar();Bar bar = new Bar ();

folder.Relationships.Add(new FolderMember(bar, "name"));folder.Relationships.Add (new FolderMember (bar, "name"));

ic.Update();ic.Update ();

// или// or

Bar bar = new Bar();Bar bar = new Bar ();

folder.MemberRelationships.Add(new FolderMember(bar, "name"));folder.MemberRelationships.Add (new FolderMember (bar, "name"));

ic.Update();ic.Update ();

// или// or

Bar bar = new Bar();Bar bar = new Bar ();

folder.MemberRelationships.Add(bar, name);folder.MemberRelationships.Add (bar, name);

ic.Update();ic.Update ();

Добавление существующей статьи к существующей папкеAdding an existing article to an existing folder

folder.MemberRelationships.Add(target, "name");folder.MemberRelationships.Add (target, "name");

ic.Update();ic.Update ();

Добавление существующей статьи к новой папкеAdding an existing article to a new folder

Folder existingFolder = ic.FindItemById(fid) as Folder;Folder existingFolder = ic.FindItemById (fid) as Folder;

Folder newFolder = new Folder();Folder newFolder = new Folder ();

existingFolder.MemberRelationships.Add( newFolder, "a name");existingFolder.MemberRelationships.Add (newFolder, "a name");

newFolder.MemberRelationships.Add(target, "a name");newFolder.MemberRelationships.Add (target, "a name");

ic.Update();ic.Update ();

Добавление новой статьи к новой папкеAdding a new article to a new folder

Folder existingFolder = ic.FindItemById(fid) as Folder;Folder existingFolder = ic.FindItemById (fid) as Folder;

Folder newFolder = new Folder();Folder newFolder = new Folder ();

existingFolder.MemberRelationships.Add(newFolder, "a name");existingFolder.MemberRelationships.Add (newFolder, "a name");

Bar bar = new Bar();Bar bar = new Bar ();

newFolder.MemberRelationships.Add(bar, "a name");newFolder.MemberRelationships.Add (bar, "a name");

ic.Update();ic.Update ();

(5) Удаление отношений (и статей)(5) Deleting relationships (and articles)

Удаление отношения поддержкиDeleting a Support Relationship

// Если ИД исходной статьи и отношения известны…// If the ID of the source article and the relationship are known ...

RelationshipId rid =...;RelationshipId rid = ...;

Relationship r = ic.FindRelationshipById(fid, rid);Relationship r = ic.FindRelationshipById (fid, rid);

r.MarkForDelete;r.MarkForDelete;

ic.Update();ic.Update ();

// Иначе…// Otherwise ...

folder.MemberRelationships.Remove(target);folder.MemberRelationships.Remove (target);

ic.Update();ic.Update ();

8. «Расширение» API платформы хранения8. "Extension" of the storage platform API

Согласно отмеченному выше каждая схема платформы хранения порождает множество классов. Эти классы имеют стандартные методы, например Find*, а также имеют свойства для получения и задания значений полей. Эти классы и соответствующие методы образуют основу API платформы хранения.As noted above, each storage platform scheme generates many classes. These classes have standard methods, for example, Find *, and also have properties for getting and setting field values. These classes and associated methods form the basis of the storage platform API.

a) Поведения доменаa) Domain Behaviors

Помимо этих стандартных методов, каждая схема имеет множество методов, зависящих от домена. Перечислим эти поведения домена. Например, некоторые из поведений домена в Схеме контактов таковы:In addition to these standard methods, each scheme has many domain-specific methods. We list these domain behaviors. For example, some of the domain behaviors in the Contact Scheme are as follows:

- Пригоден ли адрес электронной почты?- Is the email address suitable?

- Для данной папки, получить коллекцию всех элементов папки.- For a given folder, get a collection of all the items in the folder.

- Для данного ИД статьи, получить объект, представляющий эту статью.- For a given article ID, get the object representing this article.

- Для данного лица, получить его онлайновый статус.- For a given person, get his online status.

- Помощник функционирует для создания нового контакта или временного контакта.- The assistant functions to create a new contact or temporary contact.

- И т.д.- Etc.

Важно отметить, что, хотя мы делаем различия между «стандартными» поведениями (Find* и т.д.) и поведениями домена, для программиста они выглядят просто методами. Различие между этими методами заключается в том, что стандартные поведения генерируются автоматически из файлов схемы инструментами среды разработки API платформы хранения, тогда как поведения домена закодированы аппаратно.It is important to note that although we make a distinction between “standard” behaviors (Find *, etc.) and domain behaviors, for a programmer they look just like methods. The difference between these methods is that standard behaviors are automatically generated from the schema files by the tools of the storage platform API development environment, while domain behaviors are encoded in hardware.

По своей природе эти поведения домена должны задаваться вручную. Это создает практическую проблему: начальная версия C# требует, чтобы вся реализация класса была в едином файле. Для этого приходится редактировать самогенерирующиеся файлы классов для добавления поведений домена. Это само по себе может составлять проблему.By nature, these domain behaviors must be manually defined. This poses a practical problem: the initial version of C # requires that the entire class implementation be in a single file. To do this, you have to edit the self-generated class files to add domain behavior. This in itself can be a problem.

Для решения подобных проблем в C# был введен признак, именуемый частичными классами. В основном, частичный класс допускает реализацию классов для охвата множественных файлов. Частичный класс - это то же самое, что регулярный класс за исключением того, что его декларации предшествует ключевое слово partial:To solve such problems, a feature called partial classes was introduced in C #. Basically, a partial class allows classes to span multiple files. A partial class is the same as a regular class except that its declaration is preceded by the partial keyword:

partial public class Person: DerivedItemBasepartial public class Person: DerivedItemBase

{{

// реализация// implementation

}}

Теперь поведения домена для Person можно поместить в другой файл, например, так:Now the domain behavior for Person can be placed in another file, for example, like this:

partial public class Personpartial public class Person

{{

public EmailAddress PrimaryEmailAddresspublic EmailAddress PrimaryEmailAddress

{{

get {/*реализация*/}get {/ * implementation * /}

}}

}}

b) Поведения добавления значенийb) Add Value Behaviors

Классы данных с поведениями домена образуют основу, на которой разработчик строит приложения. Однако невозможно, а также нежелательно, чтобы классы данных открывали каждое мыслимое поведение, относящееся к этим данным. Платформа хранения позволяет разработчику строить на базовых функциональных возможностях, обеспечиваемых API платформы хранения. Основным шаблоном здесь является написание класса, методы которого принимают один или более классов данных платформы хранения в качестве параметров. Например, классы добавления значения для отправки электронной почты с использованием Microsoft Outlook или с использованием службы сообщений Microsoft Windows могут иметь следующий вид:Data classes with domain behaviors form the foundation on which a developer builds applications. However, it is both impossible and undesirable for data classes to expose every conceivable behavior related to that data. The storage platform allows the developer to build on the basic functionality provided by the storage platform API. The main template here is to write a class whose methods take one or more data classes of the storage platform as parameters. For example, the add value classes for sending email using Microsoft Outlook or using the Microsoft Windows messaging service might look like this:

MailMessage m = MailMessage.FindOne(...);MailMessage m = MailMessage.FindOne (...);

OutlookEMailServices.SendMessage(m);OutlookEMailServices.SendMessage (m);

Person p = Person.FindOne(...);Person p = Person.FindOne (...);

WindowsMessagerServices m = new WindowsMessagerServices(p);WindowsMessagerServices m = new WindowsMessagerServices (p);

m.MessageReceived += new MessageReceivedHandler(f);m.MessageReceived + = new MessageReceivedHandler (f);

m.SendMessage("Hello");m.SendMessage ("Hello");

Эти классы добавления значения можно регистрировать с помощью платформы хранения. Данные регистрации связаны с метаданными схемы, которые платформа хранения поддерживает для каждого установленного типа платформы хранения. Эти метаданные хранятся как статьи платформы хранения и могут запрашиваться.These value adding classes can be registered using the storage platform. Registration data is associated with the metadata of the schema that the storage platform supports for each installed type of storage platform. This metadata is stored as storage platform articles and may be requested.

Регистрация классов добавления значения является мощным признаком; например, она допускает следующий сценарий: кликнув правой кнопкой мыши по объекту Person в обозревателе оболочки, можно вывести набор допустимых действий из классов добавления значения, зарегистрированных для Person.Registering add value classes is a powerful feature; for example, it allows the following scenario: by right-clicking on the Person object in the shell browser, you can display a set of valid actions from the add classes registered for Person.

с) Поведения добавления значения как поставщики услугc) Value-adding behaviors as service providers

Согласно данному варианту осуществления API платформы хранения обеспечивает механизм, посредством которого классы добавления значения можно регистрировать как «услуги» для данного типа. Это позволяет приложению задавать и получать поставщиков услуг (= классы добавления значения) данного типа. Классы добавления значения, желающие использовать этот механизм, должны реализовать общеизвестный интерфейс; например:According to this embodiment, the storage platform API provides a mechanism by which value adding classes can be registered as “services” for a given type. This allows the application to set and receive service providers (= value adding classes) of a given type. Value adding classes that want to use this mechanism must implement a well-known interface; eg:

interface IChatServicesinterface IChatServices

{{

void SendMessage(string msg);void SendMessage (string msg);

event MessageReceivedHandler MessageReceived;event MessageReceivedHandler MessageReceived;

}}

class WindowsMessengerServices: IChatServicesclass WindowsMessengerServices: IChatServices

{{

...

}}

class YahooMessengerServices: IChatServicesclass YahooMessengerServices: IChatServices

{{

...

}}

Все классы данных API платформы хранения реализуют интерфейс ICachedServiceProvider. Этот интерфейс расширяет интерфейс System.IServiceProvider следующим образом:All storage platform API data classes implement the ICachedServiceProvider interface. This interface extends the System.IServiceProvider interface as follows:

interface ICachedServiceProvider: System.IServiceProviderinterface ICachedServiceProvider: System.IServiceProvider

{{

void SetService(System.Type type, Object provider);void SetService (System.Type type, Object provider);

void RemoteService(System.Type type);void RemoteService (System.Type type);

}}

С помощью этого интерфейса приложения могут задавать экземпляр поставщика услуг, а также запрашивать поставщика услуг конкретного типа.Using this interface, applications can define an instance of a service provider, as well as request a specific type of service provider.

Для поддержки этого интерфейса класс данных платформы хранения поддерживает хэш-таблицу поставщиков услуг, где они распределены по типам. При запросе поставщика услуг реализация сначала смотрит в хэш-таблицу, чтобы проверить, задан ли поставщик услуг указанного типа. Если нет, инфраструктура запрашиваемого поставщика услуг используется для идентификации поставщика услуг указанного типа. Затем создается экземпляр этого поставщика услуг, он добавляется в хэш-таблицу и возвращается. Заметим, что возможен также совместно используемый метод на классе данных для запрашивания поставщика услуг и передачи операции этому поставщику услуг. Например, это можно использовать для обеспечения метода Send на классе почтовых сообщений, который использует систему электронной почты, указанную пользователем.To support this interface, the storage platform data class maintains a hash table of service providers, where they are distributed by type. When asked by the service provider, the implementation first looks in the hash table to check whether the service provider of the specified type is specified. If not, the infrastructure of the requested service provider is used to identify the service provider of the specified type. Then an instance of this service provider is created, it is added to the hash table and returned. Note that a shared method on a data class is also possible to query a service provider and transfer the operation to that service provider. For example, this can be used to provide the Send method on a mailing class that uses the email system specified by the user.

9. Структура среды разработки9. The structure of the development environment

В этом разделе описано, как схема платформы хранения получает превращенные в API платформы хранения классы на клиенте и классы UDT на сервере согласно данному варианту осуществления изобретения. Диаграмма на фиг.24 демонстрирует используемые компоненты.This section describes how the storage platform diagram obtains the classes converted to the storage platform APIs on the client and UDT classes on the server according to this embodiment of the invention. The diagram in FIG. 24 shows the components used.

Согласно фиг.24 типы в схеме содержатся в файле XML (блок 1). Этот файл также содержит ограничения уровня полей и уровня статей, связанные со схемой. Генератор классов платформы хранения (xfs2cs.exe - блок 2) берет этот файл и генерирует частичные классы для UDT хранилища (блок 5) и частичные классы для классов клиента (блок 3). Для каждого домена схемы существуют дополнительные методы, которые мы называем поведениями домена. Существуют поведения домена, имеющие смысл на хранилище (блок 7), на клиенте (блок 6) и в обоих местах (блок 4). Код в блоках 4, 6 и 7 пишется вручную (не генерируется автоматически). Частичные классы в блоках 3, 4 и 6 совместно образуют полную реализацию классов для классов доменов API платформы хранения. Блоки 3, 4 и 6 компилируются (блок 8) для формирования классов API платформы хранения - блок 11 (фактически, API платформы хранения это результат компиляции блоков 3, 4 и 6, полученных из всех доменов начальной схемы). Помимо классов доменов существуют также дополнительные классы, реализующие поведение добавления значения. Эти классы используют один или более классов в одном или более доменов схемы. Это представлено блоком 10. Частичные классы в блоках 4, 5 и 7 совместно образуют полную реализацию классов для классов UDT сервера. Блоки 4, 5 и 7 компилируются (блок 9) для формирования ассемблера UDT стороны сервера - блок 12 (фактически, ассемблер UDT стороны сервера является результатом компиляции и плюсования блоков 4, 5 и 7, полученных из всех доменов начальной схемы). Модуль генератора команд DDL [ЯОД?] (блок 13) берет ассемблер UDT (блок 12) и файл схемы (блок 1) и устанавливает их на хранилище данных. Этот процесс предполагает, помимо прочего, генерацию таблиц и видов для типов в каждой схеме.24, the types in the schema are contained in an XML file (block 1). This file also contains the field level and article level restrictions associated with the schema. The storage platform class generator (xfs2cs.exe - block 2) takes this file and generates partial classes for the UDT storage (block 5) and partial classes for the client classes (block 3). There are additional methods for each schema domain that we call domain behaviors. There are domain behaviors that make sense on the store (block 7), on the client (block 6), and in both places (block 4). The code in blocks 4, 6 and 7 is written manually (not automatically generated). The partial classes in blocks 3, 4, and 6 together form the complete class implementation for the domain classes of the storage platform APIs. Blocks 3, 4, and 6 are compiled (block 8) to form storage platform API classes — block 11 (in fact, the storage platform API is the result of compiling blocks 3, 4, and 6 obtained from all domains in the initial schema). In addition to domain classes, there are also additional classes that implement value-adding behavior. These classes use one or more classes in one or more schema domains. This is represented by block 10. The partial classes in blocks 4, 5, and 7 together form the complete implementation of the classes for the server UDT classes. Blocks 4, 5 and 7 are compiled (block 9) to form the server-side UDT assembler - block 12 (in fact, the server-side UDT assembler is the result of compiling and adding blocks 4, 5, and 7 obtained from all domains of the initial circuit). The DDL command generator module [YaD?] (Block 13) takes the UDT assembler (block 12) and the schema file (block 1) and installs them in the data warehouse. This process involves, among other things, generating tables and views for types in each schema.

10. Формализм запросов10. Request formalism

Будучи приведен к основам, шаблон приложения при использовании API платформы хранения представляет собой: открытие ItemContext; использование Find с критерием фильтрации для извлечения нужных объектов; манипулирование объектами; отправку изменений обратно в хранилище. Этот раздел посвящен синтаксису строки фильтра.Being reduced to the basics, the application template when using the storage platform API is: opening ItemContext; Using Find with filter criteria to retrieve the desired objects; manipulation of objects; sending changes back to the repository. This section focuses on the syntax of the filter string.

Строка фильтра, обеспечиваемая при отыскании объектов данных платформы хранения, описывает, каким условиям должны удовлетворять свойства объектов, чтобы их можно было возвратить. Синтаксис, используемый API платформы хранения, поддерживает приведения типов и обход отношений.The filter string provided when retrieving data objects from the storage platform describes what conditions the properties of the objects must satisfy in order to be returned. The syntax used by the storage platform API supports type casting and relationship traversal.

а) Основы фильтрацииa) Basics of filtration

Строка фильтра либо пуста, что указывает на необходимость возвращения всех объектов данного типа, либо является логическим выражением, которому должен удовлетворять каждый возвращаемый объект. Среда выполнения API платформы хранения знает, как эти имена свойств отображаются в имена полей типа платформы хранения и, в конце концов, в виды SQL, поддерживаемые хранилищем платформы хранения.The filter string is either empty, which indicates the need to return all objects of a given type, or is a logical expression that each returned object must satisfy. The storage platform API runtime knows how these property names are mapped to field names such as the storage platform and, ultimately, to the SQL views supported by the storage platform storage.

Рассмотрим следующие примеры:Consider the following examples:

// Найти всех людей// Find all the people

FindResult res1 = Person.FindAll(ctx)FindResult res1 = Person.FindAll (ctx)

// Найти всех людей, имеющих значение свойства Gender (пол)// Find all people who have a Gender property value (gender)

// равное "Male" (мужской)// equal to "Male" (male)

FindResult res2 = Person.FindAll(ctx, "Gender='Male'")FindResult res2 = Person.FindAll (ctx, "Gender = 'Male'")

// Найти всех людей, имеющих значение свойства Gender,// Find all people who have a Gender property value,

// равное "Male", и родившихся в прошлом тысячелетии.// equal to "Male", and born in the past millennium.

FindResult res3 = Person.FindAll(FindResult res3 = Person.FindAll (

ctx,ctx

"Gender='Male' And Birthdate < '1/1/2001'”)"Gender = 'Male' And Birthdate <'1/1/2001'”)

В фильтре также можно использовать вложенные объекты свойства. Например:You can also use nested property objects in the filter. For example:

// Найти всех людей, измененных за последние 24 часа// Find all people changed in the last 24 hours

FindResult res1 = Person.FindAll(FindResult res1 = Person.FindAll (

ctx,ctx

String.Format("Item.Modified > '{0}'",String.Format ("Item.Modified> '{0}'",

DateTime.Now.Subtract(new TimeSpan(24,0,0))));DateTime.Now.Subtract (new TimeSpan (24,0,0))));

Для коллекций, можно фильтровать члены, используя условия в квадратных скобках. Например:For collections, you can filter members using conditions in square brackets. For example:

// Найти всех людей по имени "John" и по фамилии "Smith"// Find all people by the name "John" and by the name "Smith"

FindResult res1 = Person.FindAll(FindResult res1 = Person.FindAll (

ctx,ctx

"PersonalNames[GivenName='John' And Surname='Smith']")"PersonalNames [GivenName = 'John' And Surname = 'Smith']")

// Найти всех людей с адресом в реальном времени от провайдера// Find all people with a real-time address from the provider

// 'x' и с категорией онлайнового статуса 'y'// 'x' and with the online status category 'y'

FindResult res2 = Person.FindAll(FindResult res2 = Person.FindAll (

ctx,ctx

"PersonalRealtimeAddress[ProviderURI='x'].BasicPresence." +"PersonalRealtimeAddress [ProviderURI = 'x']. BasicPresence." +

"OnlineStatus.Category='y'")"OnlineStatus.Category = 'y'")

В нижеследующем примере перечисляются все люди, рожденные с 12/31/1999:The following example lists all people born on 12/31/1999:

ItemContext ctx = ItemContext.Open("Work Contacts");ItemContext ctx = ItemContext.Open ("Work Contacts");

FindResult results =FindResult results =

Person.FindAll(ctx, "Birthdate > '12/31/1999'”Person.FindAll (ctx, "Birthdate> '12 / 31/1999 '”

foreach(Person person in results)foreach (Person person in results)

Console.WriteLine(person.DisplayName);Console.WriteLine (person.DisplayName);

ctx.Close();ctx.Close ();

Строка 1 создает новый объект ItemContext для доступа к "Work Contacts" на совместно используемом ресурсе платформы хранения на локальном компьютере. Строки 3 и 4 получают коллекцию объектов Person, где свойство Birthdate указывает время после 12/31/1999, что задано выражением "Birthdate > '12/31/1999'". Выполнение операции FindAll проиллюстрировано на фиг.23.Line 1 creates a new ItemContext to access the “Work Contacts” on the shared storage platform resource on the local computer. Lines 3 and 4 receive a collection of Person objects, where the Birthdate property indicates the time after 12/31/1999, which is specified by the expression "Birthdate> '12 / 31/1999 '". The execution of the FindAll operation is illustrated in FIG.

b) Приведения типовb) Type casts

Часто случается так, что тип значения, хранящегося в свойстве, выводится из объявленного типа свойств. Например, свойство PersonalEAddresses в Person содержит коллекцию типов, выведенных из EAddress, например, EMailAddress и TelephoneNumber. Для фильтрации на основании регионального телефонного кода необходимо перейти от типа EAddress к типу TelephoneNumber:It often happens that the type of value stored in a property is inferred from the declared property type. For example, the PersonalEAddresses property in Person contains a collection of types derived from EAddress, for example, EMailAddress and TelephoneNumber. To filter based on the area code, you must switch from the EAddress type to the TelephoneNumber type:

// Найти всех людей с телефонным номером, имеющим// Find all people with a phone number that has

// региональный код 425// region code 425

FindResult res1 = Person.FindAll(FindResult res1 = Person.FindAll (

ctx,ctx

"PersonalEAddresses." +"PersonalEAddresses." +

"Cast(System.Storage.Contact.TelephoneNumber))." +"Cast (System.Storage.Contact.TelephoneNumber))." +

"AreaCode='425"');"AreaCode = '425"');

// Альтернативно, можно передать имя типа следующим образом:// Alternatively, you can pass the type name as follows:

FindResult res1 = Person.FindAll(FindResult res1 = Person.FindAll (

ctx,ctx

String.Format("PersonalEAddresses.Cast({0})).AreaCode='425',String.Format ("PersonalEAddresses.Cast ({0})). AreaCode = '425',

typeof(TelephoneNumber).FullName))typeof (TelephoneNumber) .FullName))

с) Синтаксис фильтраc) Filter syntax

Ниже описан синтаксис фильтра, поддерживаемый API платформы хранения, согласно одному варианту осуществления.The following describes the filter syntax supported by the storage platform API according to one embodiment.

Filter::= EmptyFilter | ConditionFilter :: = EmptyFilter | Condition

EmptyFilter::=EmptyFilter :: =

Condition::= SimpleCondition | CompoundCondition |Condition :: = SimpleCondition | CompoundCondition |

ParenthesizedConditionParentalized condition

SimpleCondition::= ExistanceCheck | ComparisonSimpleCondition :: = ExistanceCheck | Comparison

ExistanceCheck::= PropertyReferenceExistanceCheck :: = PropertyReference

Comparison::= PropertyReference ComparisonOp ConstantComparison :: = PropertyReference ComparisonOp Constant

CompoundCondition::= SimpleCondition BooleanOp ConditionCompoundCondition :: = SimpleCondition BooleanOp Condition

ParenthesizedCondition::= '('Condition')'ParenthesizedCondition :: = '(' Condition ')'

ComparisonOp::='!=' | '==' | '=' | '<' | '>' | '>=' | '<='ComparisonOp :: = '! =' | '==' | '=' | '<' | '>' | '> =' | '<='

BooleanOp::= 'And' | '&&' | 'Or' | '||'BooleanOp :: = 'And' | '&&' | 'Or' | '||'

Constant::= StringConstant | NumericConstatantConstant :: = StringConstant | NumericConstatant

StringConstant:: ''' (любой символ Unicode)* '''StringConstant :: '' '(any Unicode character) *' ''

Примечание: внедренные символы ' устраняются дублированиемNote: embedded characters are eliminated by duplication.

NumericConstant::= 0-9*NumericConstant :: = 0-9 *

PropertyReference::= SimplePropertyName |PropertyReference :: = SimplePropertyName |

CompoundPropertyNameCompoundPropertyName

SimplePropertyName::= (все символы Unicode за исключениемSimplePropertyName :: = (all Unicode characters except

'.' и пробела)* Filter?'.' and space) * Filter?

Filter::= '[' Condition ']'Filter :: = '[' Condition ']'

CompoundPropertyName::=CompoundPropertyName :: =

(TypeCast | RelationshipTraversal |(TypeCast | RelationshipTraversal |

SimplePropertyName) '. ' PropertyReferenceSimplePropertyName) '. 'PropertyReference

TypeCast::= 'Cast(' TypeName ')'TypeCast :: = 'Cast (' TypeName ')'

RelationshipTraversal::= TraversalToSource |RelationshipTraversal :: = TraversalToSource |

TraversalToTargetTraversalToTarget

TraversalToSource::= 'Source('FullRelationshipName')'TraversalToSource :: = 'Source (' FullRelationshipName ')'

TraversalToTarget::= 'Target('FullRelationshipName')'TraversalToTarget :: = 'Target (' FullRelationshipName ')'

TypeName::= полностью уточненное имя типа CLRTypeName :: = fully qualified CLR type name

FullRelationshipName::= SchemaName '.' RelationshipNameFullRelationshipName :: = SchemaName '.' RelationshipName

SchemaName::= the storage platformNameSchemaName :: = the storage platformName

RelationshipName::= the storage platformNameRelationshipName :: = the storage platformName

the storage platformName::= заданное в [SchemaDef]the storage platformName :: = specified in [SchemaDef]

11. Удаленные операции11. Remote operations

а) Локальная/удаленная прозрачность в APIa) Local / remote transparency in the API

Доступ к данным в платформе хранения нацелен на экземпляр локальной платформы хранения. Локальный экземпляр служит маршрутизатором, если запрос (или его часть) ссылается на удаленные данные. Таким образом, уровень API обеспечивает локальную/удаленную прозрачность: не существует структурной разницы в API между локальным и удаленным доступом к данным. Это исключительно функция запрашиваемой области действия.Access to data in the storage platform targets an instance of the local storage platform. The local instance serves as a router if the request (or part of it) refers to remote data. Thus, the API layer provides local / remote transparency: there is no structural difference in the API between local and remote data access. This is solely a function of the requested scope.

Хранилище данных платформы хранения также реализует распределенные запросы; таким образом, можно соединяться с экземпляром локальной платформы хранения и осуществлять запрос, который включает в себя статьи из разных томов, некоторые из которых находятся на локальном хранилище, а некоторые - на удаленном хранилище. Хранилище объединяет результаты и представляет их приложению. С точки зрения API платформы хранения (а, стало быть, и разработчика приложения) любой удаленный доступ полностью гладкий и прозрачный.The storage platform data warehouse also implements distributed queries; thus, you can connect to an instance of the local storage platform and make a request that includes articles from different volumes, some of which are located on local storage, and some on remote storage. The repository combines the results and presents them to the application. From the point of view of the storage platform API (and, therefore, the application developer), any remote access is completely smooth and transparent.

API платформы хранения позволяет приложению определять, представляет ли данный объект ItemContext (возвращаемый методом ItemContext.Open) локальное или удаленное соединение с использованием свойства IsRemote - это свойство на объекте ItemContext. Помимо прочего, приложение может пожелать обеспечить визуальную обратную связь, в помощь ожиданиям пользователя относительно производительности, надежности и т.д.The storage platform API allows the application to determine whether a given ItemContext (returned by the ItemContext.Open method) represents a local or remote connection using the IsRemote property - this is a property on the ItemContext. Among other things, the application may wish to provide visual feedback to help user expectations regarding performance, reliability, etc.

b) Реализация удаленных операций в платформе храненияb) Implementing remote operations on the storage platform

Хранилища данных платформы хранения разговаривают друг с другом с использованием особого провайдера OLEDB, который действует над HTTP (провайдер OLEDB по умолчанию использует TDS). В одном варианте осуществления распределенный запрос проходит через функциональную возможность OPENROWSET машины реляционной базы данных. Для осуществления фактических удаленных операций обеспечена специальная функция, заданная пользователем (UDF): DoRemoteQuery(server, queryText).Storage platform data stores talk to each other using a special OLEDB provider that acts on HTTP (the OLEDB provider uses TDS by default). In one embodiment, a distributed query passes through the OPENROWSET functionality of a relational database engine. For actual remote operations, a special user-defined function (UDF) is provided: DoRemoteQuery (server, queryText).

с) Доступ к хранилищам, не относящимся к платформе храненияc) Access to non-storage vaults

Согласно одному варианту осуществления платформы хранения настоящего изобретения не существует общей архитектуры провайдера, которая позволяет любому хранилищу участвовать в доступе к данным платформы хранения. Однако обеспечена ограниченная архитектура провайдера для конкретного случая Microsoft Exchange и Microsoft Active Directory (AD). При этом предполагается, что разработчики могут использовать API платформы хранения и осуществлять доступ к данным в AD и Exchange, как если бы они были в платформе хранения, но что данные, к которым они осуществляют доступ, ограничиваются схематизированными типами платформы хранения. Таким образом, адресная книжка (= коллекция типов Person платформы хранения) поддерживается в AD, и почта, календарь и контакты поддерживаются для Exchange.According to one embodiment of the storage platform of the present invention, there is no general provider architecture that allows any storage to participate in accessing the storage platform data. However, a limited provider architecture is provided for the specific case of Microsoft Exchange and Microsoft Active Directory (AD). It is assumed that developers can use the storage platform APIs and access data in AD and Exchange as if they were in a storage platform, but that the data they access is limited to schematized types of storage platform. Thus, the address book (= collection of Person types of the storage platform) is supported in AD, and mail, calendar, and contacts are supported for Exchange.

d) Отношение к DFSd) Relation to DFS

Промоутер свойств платформы хранения не продвигает прошлые точки установки. Несмотря на то, что пространство имен достаточно богато для осуществления доступа через установочные точки, запросы через них не проходят. Тома платформы хранения могут выглядеть как концевые узлы в дереве DFS.The storage platform property promoter does not advance past installation points. Although the namespace is rich enough to access through the setpoints, requests do not go through them. Storage platform volumes may look like endpoints in a DFS tree.

е) Отношение к GXA/Indigof) Attitude towards GXA / Indigo

Разработчик может использовать API платформы хранения для открытия «головы GXA» поверх хранилища данных. В принципе, здесь нет никакого отличия от создания любой другой веб-услуги. API платформы хранения не разговаривает с хранилищем данных платформы хранения с использованием GXA. Согласно отмеченному выше, API разговаривает с локальным хранилищем с использованием TDS; локальное хранилище манипулирует любыми удаленными операциями с использованием услуги синхронизации.A developer can use the storage platform APIs to open the “GXA head” on top of the data warehouse. Basically, there is no difference from creating any other web service. The storage platform API does not talk to the storage platform data warehouse using GXA. As noted above, the API talks to local storage using TDS; local storage manipulates any remote operations using the synchronization service.

12. Ограничения12. Limitations

Модель данных платформы хранения допускает ограничения значений на типах. Эти ограничения оцениваются на хранилище автоматически, и процесс является прозрачным для пользователя. Заметим, что ограничения проверяются на сервере. Иногда, как отмечено здесь, желательно давать разработчику гибкость в проверке того, что входные данные удовлетворяют ограничениям, не создавая служебной нагрузки обратной передачи на сервер. Это особенно полезно в интерактивных приложениях, где конечный пользователь вводит данные, которые используются для наполнения объекта. API платформы хранения обеспечивает этот механизм.The storage platform data model allows value restrictions on types. These restrictions are evaluated on the repository automatically, and the process is transparent to the user. Note that restrictions are checked on the server. Sometimes, as noted here, it is advisable to give the developer the flexibility to verify that the input satisfies the constraints without creating a postback overhead to the server. This is especially useful in interactive applications where the end user enters data that is used to populate an object. The storage platform API provides this mechanism.

Напомним, что схема платформы хранения задана в файле XML, который используется платформой хранения для генерации соответствующих объектов базы данных, представляющих схему. Она также используется структурой среды разработки API платформы хранения для автоматической генерации классов.Recall that the storage platform schema is defined in an XML file that is used by the storage platform to generate the corresponding database objects representing the schema. It is also used by the storage platform API development framework framework to automatically generate classes.

Ниже частично приведен текст файла XML, используемого для генерации Схемы контактов:The following is partially the text of the XML file used to generate the Contact Schema:

<Schema Name="Contacts" MajorVersion="1" MinorVersion="8”><Schema Name = "Contacts" MajorVersion = "1" MinorVersion = "8”>

<ReferencedSchema Name="Base" MajorVersion="1"/><ReferencedSchema Name = "Base" MajorVersion = "1" />

<Type Name="Person" MajorVersion=”1" MinorVersion="0"<Type Name = "Person" MajorVersion = ”1" MinorVersion = "0"

ExtendsType="Principal" ExtendsVersion="1">ExtendsType = "Principal" ExtendsVersion = "1">

<Field Name="Birthdate" Type="the storage<Field Name = "Birthdate" Type = "the storage

platformTypes.datetime"platformTypes.datetime "

Nullable="true" MultiValued="false"/>Nullable = "true" MultiValued = "false" />

<Field Name="Gender" Type="the storage<Field Name = "Gender" Type = "the storage

platformTypes.nvarchar(16)"platformTypes.nvarchar (16) "

Nullable="true" MultiValued="false"/>Nullable = "true" MultiValued = "false" />

<Field Name="PersonalNames" Type="FullName"<Field Name = "PersonalNames" Type = "FullName"

TypeMajorVersion="1"TypeMajorVersion = "1"

Nullable="true" MultiValued="true"/>Nullable = "true" MultiValued = "true" />

<Field Name="PersonalEAddresses" Type="EAddress"<Field Name = "PersonalEAddresses" Type = "EAddress"

TypeMajorVersion="1" Nullable="true"TypeMajorVersion = "1" Nullable = "true"

MultiValued="true"/>MultiValued = "true" />

<Field Name="PersonalPostalAddresses"<Field Name = "PersonalPostalAddresses"

Type="PostalAddress"Type = "PostalAddress"

TypeMajorVersion="1" Nullable="true"TypeMajorVersion = "1" Nullable = "true"

MultiValued="true"/>MultiValued = "true" />

<Check>expression</Check><Check> expression </Check>

</Type></Type>

...

...

</Schema></Schema>

Тэги Check в вышеприведенном XML задают ограничения на типе Person. Может существовать более одного тэга проверки. Вышеописанное ограничение обычно проверяется в хранилище. Чтобы задать, что ограничение также может проверяться в явном виде приложением, вышеописанный XML изменяется следующим образом:Check tags in the above XML set restrictions on the Person type. More than one verification tag may exist. The above limitation is usually checked in the repository. To specify that the constraint can also be explicitly checked by the application, the above XML is modified as follows:

<Schema Name="Contacts" MajorVersion="1" MinorVersion="8”><Schema Name = "Contacts" MajorVersion = "1" MinorVersion = "8”>

<ReferencedSchema Name="Base" MajorVersion="1"/><ReferencedSchema Name = "Base" MajorVersion = "1" />

<Type Name="Person"...><Type Name = "Person" ...>

<Field Name="Birthdate" Type="the storage<Field Name = "Birthdate" Type = "the storage

platformTypes.datetime" Nullable="true"platformTypes.datetime "Nullable =" true "

MultiValued="false"/>MultiValued = "false" />

...

<Check InApplication="true">expression</Check><Check InApplication = "true"> expression </Check>

</Type></Type>

...

...

</Schema></Schema>

Обратите внимание на новый атрибут "InApplication" на элементе <Check>, который задан равным истине. Это заставляет API платформы хранения выявлять ограничение в API посредством частного метода на классе Person, именуемого Validated. Приложение может вызывать этот метод на объекте, чтобы гарантировать пригодность данных, предотвращая потенциально бесполезный возврат данных на сервер. Это возвращает логическое значение, указывающее результаты проверки. Заметим, что ограничения значения все же применяются на сервере независимо от того, вызывает ли клиент метод <объект>.Validate(). Приведем пример того, как можно использовать Validate:Notice the new “InApplication” attribute on the <Check> element, which is set to true. This forces the storage platform API to detect the constraint in the API through a private method on the Person class called Validated. An application can call this method on an object to ensure that the data is usable, preventing the potentially useless return of data to the server. This returns a boolean indicating the results of the check. Note that value restrictions still apply on the server, regardless of whether the client calls the <object> .Validate () method. Here is an example of how to use Validate:

ItemContext ctx = ItemContext.Open();ItemContext ctx = ItemContext.Open ();

// Создать контакт в папке My Contacts пользователя.// Create a contact in the My Contacts folder of the user.

Folder f = UserDataFolder.FindMyPersonalContactsFolder(ctx);Folder f = UserDataFolder.FindMyPersonalContactsFolder (ctx);

Person p = new Person(f);Person p = new Person (f);

// Задать дату рождения лица.// Set the date of birth of the person.

p.Birthdate = new DateTime(1959, 6, 9);p.Birthdate = new DateTime (1959, 6, 9);

// Добавить имя, категоризированное как персональное имя// Add a name categorized as a personal name

FullName name = new FullName(FullName.Category.PrimaryName);FullName name = new FullName (FullName.Category.PrimaryName);

name.GivenName = "Joe";name.GivenName = "Joe";

name.Surname = "Smith";name.Surname = "Smith";

p.PersonalNames.Add(name);p.PersonalNames.Add (name);

// проверить объект Person// check the Person object

if (p.Validate() == false)if (p.Validate () == false)

{{

// данные не представляют действительное лицо// data does not represent the actual person

}}

// сохранить изменения// save changes

p.Update();p.Update ();

ctx.Close();ctx.Close ();

Существует несколько путей доступа к хранилищу платформы хранения - API платформы хранения, ADO.NET, ODBC, OLEDB и ADO. Возникает вопрос официальной проверки ограничений, т.е. как мы можем гарантировать, что данные, записанные, скажем, из ODBC, проходят через те же ограничения целостности данных, как если бы данные были записаны из API платформы хранения. Поскольку все ограничения проверяются на хранилище, ограничения теперь являются официальными. Независимо от того, какой путь API используется для доступа к хранилищу, все записи в хранилище фильтруются посредством проверок ограничения на хранилище.There are several ways to access storage platform storage — storage platform APIs, ADO.NET, ODBC, OLEDB, and ADO. The question arises of the official verification of restrictions, i.e. how can we guarantee that data written, say, from ODBC goes through the same data integrity restrictions as if the data were written from the storage platform API. Since all restrictions are checked on the repository, the restrictions are now official. Regardless of which API path is used to access the repository, all records in the repository are filtered through checks on the restriction on the repository.

13. Совместное использование13. Sharing

Совместно используемый ресурс в платформе хранения имеет вид \\<имя DNS>\<услуга контекста>,The shared resource in the storage platform is \\ <DNS name> \ <context service>,

где <имя DNS> это имя DNS машины, и <услуга контекста> это папка включения, виртуальная папка или статья в томе на этой машине. Пусть, например, машина "Johns_Desktop" имеет том, именуемый Johns_Information, и в этом томе существует папка, именуемая Contacts_Categories; эта папка содержит папку, именуемую Work, в которой находятся рабочие контакты Джона:where <DNS name> is the name of the DNS machine, and <context service> is the inclusion folder, virtual folder, or article in the volume on that machine. Suppose, for example, the Johns_Desktop machine has a volume called Johns_Information, and in this volume there is a folder called Contacts_Categories; this folder contains a folder called Work, which contains John’s work contacts:

\\Johns_Desktop\Johns_Information$\Contacts_Categories\Work\\ Johns_Desktop \ Johns_Information $ \ Contacts_Categories \ Work

Это можно совместно использовать как "WorkContacts". Благодаря определению этого совместно используемого ресурса, \\Johns_Desktop\WorkContacts\JaneSmith является пригодным именем платформы хранения и идентифицирует статью Person под названием JaneSmith.This can be shared as "WorkContacts". By defining this shared resource, \\ Johns_Desktop \ WorkContacts \ JaneSmith is a valid storage platform name and identifies a Person article called JaneSmith.

а) Представление совместно используемого ресурсаa) Presentation of a shared resource

Тип статьи совместно используемого ресурса имеет следующие свойства: имя совместно используемого ресурса и цель совместно используемого ресурса (это может быть неподдерживающая связь). Например, имя вышеупомянутого совместно используемого ресурса - WorkContacts, и цель - Contacts_Categories\Work на томе Johns_Information. Ниже приведен фрагмент схемы для типа Share:The article type of the shared resource has the following properties: the name of the shared resource and the purpose of the shared resource (this may be an unsupported relationship). For example, the name of the aforementioned shared resource is WorkContacts, and the target is Contacts_Categories \ Work on the Johns_Information volume. The following is a snippet for the Share type:

<Schema<Schema

xmlns=http://schemas.microsoft.com/winfs/2002/11/18/schemaxmlns = http: //schemas.microsoft.com/winfs/2002/11/18/schema

Name="Share" MajorVersion="1" MinorVersion="0">Name = "Share" MajorVersion = "1" MinorVersion = "0">

<ReferencedSchema Name="Base" MajorVersion="1"/><ReferencedSchema Name = "Base" MajorVersion = "1" />

<ReferencedSchema Name="the storage platformTypes"<ReferencedSchema Name = "the storage platformTypes"

MajorVersion="1”/>MajorVersion = "1” />

<Type Name="Share" MajorVersion="1" MinorVersion="0"<Type Name = "Share" MajorVersion = "1" MinorVersion = "0"

ExtendsType="Base.Item" ExtendsVersion="1">ExtendsType = "Base.Item" ExtendsVersion = "1">

<Field Name="Name" Type="the storage<Field Name = "Name" Type = "the storage

platformTypes.nvarchar(512)"platformTypes.nvarchar (512) "

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

<Field Name="Target" Type="Base.RelationshipData"<Field Name = "Target" Type = "Base.RelationshipData"

TypeMajorVersion="1”/>TypeMajorVersion = "1” />

</Type></Type>

</Schema></Schema>

b) Управление совместно используемыми ресурсамиb) Shared Resource Management

Поскольку совместно используемый ресурс является статьей, совместно используемыми ресурсами можно управлять в точности, как другими статьями. Совместно используемый ресурс можно создавать, удалять или изменять. Совместно используемый ресурс также защищается таким же образом, как другие статьи платформы хранения.Because a shared resource is an article, shared resources can be managed exactly like other articles. A shared resource can be created, deleted, or modified. The shared resource is also protected in the same way as other storage platform articles.

с) Доступ к совместно используемым ресурсамc) Access to shared resources

Приложение осуществляет доступ к совместно используемому ресурсу удаленной платформы хранения, передавая имя совместно используемого ресурса (например, \\Johns_Desktop\WorkContacts) API платформы хранения при вызове метода ItemContext.Open(). ItemContext.Open возвращает экземпляр объекта ItemContext. Затем API платформы хранения разговаривает с услугой локальной платформы хранения (напомним, что доступ к совместно используемым ресурсам удаленной платформы хранения производится посредством локальной платформы хранения). В свою очередь, услуга локальной платформы хранения разговаривает с услугой удаленной платформы хранения (например, WorkContacts). Затем услуга удаленной платформы хранения транслирует WorkContacts в Contacts_Categories\Work и открывают ее. После этого запрос и другие операции осуществляются наподобие других областей действия.The application accesses the shared resource of the remote storage platform by passing the name of the shared resource (for example, \\ Johns_Desktop \ WorkContacts) to the storage platform API when calling the ItemContext.Open () method. ItemContext.Open returns an instance of the ItemContext. Then the storage platform API talks to the local storage platform service (recall that access to the shared resources of the remote storage platform is through the local storage platform). In turn, the local storage platform service talks to the remote storage platform service (for example, WorkContacts). Then, the remote storage platform service translates WorkContacts into Contacts_Categories \ Work and opens it. After that, the request and other operations are carried out like other areas of action.

d) Обнаружимостьd) Detectability

Согласно одному варианту осуществления прикладная программа может обнаружить совместно используемые ресурсы, доступные под данным <именем DNS> следующими способами. Согласно первому способу API платформы хранения принимает имя DNS (например, Johns_Desktop) как параметр области применения в методе ItemContext.Open(). Затем API платформы хранения связывается с хранилищем платформы хранения с этим именем DNS как части строки соединения. Благодаря этому соединению, единственно, что может сделать приложение, это вызвать ItemContext.FindAll(typeof(Share)). Затем услуга платформы хранения объединяет все совместно используемые ресурсы на всех присоединенных томах и возвращает коллекцию совместно используемых ресурсов. Согласно второму способу, на локальной машине, администратор может легко обнаружить совместно используемые ресурсы на конкретном томе посредством FindAll(typeof(Share)), или конкретной папке посредством FindAll(typeof(Share), "Target(ShareDestination).Id = folderId").According to one embodiment, an application can detect shared resources available under a given <DNS name> in the following ways. According to the first method, the storage platform API accepts the DNS name (for example, Johns_Desktop) as the scope parameter in the ItemContext.Open () method. The storage platform API then contacts the storage platform storage with this DNS name as part of the connection string. Thanks to this connection, the only thing the application can do is call ItemContext.FindAll (typeof (Share)). The storage platform service then combines all the shared resources on all the attached volumes and returns a collection of shared resources. According to the second method, on the local machine, the administrator can easily find shared resources on a specific volume using FindAll (typeof (Share)), or a specific folder using FindAll (typeof (Share), "Target (ShareDestination) .Id = folderId").

14. Семантика Find14. Semantics of Find

Методы Find* (независимо от того, вызваны ли они на объекте ItemContext или на отдельной статье), в общем случае, применяются к статьям (включая внедренные статьи) в данном контексте. Вложенные элементы не имеют Find - в них нельзя производить поиск независимо от содержащих их статей. Это согласуется с семантикой, нужной модели данных платформы хранения, где вложенные элементы выводят свою «идентификацию» из содержащей статьи. Чтобы прояснить эту идею, приведем примеры пригодных и непригодных операций нахождения:Find * methods (regardless of whether they are called on an ItemContext or on a separate article) generally apply to articles (including embedded articles) in this context. Nested elements do not have Find - you cannot search in them regardless of the articles that contain them. This is consistent with the semantics of the desired data model of the storage platform, where the nested elements derive their “identification” from the containing article. To clarify this idea, we give examples of suitable and unsuitable finding operations:

а) Показать мне все телефонные номера в системе, имеющие региональный код 206.a) Show me all the phone numbers in the system that have the area code 206.

Непригоден, поскольку нахождение осуществляется на телефонных номерах - элементе - без ссылки на статью.Unsuitable, since the location is carried out on telephone numbers - an element - without a link to the article.

b) Показать мне все телефонные номера во всех статьях Person, имеющие региональный код 206.b) Show me all phone numbers in all Person articles with area code 206.

Непригоден, несмотря на ссылку на Person (=статья), такой критерий не задействует эту статью.Unsuitable, despite the link to Person (= article), this criterion does not apply this article.

с) Показать мне все телефонные номера Murali (=одно единственное лицо), имеющие региональный код 206.c) Show me all Murali phone numbers (= one single person) with area code 206.

Пригоден, поскольку существует критерий поиска на статье (лицо по имени "Murali").Suitable because there is a search term on an article (a person named "Murali").

Исключениями для этого правила являются типы вложенного элемента, прямо или косвенно выведенные из типа Base.Relationship. Эти типы можно запрашивать по отдельности через классы отношений. Такие запросы могут поддерживаться, поскольку реализация платформы хранения использует «главную таблицу связей» для сохранения элементов отношения вместо внедрения их в UDT статей.Exceptions to this rule are nested element types derived directly or indirectly from the Base.Relationship type. These types can be requested individually through relationship classes. Such queries can be supported because the storage platform implementation uses a “master link table” to store relationship elements instead of embedding them in UDT articles.

15. API Contacts платформы хранения15. Storage platform Contacts API

В этом разделе приведен обзор API Contacts платформы хранения. Схема, лежащая в основе API Contacts, показана на фиг.21A и 21B.This section provides an overview of the Storage platform API Contacts. The diagram underlying the API Contacts is shown in FIGS. 21A and 21B.

а) Обзор System.Storage.Contacta) System.Storage.Contact Overview

API платформы хранения включает в себя пространство имен для того, чтобы иметь дело со статьями и элементами в Схеме контактов. Это пространство имен называется System.Storage.Contact. Эта схема имеет, например, следующие классы:The storage platform API includes a namespace for dealing with articles and items in the Contact Scheme. This namespace is called System.Storage.Contact. This scheme has, for example, the following classes:

- Статьи: UserDataFolder, User, Person, ADService, Service, Group, Organization, Principal, Location- Articles: UserDataFolder, User, Person, ADService, Service, Group, Organization, Principal, Location

- Элементы: Profile, PostalAddress, EmailAddress, TelephoneNumber, RealTimeAddress, EAddress, FullName, BasicPresence, GroupMembership, RoleOccupancy- Elements: Profile, PostalAddress, EmailAddress, TelephoneNumber, RealTimeAddress, EAddress, FullName, BasicPresence, GroupMembership, RoleOccupancy

b) Поведения доменаb) Domain Behavior

Ниже приведен список поведений домена для Схемы контактов. Рассматривая поведения домена с достаточно высокого уровня, их можно разделить на интуитивно понятные категории:The following is a list of domain behaviors for Contact Schema. Considering the behavior of a domain from a sufficiently high level, they can be divided into intuitive categories:

- статические помощники, например, Person.CreatePersonalContact() для создания нового личного контакта;- static assistants, for example, Person.CreatePersonalContact () to create a new personal contact;

- помощники экземпляра, например user.AutoLoginToAllProfiles(), который осуществляет вход пользователя (экземпляр класса User) во все профили, помеченные как предназначенные для автоматического входа;- instance helpers, for example user.AutoLoginToAllProfiles (), which logs the user (an instance of the User class) into all profiles that are marked as intended for automatic login;

- CategoryGUID, например, Category.Home, Category.Work и т.д.;- CategoryGUID, for example, Category.Home, Category.Work, etc .;

- производные свойства, например, emailAddress.Address() - возвращает строку, которая объединяет поля имени пользователя и домена данного emailAddress (= экземпляр класса EmailAddress); и- derived properties, for example, emailAddress.Address () - returns a string that combines the user name and domain fields of the given emailAddress (= instance of the EmailAddress class); and

- производные коллекции, например, person.PersonalEmailAddresses - для данного экземпляра класса Person, получают его личный адрес электронной почты.- Derived collections, for example, person.PersonalEmailAddresses - for this instance of the Person class, get his personal email address.

В нижеследующей таблице приведены, для каждого класса в Контактах, который имеет поведения домена, список этих методов и категория, которой они принадлежат.The following table shows, for each class in Contacts that has domain behaviors, a list of these methods and the category to which they belong.

BasicPresenceBasicpresence URI категорийCategory URI UnknownCategoryURI, OfflineCategoryURI, BusyCategoryURI, AwayCategoryURI, OnlineCategoryURIUnknownCategoryURI, OfflineCategoryURI, BusyCategoryURI, AwayCategoryURI, OnlineCategoryURI Статические помощникиStatic Helpers ConvertPresenceStateToString - состояние наличия формата локализованной строки (фактически локализация должна быть добавлена; просто делает дружественную строку на английском).ConvertPresenceStateToString - state of the presence of the localized string format (in fact, localization should be added; it just makes the string friendly in English). CategoryCategory GUID категорийCategory GUID Home, Work, Primary, Secondary, Cell, Fax, PagerHome, Work, Primary, Secondary, Cell, Fax, Pager EmailAddressEmailAddress Производные свойстваDerived Properties Адрес - объединяет имя пользователя и доменAddress - combines the username and domain Статические помощникиStatic Helpers IsValidEmailAddressIsValidEmailAddress FolderFolder Производные свойстваDerived Properties GetChildItemCollection - создает коллекцию статей на основе целей FolderMembership.GetChildItemCollection - Creates a collection of articles based on the goals of the FolderMembership. Статические помощникиStatic Helpers GetKnownFolder - специальные запросы для получения общеизвестных папокGetKnownFolder - special requests for getting well-known folders AddToPersonalContacts - добавляет статью в общеизвестную папку личных контактовAddToPersonalContacts - adds an article to the well-known personal contacts folder ItemsItems Статические помощникиStatic Helpers GetItemFromID - делает запрос на основе ИДGetItemFromID - Makes a request based on ID RelationshipRelationship Помощники экземпляраInstance Helpers BindToTarget - возвращает статью для целиBindToTarget - returns an article for the purpose PersonPerson Производные коллекцииDerived Collections PersonalRealtimeAddresses, PersonalEmailAddresses, PersonalTelephoneNumbersPersonalRealtimeAddresses, PersonalEmailAddresses, PersonalTelephoneNumbers Производные свойстваDerived Properties OnlineStatus, OnlineStatusIconSource, PrimaryEmailAddress, PrimarySecurityIDOnlineStatus, OnlineStatusIconSource, PrimaryEmailAddress, PrimarySecurityID Статические помощникиStatic Helpers CreatePersonalContact, CreateTemporaryContact - создает новое лицо в общеизвестной папкеCreatePersonalContact, CreateTemporaryContact - creates a new face in a well-known folder GetCurrentUser - получает личность пользователя текущего сеансаGetCurrentUser - Gets the user identity of the current session SecurityIDSecurityid Производные свойстваDerived Properties UserName, DomainName, DomainUserNameUserName, DomainName, DomainUserName TelephoneNumberTelephoneNumber Помощники экземпляраInstance Helpers SetFromUserInputString - разлагает строку телефонного номера на частиSetFromUserInputString - decomposes a phone number string into parts Статические помощникиStatic Helpers ParseNumber - разлагает строку телефонного номера на частиParseNumber - decomposes a phone number string into parts UserUser Помощники экземпляраInstance Helpers AutoLoginToAllProfiles - входит во все профили, которые помечены как предназначенные для автоматического входаAutoLoginToAllProfiles - included in all profiles that are marked as intended for automatic login

16. API File платформы хранения16. Storage Platform API File

В этом разделе приведен обзор API File платформы хранения согласно одному варианту осуществления настоящего изобретения.This section provides an overview of the Storage Platform API File according to one embodiment of the present invention.

а) Введениеa) Introduction

(1) Отражение тома NTFS в платформе хранения(1) Reflection of an NTFS volume on a storage platform

Платформа хранения обеспечивает способ индексации по контексту в существующих томах NTFS. Для этого извлекаются («продвигающие») свойства из каждого потока файла или директории в NTFS и эти свойства сохраняются как статьи в платформе хранения.The storage platform provides a way to index by context on existing NTFS volumes. To do this, (“promoting”) properties are extracted from each file stream or directory in NTFS and these properties are saved as articles in the storage platform.

Схема файлов платформы хранения задает два типа статьи - File и Directory - для сохранения продвинутых сущностей файловой системы. Тип Directory - это подтип типа Folder; это папка включения, которая содержит другие статьи Directory или статьи File.The storage platform file schema defines two types of articles - File and Directory - for storing advanced file system entities. The Directory type is a subtype of the Folder type; this is the inclusion folder that contains other Directory articles or File articles.

Статья Directory может содержать статьи Directory и File; она не может содержать статьи никакого другого типа. Что касается платформы хранения, статьи Directory и File предназначены только для чтения из любых API доступа к данным. Услуга менеджера продвижения файловой системы (FSPM) асинхронно продвигает измененные свойства в платформу хранения. Свойства статей File и Directory могут изменяться посредством API Win32. API платформы хранения можно использовать для чтения любых свойств этих статей, включая поток, связанный со статьей File.A Directory entry may contain Directory and File entries; it cannot contain any other type of article. As for the storage platform, Directory and File articles are read-only from any data access API. The file system promotion manager (FSPM) service asynchronously promotes changed properties to the storage platform. The properties of the File and Directory articles can be changed through the Win32 API. The storage platform API can be used to read any properties of these articles, including the stream associated with the File article.

(2) Создание файлов и директорий в пространстве имен платформы хранения(2) Creating files and directories in the storage platform namespace

После продвижения тома NTFS в том платформы хранения все файлы и директории в нем находятся в особой части этого тома. Эта область предназначена только для чтения с точки зрения платформы хранения; FSPM может создавать новые директории и файлы и/или изменять свойства существующих статей.After the NTFS volume is promoted to the storage platform volume, all the files and directories in it are located in a special part of this volume. This area is read-only in terms of storage platform; FSPM can create new directories and files and / or modify the properties of existing articles.

Остаток пространства имен этого тома может содержать обычный диапазон типов статей платформы хранения - Principal, Organization, Document, Folder и т.д. Платформа хранения также позволяет создавать файлы и директории в любой части пространства имен платформы хранения. Эти «родные» файлы и директории не имеют эквивалентов в файловой системе NTFS; они целиком хранятся в платформе хранения. Кроме того, изменения свойств видны немедленно.The rest of the namespace of this volume may contain the usual range of types of storage platform entries - Principal, Organization, Document, Folder, etc. The storage platform also allows you to create files and directories in any part of the storage platform namespace. These "native" files and directories have no equivalents in the NTFS file system; they are entirely stored in the storage platform. In addition, property changes are visible immediately.

Однако модель программирования остается такой же: они по прежнему предназначены только для чтения в отношении API доступ к данным платформы хранения. «Родные» файлы и директории должны обновляться с использованием API Win32. Это упрощает ментальную модель разработчика, которая представляет собой:However, the programming model remains the same: they are still read-only in terms of API access to storage platform data. Native files and directories must be updated using the Win32 API. This simplifies the developer’s mental model, which is:

1. Любой тип статьи платформы хранения можно создать где угодно в пространстве имен (если, конечно, этому не препятствуют права).1. Any type of storage platform article can be created anywhere in the namespace (unless, of course, rights prevent this).

2. Любой тип статьи платформы хранения можно читать с использованием API платформы хранения.2. Any type of storage platform article can be read using the storage platform API.

3. Все типы статьи платформы хранения записываются с использованием API платформы хранения за исключением File и Directory.3. All types of storage platform entries are written using the storage platform APIs, with the exception of File and Directory.

4. Для записи статей File и Directory независимо от того, где они находятся в пространстве имен, используется API Win32.4. The Win32 API is used to record File and Directory articles regardless of where they are in the namespace.

5. Изменения статей File/Directory в «продвинутом» пространстве имен могут немедленно проявляться в платформе хранения; в «непродвинутом» пространстве имен, изменения немедленно отражаются в платформе хранения.5. Changes to File / Directory entries in the “advanced” namespace can immediately appear on the storage platform; in the "non-advanced" namespace, changes are immediately reflected in the storage platform.

b) Схема файловb) File schema

На фиг.25 показана схема, на которой основан API File.25 shows a diagram on which the File API is based.

с) Обзор System.Storage.Filesc) System.Storage.Files Overview

API платформы хранения включает в себя пространство имен для работы с объектами файлов. Это пространство имен называется System.Storage.Files. Информационные элементы классов в System.Storage.Files непосредственно отражают информацию, хранящуюся в хранилище платформы хранения; эта информация «продвигается» из объектов файловой системы или может быть создана внутренне с использованием API Win32. Пространство имен System.Storage.Files имеет два класса: FileItem и DirectoryItem. Элементы этих классов и их методы легко предсказать, посмотрев на диаграмму схемы на фиг.25. FileItem и DirectoryItem предназначены только для чтения из API платформы хранения. Для их изменения нужно использовать API Win32 или классы в System.IO.The storage platform API includes a namespace for working with file objects. This namespace is called System.Storage.Files. The class information elements in System.Storage.Files directly reflect the information stored in the storage of the storage platform; this information is “pushed” from file system objects or can be created internally using the Win32 API. The System.Storage.Files namespace has two classes: FileItem and DirectoryItem. The elements of these classes and their methods are easy to predict by looking at the diagram diagram in FIG. FileItem and DirectoryItem are read-only from the storage platform API. To change them, you need to use the Win32 API or classes in System.IO.

d) Примеры кодаd) Code examples

В этом разделе приведены три примера кода, иллюстрирующие использование классов System.Storage.Files.This section provides three code examples that illustrate the use of the System.Storage.Files classes.

(1) Открытие файла и запись в него(1) Opening a file and writing to it

Этот пример показывает, как производить «традиционные» манипуляции с файлом.This example shows how to perform “traditional” file manipulations.

ItemContext ctx = ItemContext.Open();ItemContext ctx = ItemContext.Open ();

FileItem f = FileItem.FindByPath(ctx,FileItem f = FileItem.FindByPath (ctx,

@”\My Documents\billg.ppt");@ ”\ My Documents \ billg.ppt");

// пример обработки свойств файла - гарантировать, что// example of processing file properties is to ensure that

// файл не предназначен только для чтения// the file is not read-only

if (!f.IsReadOnly)if (! f.IsReadOnly)

{{

FileStream fs = f.OpenWrite();FileStream fs = f.OpenWrite ();

// Чтение, запись, закрытие потока файла fs// Read, write, close the fs file stream

}}

ctx.Close();ctx.Close ();

В строке 3 используется метод FindByPath для открытия файла. В строке 7 показано использование продвинутого свойства, IsReadOnly, для проверки, является ли файл записываемым. Если да, то в строке 9 мы используем метод OpenWrite() на объекте FileItem для получения потока файла.Line 3 uses the FindByPath method to open the file. Line 7 shows the use of the advanced property, IsReadOnly, to check if the file is writable. If yes, then in line 9 we use the OpenWrite () method on the FileItem object to get the file stream.

(2) Использование запросов(2) Using queries

Поскольку хранилище платформы хранения поддерживает свойства, продвинутые из файловой системы, на файлах можно легко делать богатые запросы. В этом примере перечислены все файлы, измененные за последние три дня:Because storage platform storage supports advanced features from the file system, rich queries can easily be made on files. This example lists all the files changed in the last three days:

// Перечислить все файлы, измененные за последние 3 дня// List all files modified in the last 3 days

FindResult result = FileItem. FindAll(FindResult result = FileItem. FindAll (

ctxctx

"Modified >= '{0}'","Modified> = '{0}'",

DateTime.Now.AddDays(-3));DateTime.Now.AddDays (-3));

foreach(FileItem file in result)foreach (FileItem file in result)

{{

...

}}

Вот другой пример использования запросов - отыскание всех записываемых файлов определенного типа (=расширение):Here is another example of using queries - finding all the recorded files of a certain type (= extension):

// Найти все записываемые файлы.cs// Find all writable files .cs

// в конкретной директории.// in a specific directory.

// Эквивалентно: dir c:\win\src\api\*.cs /a-r-d// Equivalent: dir c: \ win \ src \ api \ *. Cs / a-r-d

DirectoryItem dir =DirectoryItem dir =

DirectoryItem.FindByPath(ctx, @"c:\win\src\api");DirectoryItem.FindByPath (ctx, @ "c: \ win \ src \ api");

FindResult result = dir.GetFiles(FindResult result = dir.GetFiles (

"Extension='cs' and IsReadOnly=false");"Extension = 'cs' and IsReadOnly = false");

foreach(File file in result)foreach (File file in result)

{{

...

}}

e) Поведения доменаe) Domain Behaviors

Согласно одному варианту осуществления, помимо стандартных свойств и методов, класс файлов также имеет поведения домена (прописанные вручную свойства и методы). Эти поведения, в общем случае, базируются на методах в соответствующих классах System.IO.According to one embodiment, in addition to standard properties and methods, the file class also has domain behaviors (manually prescribed properties and methods). These behaviors are generally based on methods in the corresponding System.IO classes.

J. ЗаключениеJ. Conclusion

Согласно проиллюстрированному выше настоящее изобретение относится к платформе хранения для организации, поиска и совместного использования данных. Платформа хранения настоящего изобретения расширяет понятие хранения данных за пределы существующих файловых систем и систем базы данных и предназначена быть хранилищем для всех типов данных, включая структурированные, неструктурированные или частично структурированные данные, например реляционные (табличные) данные, XML и новую форму данных, так называемые Статьи. Благодаря своей общей основе хранения и схематизированным данным платформа хранения согласно настоящему изобретению позволяет более эффективно разрабатывать приложение для потребителей, специалистов в области информационных технологий и предприятий. Она обеспечивает богатый и расширяемый программный интерфейс приложения, который не только делает доступными возможности, свойственные этой модели данных, но также охватывает и расширяет существующие файловую систему и методы доступа к базе данных. Понятно, что изменения можно производить согласно вышеописанным вариантам осуществления, не выходя за рамки сущности изобретения. Соответственно, настоящее изобретение не ограничивается конкретными раскрытыми вариантами осуществления, но призвано охватывать все модификации, отвечающие сущности и объему изобретения, заданным в прилагаемой формуле изобретения.According to the foregoing, the present invention relates to a storage platform for organizing, searching and sharing data. The storage platform of the present invention extends the concept of data storage beyond existing file systems and database systems and is intended to be a repository for all types of data, including structured, unstructured or partially structured data, such as relational (tabular) data, XML and a new data form, the so-called Articles. Due to its common storage foundation and schematized data, the storage platform according to the present invention allows more efficiently developing an application for consumers, IT professionals and enterprises. It provides a rich and extensible application programming interface that not only makes available the features inherent in this data model, but also extends and extends the existing file system and database access methods. It is understood that changes can be made according to the above described embodiments without going beyond the scope of the invention. Accordingly, the present invention is not limited to the specific disclosed embodiments, but is intended to cover all modifications that meet the essence and scope of the invention defined in the attached claims.

Из вышеизложенного следует, что различные системы, способы и аспекты настоящего изобретения могут быть, полностью или частично, реализованы в виде программного кода (например, команд). Этот программный код может храниться на компьютерно-считываемом носителе, например, магнитном, электрическом или оптическом носителе данных, в том числе, без ограничения, флоппи-диске, CD-ROM, CD-RW, DVD-ROM, DVD-RAM, магнитной ленте, флэш-памяти, жестком диске или любом другом машинно-считываемом носителе информации, причем, когда программный код загружается в машину, например, компьютер или сервер, и выполняется на ней, машина становится устройством для практического применения изобретения. Настоящее изобретение также может быть реализовано в виде программного кода, который передается по некоторой среде передачи, например по электрическим проводам или кабелям, по оптическим волокнам, по сети, включая Интернет или интрасеть или посредством любого другого вида передачи, причем, когда программный код поступает и загружается в машину, например компьютер или сервер, и выполняется на ней, машина становится устройством для практического применения изобретения. При реализации на процессоре общего назначения программный код объединяется с процессором для обеспечения уникального устройства, которое действует аналогично специальным логическим схемам.From the foregoing, it follows that various systems, methods and aspects of the present invention can be, in whole or in part, implemented in the form of program code (for example, instructions). This program code may be stored on a computer-readable medium, for example, magnetic, electrical or optical storage medium, including, without limitation, a floppy disk, CD-ROM, CD-RW, DVD-ROM, DVD-RAM, magnetic tape , flash memory, hard disk, or any other computer-readable storage medium, and when the program code is loaded into a machine, such as a computer or server, and executed on it, the machine becomes a device for the practical application of the invention. The present invention can also be implemented in the form of program code that is transmitted over a certain transmission medium, for example, via electric wires or cables, through optical fibers, through a network, including the Internet or an intranet, or through any other type of transmission, moreover, when the program code arrives and loaded into a machine, such as a computer or server, and executed on it, the machine becomes a device for the practical application of the invention. When implemented on a general-purpose processor, the program code is combined with the processor to provide a unique device that acts similarly to special logic circuits.

Приложение АAppendix A

namespace System.Storagenamespace System.Storage

{{

abstract class ItemContext: IDisposable, IServiceProviderabstract class ItemContext: IDisposable, IServiceProvider

{{

Создание ItemContext и управление элементамиCreate ItemContext and manage items

// Приложения не могут напрямую создавать объекты// Applications cannot directly create objects

// ItemContext и выводить классы из ItemContext// ItemContext and derive classes from ItemContext

interal ItemContext();interal ItemContext ();

// Создать ItemContext, который можно использовать// Create An ItemContext That Can Be Used

// для поиска по указанным путям или, если ни один// to search the specified paths or, if none

// путь не указан, в хранилище по умолчанию// path not specified, in the default storage

// на локальном компьютере// on the local computer

public static ItemContext Open();public static ItemContext Open ();

public static ItemContext Open(string path);public static ItemContext Open (string path);

public static ItemContext Open(params string[] paths);public static ItemContext Open (params string [] paths);

// Возвратить указанные пути, когда ItemContext создан// Return the specified paths when the ItemContext is created

public string[] GetOpenPaths();public string [] GetOpenPaths ();

// Создать копию этого ItemContext. Копия будет// Create a copy of this ItemContext. Copy will be

// иметь независимую транзакцию, кэширование// have an independent transaction, caching

// и состояние обновления. Кэш первоначально// and update status. Cache initially

// будет пустым. Ожидается, что использование// will be empty. Usage expected

// клонированного ItemContext будет более// cloned ItemContext will be more

// эффективно, чем открытие нового ItemContext// effective than opening a new ItemContext

// с использованием тех же доменов статей.// using the same article domains.

public ItemContext Clone();public ItemContext Clone ();

// Закрыть ItemContext. Любая попытка использовать// Close ItemContext. Any attempt to use

// ItemContext после закрытия приведет// ItemContext after closing will result

// к ObjectDisposedException.// to ObjectDisposedException.

public void Close();public void Close ();

void IDisposable.Dispose();void IDisposable.Dispose ();

// Истина, если любой домен, указанный, когда// True if any domain specified when

// ItemContext был открыт, разрешался на удаленном// ItemContext was open, resolved on the remote

// компьютере.// computer.

public bool IsRemote { get; }public bool IsRemote {get; }

// Возвращает объект, который может обеспечивать// Returns an object that can provide

// запрашиваемый тип услуги. Возвращает null,// requested type of service. Returns null

// если запрашиваемая услуга не может быть// if the requested service cannot be

// предоставлена. Использование шаблона// provided. Using a template

// IServiceProvider позволяет выделить API, который// IServiceProvider allows you to allocate an API that

// обычно не используется и может смутить// usually not used and may confuse

// разработчиков, из класса ItemContext. ItemContext// developers, from the ItemContext class. ItemContext

// может обеспечивать следующие виды услуг:// can provide the following services:

// IItemSerialization, IStoreObjectCache// IItemSerialization, IStoreObjectCache

public object GetService(Type serviceType);public object GetService (Type serviceType);

Обновление связанных элементовUpdate related items

// Сохраняет изменение, представленные измененными// Saves the change represented by the changed

// объектами и все объекты, переданные MarkForCreate// objects and all objects passed to MarkForCreate

// или MarkForDelete. Может выбрасывать// or MarkForDelete. Can throw away

// UpdateCollisionException при обнаружении конфликта// UpdateCollisionException when a conflict is detected

// обновлений.// updates.

public void Update();public void Update ();

// Сохраняет изменения, представленные указанными// Saves the changes represented by the specified

// объектами. Объекты должны либо изменяться, либо// objects. Objects must either change or

// передаваться MarkForCreate или MarkForDelete, иначе// passed MarkForCreate or MarkForDelete, otherwise

// выбрасывается ArgumentException. Может выбрасывать// throw an ArgumentException. Can throw away

// UpdateCollisionException при обнаружении конфликта// UpdateCollisionException when a conflict is detected

// обновлений.// updates.

public void Update(object objectToUpdate);public void Update (object objectToUpdate);

public void Update(IEnumerable objectsToUpdate);public void Update (IEnumerable objectsToUpdate);

// Обновляет контент указанных объектов из хранилища.// Updates the content of the specified objects from the repository.

// Если объект изменен, изменения переписываются, и// If the object is modified, the changes are overwritten, and

// объект больше не считается измененным. Выбрасывает// the object is no longer considered modified. Throws away

// ArgumentException, если задано что-либо другое, чем// ArgumentException if anything other than

// объект статьи, расширении статьи или отношения.// object of the article, the extension of the article or relationship.

public void Refresh(object objectToRefresh);public void Refresh (object objectToRefresh);

public void Refresh(IEnumerable objectsToRefresh);public void Refresh (IEnumerable objectsToRefresh);

// Возбуждается, если обновление обнаруживает, что// Excited if the update detects that

// данные изменились в хранилище между моментами// data has changed in storage between moments

// извлечения измененного объекта и попытки сохранить// retrieve the modified object and try to save

// его. Если ни один описатель события не// him. If no event descriptor

// зарегистрирован, обновление выбрасывает исключение.// registered, the update throws an exception.

// Если описатель события зарегистрирован, он может// If an event descriptor is registered, it can

// выбросить исключение, чтобы прервать обновление,// throw an exception to abort the update,

// заставить измененный объект переписать данные в// force the changed object to overwrite the data in

// хранилище или соединить изменения, сделанные в// store or merge changes made to

// хранилище и в объекте.// storage and in the object.

public event ChangeCollisionEventHandlerpublic event ChangeCollisionEventHandler

UpdateCollision;UpdateCollision;

// Возбуждается в различные моменты в ходе обработки// Excited at various times during processing

// обновлений для обеспечения информации о ходе// updates to provide progress information

// обновления// updates

public event UpdateProgressEventhandler UpdateProgress;public event UpdateProgressEventhandler UpdateProgress;

// Асинхронные версии Update// Asynchronous versions of Update

public IAsyncResult BeginUpdate(IAsyncCallbackpublic IAsyncResult BeginUpdate (IAsyncCallback

callback, object state);callback, object state);

public IAsyncResult BeginUpdate(object objectToUpdate,public IAsyncResult BeginUpdate (object objectToUpdate,

IAsyncCallback callback, object state);IAsyncCallback callback, object state);

public IAsyncResult BeginUpdate(IEnumerablepublic IAsyncResult BeginUpdate (IEnumerable

objectsToUpdate, IAsyncCallback callback,objectsToUpdate, IAsyncCallback callback,

object state);object state);

public void EndUpdate(IAsyncResult result);public void EndUpdate (IAsyncResult result);

// Асинхронные версии Refresh// Asynchronous versions of Refresh

public IAsyncResult BeginRefresh(objectpublic IAsyncResult BeginRefresh (object

objectToRefresh, IAsyncCallback callback,objectToRefresh, IAsyncCallback callback,

object state);object state);

public IAsyncResult BeginRefresh(IEnumerablepublic IAsyncResult BeginRefresh (IEnumerable

objectsToRefresh, IAsyncCallback callback,objectsToRefresh, IAsyncCallback callback,

object state);object state);

public void EndRefresh(IAsyncResult result);public void EndRefresh (IAsyncResult result);

Элементы, связанные с транзакциейTransaction Related Items

// Начинает транзакцию с указанного уровня изоляции.// Starts the transaction from the specified isolation level.

// Уровень изоляции по умолчанию это ReadCommited. Во// The default isolation level is ReadCommited. In

// всех случаях, начинается распределенная транзакция,// in all cases, a distributed transaction begins,

// поскольку ей может понадобиться охватить свойства// since she might need to cover properties

// статьи потокового типа.// stream type articles.

public Transaction BeginTransaction();public Transaction BeginTransaction ();

public Transaction BeginTransaction(public Transaction BeginTransaction (

System.Data.IsolationLevel isolationLevel);System.Data.IsolationLevel isolationLevel);

Элементы, связанные с поискомSearch related items

// Создать ItemSearcher, который будет осуществлять// Create An ItemSearcher That Will Implement

// поиск в этом контексте статьи объектов указанного// search in this context articles of objects of the specified

//типа. Выбрасывает ArgumentException, если указан тип,// type. Throws an ArgumentException if a type is specified,

// отличный от статьи, отношения или расширения статьи.// different from the article, relationship or extension of the article.

public ItemSearcher GetSearcher(Type type);public ItemSearcher GetSearcher (Type type);

// Найти статью по ее ИД.// Find the article by its ID.

public Item FindItemById(ItemId itemId);public Item FindItemById (ItemId itemId);

// Найти статью по данному пути к ней. Путь может быть// Find the article on this path to it. Path may be

// абсолютным или относительным. Если он относительный,// absolute or relative. If it is relative,

// будет выброшено NotSupportedException, если, когда// NotSupportedException will be thrown if, when

// ItemContext был открыт, были заданы множественные// ItemContext was open, multiple were specified

// домены статьи. Возвратит null, если такой статьи не// article domains. Returns null if no such article

// существует. Создает соединение с частью// exist. Creates a connection to a part

// \\machine\share домена для извлечения статьи. Статья// \\ machine \ share domain to retrieve the article. Article

// будет связана с этим доменом.// will be associated with this domain.

public Item FindItemByPath( string path );public Item FindItemByPath (string path);

// Найти статью по данному пути к ней. Путь относится к// Find the article on this path to it. Path refers to

// указанному домену статьи. Создает соединение с// the specified domain of the article. Creates a connection to

//указанным доменом для извлечения статьи. Статья будет// the specified domain to retrieve the article. Article will be

// связана с этим доменом. Возвратит null, если такой// linked to this domain. Will return null if such

// статьи не существует.// article does not exist.

public Item FindItemByPath(string domain, string path);public Item FindItemByPath (string domain, string path);

// Найти отношение по ее ИД// Find the relationship by its ID

public Relatioinship FindRelationshipById(ItemIdpublic Relatioinship FindRelationshipById (ItemId

itemID, RelationshipId relationshipId);itemID, RelationshipId relationshipId);

// Найти расширение статьи по ее ИД// Find the extension of the article by its ID

public ItemExtension FindItemExtensionById(ItemIdpublic ItemExtension FindItemExtensionById (ItemId

itemId, ItemExtensionId itemExtensionId);itemId, ItemExtensionId itemExtensionId);

// Найти все статьи, отношения или расширения статьи// Find all articles, relationships or article extensions

// указанного типа, в необязательном порядке// of the specified type, optional

// удовлетворяющие данному фильтру. Выбрасывает// matching this filter. Throws away

//ArgumentException, если указан тип, отличный от этих.// ArgumentException if a type other than these is specified.

public FindResult FindAll( Type type );public FindResult FindAll (Type type);

public FindResult FindAll( Type type, string filter);public FindResult FindAll (Type type, string filter);

// Найти любую статью, отношения или расширения статьи// Find any article, relationship or article extension

// указанного типа, которая удовлетворяет данному// the specified type that satisfies the given

// фильтру. Выбрасывает ArgumentException, если указан// filter. Throws an ArgumentException if specified

// тип, отличный от этих. Возвращает null, если такой// type different from these. Returns null if such

// объект не найден.// object not found.

public object FindOne(Type type, string filter);public object FindOne (Type type, string filter);

// Найти статью, отношение или расширения статьи// Find an article, relationship or article extension

// указанного типа, которая удовлетворяет данному// the specified type that satisfies the given

// фильтру. Выбрасывает ArgumentException, если указан// filter. Throws an ArgumentException if specified

// тип, отличный от одного из них. Выбрасывает// type different from one of them. Throws away

// MultipleObjectsFoundException, если найдено более// MultipleObjectsFoundException if more than

// одного объекта.// single object.

public object FindOnly(Type type, string filter);public object FindOnly (Type type, string filter);

// Возвращает истину, если статья, отношение или// Returns true if the article, relationship, or

// расширения статьи указанного типа, которая// extensions of the article of the specified type, which

// удовлетворяет данному фильтру, существует.// satisfies the given filter, exists.

// Выбрасывает ArgumentException, если указан тип,// Throws an ArgumentException if a type is specified,

// отличный от одного из них.// different from one of them.

public bool Exists( Type type, string filter );public bool Exists (Type type, string filter);

// Указывает, как объекты, возвращенные в результате// Indicates how objects returned as a result

// поиска, относятся к отображению идентификации// search, refer to identity mapping

// объекта, поддерживаемому ItemContext.// object supported by ItemContext.

public SearchColllisionMode SearchCollisionMode {public SearchColllisionMode SearchCollisionMode {

get; set;}get; set;}

// Возбуждается, когда PreserveModifiedObjects задан// Excited when PreserveModifiedObjects is set

// для ResultMapping. Это событие позволяет приложению// for ResultMapping. This event allows the application

// избирательно обновлять модифицированный объект// selectively update the modified object

// данными, извлеченными посредством поиска.// data retrieved through the search.

public event ChangeCollisionEventHandlerpublic event ChangeCollisionEventHandler

SearchCollision;SearchCollision;

// Включает объект из другого ItemContext в этот// Includes an object from another ItemContext in this

// контекст статьи. Если объект, представляющий ту же// context of the article. If an object representing the same

//самую статью, отношение или расширение статьи, уже не// the article itself, the relationship or extension of the article, is no longer

// существует, это отображение идентификации// exists, this is an identity mapping

// ItemContext, клон объекта создается и добавляется к// ItemContext, an object clone is created and added to

// отображению. Если объект существует, он обновляется// display. If the object exists, it is updated.

// состоянием и контентом указанного объекта в// state and content of the specified object in

// соответствии с SearchCollisionMode.// according to SearchCollisionMode.

public Item IncorporateItem( Item item );public Item IncorporateItem (Item item);

public Relationship IncorporateRelationship(public Relationship IncorporateRelationship (

Relationship relationship);Relationship relationship);

public ItemExtension IncorporateItemExtension(public ItemExtension IncorporateItemExtension (

ItemExtension itemExtension);ItemExtension itemExtension);

}}

// Описатель для событий ItemContext.UpdateCollision и itemSearcher.SearchColIision// Descriptor for ItemContext.UpdateCollision and itemSearcher.SearchColIision events

public delegate void ChangeCollisionEventHandler(public delegate void ChangeCollisionEventHandler (

object source, ChangeCollisionEventArgs args);object source, ChangeCollisionEventArgs args);

// Аргументы для делегата ChangeCollisionEventHandler// Arguments for the delegate ChangeCollisionEventHandler

public class ChangeCollisionEventArgs: EventArgspublic class ChangeCollisionEventArgs: EventArgs

{{

// Измененный объект статьи, расширении статьи или// Modified article object, article extension, or

// отношения// relations

public object ModifiedObject {get;}public object ModifiedObject {get;}

// Свойства из хранилища// Properties from the repository

public IDictionary StoredProperties {get;}public IDictionary StoredProperties {get;}

}}

// Описатель для ItemContext.UpdateProgress.// Descriptor for ItemContext.UpdateProgress.

public delegate void UpdateProgressEventHandler(public delegate void UpdateProgressEventHandler (

ItemContext itemContext,ItemContext itemContext,

UpdateProgressEventArgs args);UpdateProgressEventArgs args);

// Аргументы для делегата UpdateProgressEventHandler// Arguments for the delegate UpdateProgressEventHandler

public class ChangeCollisionEventArgs: EventArgspublic class ChangeCollisionEventArgs: EventArgs

{{

// Текущая операция обновления// Current update operation

public UpdateOperation CurrentOperation { get; }public UpdateOperation CurrentOperation {get; }

// Объект, обновляемый в данный момент// The object currently being updated

public object CurrentObject { get;}public object CurrentObject {get;}

}}

//Указывает, как объекты, возвращенные в результате поиска,// Indicates how the objects returned from the search

// относятся к отображению идентификации объектов,// refer to the display of the identification of objects,

// поддерживаемому ItemContext.// supported ItemContext.

public enum SearchCollisionModepublic enum SearchCollisionMode

{{

// Указывает, как следует создавать и возвращать новые// Specifies how to create and return new ones

//объекты. Объекты, представляющие одну и ту же статью,// objects. Objects representing the same article

// расширение статьи или отношение в отображении// extension of the article or relation in the display

// идентификации игнорируются. Если эта опция задана,// identifications are ignored. If this option is specified,

// событие SearchCollision не будет возбуждаться.// the SearchCollision event will not be raised.

DoNotMapSearchResults,DoNotMapSearchResults,

// Указывает, что объекты из отображения идентификации// Indicates that the objects from the identity mapping

// должны быть возвращены. Если контент объекта был// must be returned. If the content of the object was

// изменен приложением, измененный контент объекта// modified by application, modified object content

//сохраняется. Если объект не был изменен, этот контент// saved. If the item has not been modified, this content

//обновляется данными, возвращенными в результате// updated with data returned as a result

// поиска. Приложение может обеспечивать описатель для// search. An application may provide a descriptor for

// события SearchCollision и избирательно обновлять// SearchCollision events and selectively update

// нужный объект.// desired object.

PreserveModifiedObjects,PreserveModifiedObjects,

// Указывает, что объекты из отображения идентификации// Indicates that the objects from the identity mapping

// должны быть возвращены. Контент объекта обновляется// must be returned. The content of the object is updated.

//данными, возвращенными в результате поиска, даже если// data returned from the search, even if

// объект был изменен приложением. Если эта опция// the object has been modified by the application. If this option

// задана, событие SearchCollision не будет// set, the SearchCollision event will not be

// возбуждаться.// get excited.

OverwriteModifiedObjectsOverwriteModifiedObjects

}}

// Текущая операция обновления// Current update operation

public enum UpdateOperationpublic enum UpdateOperation

{{

//Обеспечивается при первом вызове Update.// Provided the first time Update is called.

// CurrentObject будет null.// CurrentObject will be null.

OverallUpdateStarting,OverallUpdateStarting,

// Обеспечивается непосредственно перед тем, как Update// Provided just before Update

// возвращает после успешного обновления. CurrentObject// returns after a successful update. Currentobject

// будет null.// will be null.

OverallUpdateCompletedSucessfully,OverallUpdateCompletedSucessfully,

// Обеспечивается непосредственно перед тем, как Update// Provided just before Update

// выбрасывает исключение. CurrentObject будет объектом исключения.// throws an exception. CurrentObject will be the exception object.

OverallUpdateCompletedUnsuccessfully,OverallUpdateCompletedUnsuccessfully,

// Обеспечивается, когда начинается обновление объекта.// Provided when an object update begins.

// CurrentObject будет ссылаться на объект, который// CurrentObject will reference the object that

// будет использоваться для обновления.// will be used for updating.

ObjectUpdateStaring,ObjectUpdateStaring,

// Обеспечивается, когда необходимо новое соединение.// Provided when a new connection is needed.

// CurrentObject будет строкой, которая содержит путь,// CurrentObject will be a string that contains the path,

// идентифицирующий домен статьи, передаваемую// identifying domain of the article passed

// ItemContext.Open или извлекаемую из поля Location// ItemContext.Open or retrieved from the Location field

// отношения.// relations.

OpeningConnectionOpeningconnection

}}

}Приложение В} Appendix B

namespace System.Storagenamespace System.Storage

{{

// Выполняет поиск по конкретному типу в контексте статьи.// Searches for a specific type in the context of the article.

public class ItemSearcherpublic class ItemSearcher

{{

Конструкторы:Constructors:

public ItemSearcher();public ItemSearcher ();

public ItemSearcher(Type targetType,public ItemSearcher (Type targetType,

ItemContext context);ItemContext context);

public ItemSearcher(Type targetType,public ItemSearcher (Type targetType,

ItemContext context,ItemContext context,

params SearchExpression[] filters);params SearchExpression [] filters);

Свойства:Properties:

//Фильтры, используемые для идентификации совпадающих// Filters used to identify matching

// объектов.// objects.

public SearchExpressionCollection Filters {get;}public SearchExpressionCollection Filters {get;}

// ItemContext, который указывает домены, в которых// ItemContext, which indicates the domains in which

// будет производиться поиск.// will be searched.

public ItemContext ItemContext {get; set;}public ItemContext ItemContext {get; set;}

// Коллекция параметров поиска.// Collection of search parameters.

public ParameterCollection Parameters {get;}public ParameterCollection Parameters {get;}

// Тип, с которым будет работать механизм поиска.// Type with which the search engine will work.

// Для простых механизмов поиска это тип объекта,// For simple search engines, this is an object type,

// который будет возвращен.// to be returned.

public Type TargetType {get; set;}public Type TargetType {get; set;}

Методы поискаSearch methods

// Найти объекты TargetType, которые удовлетворяют// Find TargetType objects that satisfy

// условиям, указанным фильтрами. Возвращает пустой// conditions specified by filters. Returns empty

// FindResult, если таких объектов не существует.// FindResult if such objects do not exist.

public FindResult FindAll();public FindResult FindAll ();

public FindResult FindAll(FindOptions findOptions);public FindResult FindAll (FindOptions findOptions);

public FindResult FindAll(params SortOption[]public FindResult FindAll (params SortOption []

sortOptions);sortOptions);

// Найти любой один объект TargetType, который// Find any single TargetType object that

// удовлетворяет условиям, указанным фильтрами.// satisfies the conditions specified by the filters.

// Возвращает null, если такого объекта не существует.// Returns null if such an object does not exist.

public object FindOne();public object FindOne ();

public object FindOne(FindOptions findOptions);public object FindOne (FindOptions findOptions);

public object FindOne(params SortOption[]public object FindOne (params SortOption []

sortOptions);sortOptions);

// Найти объект TargetType, который удовлетворяет// Find a TargetType object that satisfies

// условиям, указанным фильтрами. Выбрасывает// conditions specified by filters. Throws away

// ObjectNotFoundException, если такой объект// ObjectNotFoundException, if such an object

// не найден.// not found.

public object FindOnly();public object FindOnly ();

public object FindOnly(FindOptions findOptions);public object FindOnly (FindOptions findOptions);

// Определить, существует ли объект TargetType, который// Determine if a TargetType exists that

// удовлетворяет условиям, указанным фильтрами.// satisfies the conditions specified by the filters.

public bool Exists();public bool Exists ();

//Создает объект, который можно использовать для более// Creates an object that can be used for more

// эффективного выполнения того же поиска повторно.// efficiently perform the same search repeatedly.

public PreparedFind PrepareFind();public PreparedFind PrepareFind ();

public PreparedFind PrepareFind(FindOptionspublic PreparedFind PrepareFind (FindOptions

findOptions);findOptions);

public PreparedFind PrepareFind(params SortOption[]public PreparedFind PrepareFind (params SortOption []

sortOptions);sortOptions);

// Извлекает количество записей, которые будут// Retrieves the number of records that will be

// возвращены FindAll().// returned by FindAll ().

public int GetCount();public int GetCount ();

// Асинхронные версии различных методов// Asynchronous versions of various methods

public IAsyncResult BeginFindAll(AsyncCallbackpublic IAsyncResult BeginFindAll (AsyncCallback

callback, object state);callback, object state);

public IAsyncResult BeginFindAll(FindOptionspublic IAsyncResult BeginFindAll (FindOptions

findOptions, AsyncCallback callback,findOptions, AsyncCallback callback,

object state);object state);

public IAsyncResult BeginFindAll(SortOption[]public IAsyncResult BeginFindAll (SortOption []

sortOptions, AsyncCallback callback,sortOptions, AsyncCallback callback,

object state);object state);

public FindResult EndFindAll(IAsyncResult ar);public FindResult EndFindAll (IAsyncResult ar);

public IAsyncResult BeginFindOne(AsyncCallbackpublic IAsyncResult BeginFindOne (AsyncCallback

callback, object state);callback, object state);

public IAsyncResult BeginFindOne(FindOptionspublic IAsyncResult BeginFindOne (FindOptions

findOptions, AsyncCallback callback,findOptions, AsyncCallback callback,

object state);object state);

public IAsyncResult BeginFindOne(SortOption[]public IAsyncResult BeginFindOne (SortOption []

sortOptions, AsyncCallback callback,sortOptions, AsyncCallback callback,

object state);object state);

public object EndFindOne(IAsyncResult asyncResult);public object EndFindOne (IAsyncResult asyncResult);

public IAsyncResult BeginFindOnly(AsyncCallbackpublic IAsyncResult BeginFindOnly (AsyncCallback

callback, object state);callback, object state);

public IAsyncResult BeginFindOnly(FindOptionspublic IAsyncResult BeginFindOnly (FindOptions

findOptions, AsyncCallback callback,findOptions, AsyncCallback callback,

object state);object state);

public IAsyncResult BeginFindOnly(SortOption[]public IAsyncResult BeginFindOnly (SortOption []

sortOptions, AsyncCallback callback,sortOptions, AsyncCallback callback,

object state);object state);

public object EndFindOnly( IAsyncResult asyncResult);public object EndFindOnly (IAsyncResult asyncResult);

public IAsyncResult BeginGetCount(AsyncCallbackpublic IAsyncResult BeginGetCount (AsyncCallback

callback, object state);callback, object state);

public int EndGetCount( IAsyncResult asyncResult);public int EndGetCount (IAsyncResult asyncResult);

public IAsyncResult BeginExists(AsyncCallback callback,public IAsyncResult BeginExists (AsyncCallback callback,

object state);object state);

public bool EndExists(IAsyncResult asyncResult);public bool EndExists (IAsyncResult asyncResult);

}}

//Опции, используемые при выполнении поиска.// Options used when performing the search.

public class FindOptionspublic class FindOptions

{{

public FindOptions();public FindOptions ();

public FindOptions(params SortOption[] sortOptions);public FindOptions (params SortOption [] sortOptions);

// Указывает, должны ли загружаться с задержкой поля,// Indicates whether fields should be loaded with a delay,

// загружаемые с задержкой.// loaded with a delay.

public bool DelayLoad {get; set;}public bool DelayLoad {get; set;}

// Количество возвращаемых совпадений// Number of returned matches

public int MaxResults {get; set;}public int MaxResults {get; set;}

// Коллекция опций сортировки// Collection of sorting options

public SortOptionCollection SortOptions {get;}public SortOptionCollection SortOptions {get;}

}}

// Представляет имя и значение параметра.// Represents the name and value of the parameter.

public class Parameterpublic class Parameter

{{

// Инициализирует объект Parameter именем и значением.// Initializes the Parameter object by name and value.

public Parameter(string name, object value);public Parameter (string name, object value);

// Имя параметра// parameter name

public string Name {get;}public string Name {get;}

// Значение параметра// Parameter value

public object Value {get; set;}public object Value {get; set;}

}}

//Коллекция пар имя/значение параметра// Collection of parameter name / value pairs

public class ParameterCollection: (Collectionpublic class ParameterCollection: (Collection

{{

public ParameterCollection();public ParameterCollection ();

public int Count {get;}public int Count {get;}

public object this[string name] {get; set;}public object this [string name] {get; set;}

public object SyncRoot {get;}public object SyncRoot {get;}

public void Add(Parameter parameter);public void Add (Parameter parameter);

public Parameter Add(string name, object value);public Parameter Add (string name, object value);

public bool Contains(Parameter parameter);public bool Contains (Parameter parameter);

public bool Contains(string name);public bool Contains (string name);

public void CopyTo(Parameter[] array, int index);public void CopyTo (Parameter [] array, int index);

void ICollection.CopyTo(Array array, int index);void ICollection.CopyTo (Array array, int index);

IEnumerator IEnumerable.GetEnumerator();IEnumerator IEnumerable.GetEnumerator ();

public void Remove(Parameter parameter);public void Remove (Parameter parameter);

public void Remove(string name);public void Remove (string name);

}}

// Представляет поиск, оптимизированный для повторного// Represents a search optimized for repeated

// выполнения// run

public class PreparedFindpublic class PreparedFind

{{

public ItemContext ItemContext {get;}public ItemContext ItemContext {get;}

public ParameterCollection Parameters {get;}public ParameterCollection Parameters {get;}

public FindResult FindAll();public FindResult FindAll ();

public object FindOne();public object FindOne ();

public object FindOnly();public object FindOnly ();

public bool Exists();public bool Exists ();

}}

// Указывает опции сортировки, используемые в поиске.// Specifies the sorting options used in the search.

public class SortOptionpublic class SortOption

{{

// Инициализирует объект значениями по умолчанию.// Initializes the object with default values.

public SortOption();public SortOption ();

// Инициализирует объект SortOptions посредством// Initializes the SortOptions object by

// SearchExpression, order.// SearchExpression, order.

public SortOption(SearchExpression searchExpression,public SortOption (SearchExpression searchExpression,

SortOrder order);SortOrder order);

// SearchExpression поиска, который идентифицирует// SearchExpression of the search that identifies

// свойство, по которому будет производиться// property to be produced

// сортировка.// sort.

public SearchExpression Expression {get; set;}public SearchExpression Expression {get; set;}

// Указывает возрастающий или убывающий порядок// Indicates ascending or descending order

// сортировки// sort

public SortOrder Order {get; set;}public SortOrder Order {get; set;}

}}

// Коллекция объектов опций сортировки// Collection of sort options objects

public class SortOptionCollection: IListpublic class SortOptionCollection: IList

{{

public SortOptionCollection();public SortOptionCollection ();

public SortOption this[int index] {get; set;}public SortOption this [int index] {get; set;}

public int Add(SortOption value);public int Add (SortOption value);

public int Add(SearchExpression expression,public int Add (SearchExpression expression,

SortOrder order);SortOrder order);

int IList.Add(object value);int IList.Add (object value);

public void Clear();public void Clear ();

public bool Contains(SortOption value);public bool Contains (SortOption value);

bool IList.Contains(object value);bool IList.Contains (object value);

public void CopyTo(SortOption[] array, int index);public void CopyTo (SortOption [] array, int index);

void ICollection.CopyTo(Array array, int index);void ICollection.CopyTo (Array array, int index);

public int Count {get;}public int Count {get;}

IEnumerator IEnumerable.GetEnumerator();IEnumerator IEnumerable.GetEnumerator ();

public void Insert(int index, SortOption value);public void Insert (int index, SortOption value);

void IList.Insert(int index, object value);void IList.Insert (int index, object value);

public int IndexOf(SortOption value);public int IndexOf (SortOption value);

int IList.IndexOf(object value);int IList.IndexOf (object value);

public void Remove(SortOption value);public void Remove (SortOption value);

void IList.Remove(object value);void IList.Remove (object value);

public void RemoveAt(int index);public void RemoveAt (int index);

public object SyncRoot {get;}public object SyncRoot {get;}

}}

// Указывает порядок сортировки с использованием объекта// Specifies the sort order using the object

// SortOption// SortOption

public enum SortOrderpublic enum SortOrder

{{

Ascending,Ascending,

DescendingDescending

}}

}Приложение С} Appendix C

namespace System.Storagenamespace System.Storage

{{

public abstract class FindResult: IAsyncObjectReaderpublic abstract class FindResult: IAsyncObjectReader

{{

public FindResult();public FindResult ();

// Перемещает FindResult в следующую позицию// Moves FindResult to the next position

// в результате.// as a result.

public bool Read();public bool Read ();

public IAsyncResult BeginRead(AsyncCallback callback,public IAsyncResult BeginRead (AsyncCallback callback,

object state);object state);

public bool EndRead(IAsyncResult asyncResult);public bool EndRead (IAsyncResult asyncResult);

// Текущий объект.// The current object.

public object Current {get;}public object Current {get;}

// Возвращает, содержит ли FindResult какие-либо// Returns whether FindResult contains any

// объекты.// objects.

public bool HasResults {get;}public bool HasResults {get;}

// Возвращает, закрыт ли FindResult// Returns whether FindResult is closed

public bool IsClosed {get;}public bool IsClosed {get;}

// Возвращает тип статей этого FindResult// Returns the article type of this FindResult

public Type ObjectType {get;}public Type ObjectType {get;}

// Закрывает FindResult// Closes FindResult

public void Closed;public void Closed;

void IDisposable.Dispose();void IDisposable.Dispose ();

//Возвращает перечислитель над FindResult, начинающийся// Returns an enumerator over FindResult starting

// с текущей позиции. Продвигает любой перечислитель,// from the current position. Promotes any enumerator

// когда FindResult продвигает все перечислители,// when FindResult promotes all enumerators,

// а также сам FindResult.// as well as FindResult itself.

IEnumerator IEnumerable.GetEnumerator();IEnumerator IEnumerable.GetEnumerator ();

public FindResultEnumerator GetEnumerator();public FindResultEnumerator GetEnumerator ();

}}

public abstract class FindResultEnumerator: (Enumerator,public abstract class FindResultEnumerator: (Enumerator,

IDisposableIDisposable

{{

public abstract object Current {get;}public abstract object Current {get;}

public abstract bool MoveNext();public abstract bool MoveNext ();

public abstract void Reset();public abstract void Reset ();

public abstract void Close();public abstract void Close ();

void IDisposable.Dispose();void IDisposable.Dispose ();

}}

}}

namespace Systemnamespace system

{{

//Общий интерфейс для итерации по объектам.// General interface for iterating over objects.

public interface IObjectReader: IEnumerable, IDisposablepublic interface IObjectReader: IEnumerable, IDisposable

{{

object Current {get;}object Current {get;}

bool IsClosed {get;}bool IsClosed {get;}

bool HasResults {get;}bool HasResults {get;}

Type ObjectType {get;}Type ObjectType {get;}

bool Read();bool Read ();

void Close();void Close ();

}}

// Добавляет асинхронные методы в IObjectReader.// Adds asynchronous methods to IObjectReader.

public interface IAsyncObjectReader: IObjectReaderpublic interface IAsyncObjectReader: IObjectReader

{{

IAsyncResult BeginRead(AsyncCallback callback,IAsyncResult BeginRead (AsyncCallback callback,

object state);object state);

bool EndRead(IAsyncResult result);bool EndRead (IAsyncResult result);

}}

}}

Claims (16)

1. Платформа хранения, включающая в себя процессор и считываемый компьютером носитель данных, содержащий записанные на нем инструкции, которые, при выполнении их компьютером, приводят к реализации упомянутым компьютером функций операционной системы, при этом упомянутая операционная система содержит ядро, включающее в себя программные средства управления базами данных, выполненные с возможностью сохранения данных в упомянутой файловой системе в виде потоков файлов, генерации элементов, включающих в себя метаданные для упомянутых потоков файлов, и сохранения упомянутых элементов с помощью упомянутых программных средств управления базами данных, при этом упомянутые программные средства управления базами данных содержат базовую схему и механизм, выполненный с возможностью расширения упомянутой базовой схемы для определения схемы для упомянутых данных и разделения упомянутых данных на программно определенные элементы изменения, основываясь на упомянутой схеме для упомянутых данных, причем упомянутый элемент изменения представляет собой наименьшую часть схемы, которая может быть индивидуально отслежена упомянутыми программными средствами управления базами данных, при этом размер элемента изменения является регулируемым;
упомянутая операционная система дополнительно включает в себя подсистему синхронизации, выполненную с возможностью синхронизации упомянутых данных, сохраненных с помощью упомянутых программных средств управления базами данных, с удаленным компьютером, основываясь на изменениях, которые являются последовательно пронумерованными и отслеживаются в отношении каждого элемента изменения;
при этом
упомянутые данные заданы в терминах статей, элементов и отношений, при этом статья является единицей данных, сохраняемой в хранилище данных, и содержит один или более элементов, причем элемент представляет собой экземпляр типа, содержащий одно или более полей, и отношение представляет собой связь между, по меньшей мере, двумя статьями,
множество схем, которые задают разные типы статей, элементов и отношений, и
программный интерфейс приложения, содержащий класс для каждой из различных статей, элементов и отношений, заданных в множестве схем.
1. A storage platform including a processor and a computer-readable storage medium containing instructions recorded thereon which, when executed by a computer, lead to the implementation by the computer of the functions of the operating system, said operating system comprising a kernel including software database management, configured to save data in said file system as file streams, generate elements including metadata for said stream files, and storing said elements using said database management software, said database management software comprising a basic circuit and a mechanism adapted to extend said basic circuit to define a circuit for said data and to divide said data into software defined change elements based on said pattern for said data, said change element being the smallest part of the circuit that paradise can be individually tracked by said software database management, the size changing element is adjustable;
said operating system further includes a synchronization subsystem adapted to synchronize said data stored by said database management software with a remote computer based on changes that are sequentially numbered and tracked with respect to each change element;
wherein
said data is defined in terms of articles, elements and relationships, wherein the article is a unit of data stored in a data warehouse and contains one or more elements, the element being an instance of a type containing one or more fields, and the relation is a relationship between, in at least two articles,
many schemes that define different types of articles, elements and relationships, and
application programming interface containing a class for each of the various articles, elements, and relationships defined in a variety of schemes.
2. Платформа хранения по п.1, в которой данные также могут храниться в хранилище данных в виде расширения к существующему типу статьи, и в которой программный интерфейс приложения содержит класс для каждого отдельного расширения статьи.2. The storage platform according to claim 1, in which data can also be stored in a data warehouse as an extension to an existing article type, and in which the application programming interface contains a class for each individual article extension. 3. Платформа хранения по п.1, в которой класс для каждого типа статьи, элемента и отношения генерируется автоматически на основании множества схем, которые задают каждый тип статьи, элемента и отношения.3. The storage platform according to claim 1, in which a class for each type of article, element and relationship is generated automatically based on the set of schemes that define each type of article, element and relationship. 4. Платформа хранения по п.1, в которой классы для каждого типа статьи, элемента и отношения задают множество классов данных, и в которой программный интерфейс приложения дополнительно содержит второе множество классов, которые задают общее множество поведений для классов данных.4. The storage platform according to claim 1, in which the classes for each type of article, element and relationship define a set of data classes, and in which the application programming interface further comprises a second set of classes that specify a common set of behaviors for data classes. 5. Платформа хранения по п.4, в которой второе множество классов содержит первый класс, который представляет область действия платформы хранения и который обеспечивает контекст для запросов на хранилище данных, и второй класс, который представляет результаты запроса на хранилище данных.5. The storage platform according to claim 4, in which the second set of classes contains the first class, which represents the scope of the storage platform and which provides the context for queries on the data warehouse, and the second class, which represents the results of the query on the data warehouse. 6. Платформа хранения по п.1, дополнительно содержащая машину базы данных, на которой реализовано хранилище данных, и в которой разные типы статей, элементов и отношений в хранилище данных реализованы в машине базы данных как типы, заданные пользователем (UDT).6. The storage platform according to claim 1, additionally containing a database machine on which the data warehouse is implemented, and in which different types of articles, elements and relationships in the data warehouse are implemented in the database machine as user-defined types (UDT). 7. Платформа хранения по п.6, в которой программный интерфейс приложения обеспечивает модель запроса, которая позволяет разработчикам прикладных программ формировать запросы на основании различных свойств статей в хранилище данных, таким образом, чтобы разработчик прикладной программы был изолирован от деталей языка запросов машины базы данных.7. The storage platform according to claim 6, in which the application programming interface provides a query model that allows application developers to generate queries based on various properties of articles in the data warehouse, so that the application developer is isolated from the details of the query language of the database machine . 8. Способ обеспечения программного интерфейса приложения между прикладной программой и платформой хранения для хранения, организации, совместного использования и поиска данных, причем платформа хранения содержит хранилище данных, в котором данные, хранящиеся в нем, заданы в терминах статей, элементов и отношений, при этом статья является единицей данных, сохраняемой в хранилище данных, и содержит один или более элементов, причем элемент представляет собой экземпляр типа, содержащий одно или более полей, и отношение представляет собой связь между, по меньшей мере, двумя статьями, способ содержит этапы, на которых
обеспечивают множество схем, которые задают разные типы статей, элементов и отношений, и
генерируют, как часть программного интерфейса приложения, класс для каждой из различных статей, элементов и отношений, заданных во множестве схем;
при этом платформа хранения включает в себя процессор и считываемый компьютером носитель данных, содержащий записанные на нем инструкции, которые при выполнении их компьютером приводят к реализации упомянутым компьютером функций операционной системы, при этом упомянутая операционная система содержит ядро, включающее в себя программные средства управления базами данных, причем упомянутые программные средства управления базами данных выполнены с возможностью сохранения данных в упомянутой файловой системе в виде потоков файлов, генерации элементов, включающих в себя метаданные для упомянутых потоков файлов, и сохранения упомянутых элементов с помощью упомянутых программных средств управления базами данных, при этом упомянутые программные средства управления базами данных содержат базовую схему и механизм, выполненный с возможностью расширения упомянутой базовой схемы для определения схемы для упомянутых данных и разделения упомянутых данных на программно определенные элементы изменения, основываясь на упомянутой схеме для упомянутых данных, причем упомянутый элемент изменения представляет собой наименьшую часть схемы, которая может быть индивидуально отслежена упомянутыми программными средствами управления базами данных, при этом размер элемента изменения является регулируемым;
упомянутая операционная система дополнительно включает в себя подсистему синхронизации, выполненную с возможностью синхронизации упомянутых данных, сохраненных с помощью упомянутых программных средств управления базами данных, с удаленным компьютером, основываясь на изменениях, которые являются последовательно пронумерованными и отслеживаются в отношении каждого элемента изменения.
8. A method of providing an application programming interface between an application and a storage platform for storing, organizing, sharing and searching data, the storage platform comprising a data warehouse in which data stored therein is defined in terms of articles, elements and relationships, wherein an article is a unit of data stored in a data warehouse and contains one or more elements, the element being an instance of a type containing one or more fields, and the relation is communicating between at least two articles, the method comprising the steps of:
provide many schemes that define different types of articles, elements and relationships, and
generating, as part of the application programming interface, a class for each of the various articles, elements, and relationships defined in the plurality of schemes;
wherein the storage platform includes a processor and a computer-readable storage medium containing instructions recorded thereon which, when executed by a computer, lead to the implementation of the functions of the operating system by the computer, said operating system comprising a kernel including database management software wherein said database management software is configured to save data in said file system as file streams, a gene walkie-talkies of elements including metadata for said file streams and storing said elements using said database management software, said database management software comprising a basic circuit and a mechanism adapted to extend said basic circuit to define a circuit for said data and dividing said data into programmatically determined change elements based on said scheme for said data, change element is the smallest part of a circuit which may be tracked individually by said software database management, the size changing element is adjustable;
said operating system further includes a synchronization subsystem configured to synchronize said data stored by said database management software with a remote computer based on changes that are sequentially numbered and tracked for each change item.
9. Способ по п.8, в котором данные также могут храниться в хранилище данных в виде расширения к существующему типу статьи и в котором способ дополнительно содержит генерацию класса для каждого отдельного расширения статьи.9. The method of claim 8, in which the data can also be stored in the data warehouse as an extension to the existing type of article and in which the method further comprises generating a class for each individual article extension. 10. Способ по п.9, в котором сгенерированные классы для каждого типа статьи, элемента и отношения задают множество классов данных, и в котором способ дополнительно содержит этап, на котором обеспечивают, как дополнительную часть программного интерфейса приложения, второе множество классов, которые задают общее множество поведений для классов данных.10. The method according to claim 9, in which the generated classes for each type of article, element and relationship define a variety of data classes, and in which the method further comprises providing, as an additional part of the application programming interface, a second set of classes that specify common set of behaviors for data classes. 11. Способ по п.10, в котором второе множество классов содержит первый класс, который представляет область действия платформы хранения и который обеспечивает контекст для запросов на хранилище данных, и второй класс, который представляет результаты запроса на хранилище данных.11. The method of claim 10, wherein the second set of classes comprises a first class that represents the scope of the storage platform and which provides a context for data warehouse queries, and a second class that represents the results of the data warehouse query. 12. Способ по п.8, в котором хранилище данных платформы хранения реализовано на машине базы данных и в котором способ дополнительно содержит этап, на котором реализуют разные типы статей, элементов и отношений в хранилище данных как типы, заданные пользователем, (UDT) в машине базы данных.12. The method of claim 8, wherein the storage platform data warehouse is implemented on the database machine and the method further comprises the step of implementing different types of articles, elements and relationships in the data warehouse as user-defined types (UDT) in database machine. 13. Компьютерная система, содержащая процессор и компьютерочитаемый носитель информации, содержащий инструкции, хранимые на нем, которые при исполнении процессором побуждают процессор реализовать программный интерфейс приложения, операционную систему и хранилище данных, при этом хранилище данных сконфигурировано для хранения данных, заданных в терминах статей, элементов и отношений, в которой статья является единицей данных, сохраняемой в хранилище данных, и содержит один или более элементов, причем элемент представляет собой экземпляр типа, содержащий одно или более полей, и отношение представляет собой связь между, по меньшей мере, двумя статьями, причем программный интерфейс приложения, включает в себя классы данных, представляющие элемент платформы хранения и типы статей, структуру среды выполнения, сконфигурированную для регулирования живучести объекта и обеспечения классов поддержки и инструменты, сконфигурированные
для генерации классов CLR из схем платформы хранения,
при этом упомянутая операционная система включает в себя ядро, включающее в себя программные средства управления базами данных, для сохранения данных в упомянутой файловой системе в виде потоков файлов, генерации элементов, включающих в себя метаданные для упомянутых потоков файлов, и сохранения упомянутых элементов с помощью упомянутых программных средств управления базами данных, при этом упомянутые программные средства управления базами данных содержат базовую схему и механизм, выполненный с возможностью расширения упомянутой базовой схемы для определения схемы для упомянутых данных и разделения упомянутых данных на программно определенные элементы изменения, основываясь на упомянутой схеме для упомянутых данных, причем упомянутый элемент изменения представляет собой наименьшую часть схемы, которая может быть индивидуально отслежена упомянутыми программными средствами управления базами данных, и размер элемента изменения является регулируемым;
упомянутая операционная система дополнительно включает в себя подсистему синхронизации, выполненную с возможностью синхронизации упомянутых данных, сохраненных с помощью упомянутых программных средств управления базами данных, с удаленным компьютером, основываясь на изменениях, которые являются последовательно пронумерованными и отслеживаются в отношении каждого элемента изменения.
13. A computer system comprising a processor and a computer-readable storage medium containing instructions stored on it, which, when executed by the processor, cause the processor to implement the application programming interface, operating system and data storage, the data storage being configured to store data specified in terms of articles, elements and relationships in which an article is a unit of data stored in a data warehouse and contains one or more elements, the element being an instance p type, containing one or more fields, and the relationship is the relationship between at least two articles, moreover, the application programming interface includes data classes representing an element of the storage platform and article types, a runtime structure configured to control survivability object and support classes support and tools configured
to generate CLR classes from storage platform schemas,
wherein said operating system includes a kernel including database management software for storing data in said file system as file streams, generating elements including metadata for said file streams, and storing said elements using said database management software, wherein said database management software comprises a basic circuit and a mechanism configured to expand said ba a new scheme for determining a scheme for said data and dividing said data into programmatically determined change elements based on said scheme for said data, said change element being the smallest part of a circuit that can be individually tracked by said database management software, and size The item change is adjustable;
said operating system further includes a synchronization subsystem configured to synchronize said data stored by said database management software with a remote computer based on changes that are sequentially numbered and tracked for each change item.
14. Компьютерная система по п.13, в котором данные также могут храниться в хранилище данных в виде расширения к существующему типу статьи, и в котором программный интерфейс приложения дополнительно содержит класс для каждого отдельного расширения статьи.14. The computer system according to item 13, in which data can also be stored in the data warehouse as an extension to the existing type of article, and in which the application programming interface further comprises a class for each individual article extension. 15. Компьютерная система по п.13, в которой классы для каждого типа статьи, элемента и отношения задают множество классов данных, и в которой программный интерфейс приложения дополнительно содержит второе множество классов, которые задают общее множество поведений для классов данных.15. The computer system according to item 13, in which the classes for each type of article, element and relationship define a set of data classes, and in which the application programming interface further comprises a second set of classes that specify a common set of behaviors for data classes. 16. Компьютерная система по п.15, в которой второе множество классов содержит первый класс, который представляет область действия платформы хранения и который обеспечивает контекст для запросов на хранилище данных, и второй класс, который представляет результаты запроса на хранилище данных. 16. The computer system according to clause 15, in which the second set of classes contains the first class, which represents the scope of the storage platform and which provides the context for queries on the data warehouse, and the second class, which represents the results of the query on the data warehouse.
RU2006105196/08A 2003-08-21 2003-08-21 Systems and methods of interfacing application programs with article based storage platform RU2412461C2 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2006105196/08A RU2412461C2 (en) 2003-08-21 2003-08-21 Systems and methods of interfacing application programs with article based storage platform

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2006105196/08A RU2412461C2 (en) 2003-08-21 2003-08-21 Systems and methods of interfacing application programs with article based storage platform

Publications (2)

Publication Number Publication Date
RU2006105196A RU2006105196A (en) 2006-08-27
RU2412461C2 true RU2412461C2 (en) 2011-02-20

Family

ID=37061174

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2006105196/08A RU2412461C2 (en) 2003-08-21 2003-08-21 Systems and methods of interfacing application programs with article based storage platform

Country Status (1)

Country Link
RU (1) RU2412461C2 (en)

Cited By (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2461887C1 (en) * 2011-08-10 2012-09-20 Федеральное Государственное Унитарное Предприятие Ордена Трудового Красного Знамени Научно-Исследовательский Институт Радио (Фгуп Ниир) Method of transmitting information to mobile terminal to ensure safety of users
RU2498400C1 (en) * 2012-05-10 2013-11-10 Владимир Юрьевич Вербицкий Associative identifier of events, technological
RU2586062C2 (en) * 2011-11-15 2016-06-10 Нек Корпорейшн Network communication device and method for selective restriction of bandwidth of transmission frame
RU2646334C2 (en) * 2013-04-30 2018-03-02 МАЙКРОСОФТ ТЕКНОЛОДЖИ ЛАЙСЕНСИНГ, ЭлЭлСи File management using placeholders
US10264039B2 (en) 2013-05-01 2019-04-16 Microsoft Technology Licensing, Llc Streaming content and placeholders

Cited By (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2461887C1 (en) * 2011-08-10 2012-09-20 Федеральное Государственное Унитарное Предприятие Ордена Трудового Красного Знамени Научно-Исследовательский Институт Радио (Фгуп Ниир) Method of transmitting information to mobile terminal to ensure safety of users
RU2586062C2 (en) * 2011-11-15 2016-06-10 Нек Корпорейшн Network communication device and method for selective restriction of bandwidth of transmission frame
RU2498400C1 (en) * 2012-05-10 2013-11-10 Владимир Юрьевич Вербицкий Associative identifier of events, technological
RU2646334C2 (en) * 2013-04-30 2018-03-02 МАЙКРОСОФТ ТЕКНОЛОДЖИ ЛАЙСЕНСИНГ, ЭлЭлСи File management using placeholders
US10264039B2 (en) 2013-05-01 2019-04-16 Microsoft Technology Licensing, Llc Streaming content and placeholders

Also Published As

Publication number Publication date
RU2006105196A (en) 2006-08-27

Similar Documents

Publication Publication Date Title
US7428546B2 (en) Systems and methods for data modeling in an item-based storage platform
US7483915B2 (en) Systems and method for representing relationships between units of information manageable by a hardware/software interface system
US8131739B2 (en) Systems and methods for interfacing application programs with an item-based storage platform
US7555497B2 (en) Systems and methods for separating units of information manageable by a hardware/software interface system from their physical organization
KR101120817B1 (en) Systems and methods for providing relational and hierarchical synchronization services for units of information manageable by hardware/software interface system
US7739316B2 (en) Systems and methods for the implementation of base schema for organizing units of information manageable by a hardware/software interface system
US7349913B2 (en) Storage platform for organizing, searching, and sharing data
US7529811B2 (en) Systems and methods for the implementation of a core schema for providing a top-level structure for organizing units of information manageable by a hardware/software interface system
JP4394643B2 (en) System and method for data modeling in an item-based storage platform
KR100959473B1 (en) Systems and methods for interfacing application programs with an item-based storage platform
JP4583376B2 (en) System and method for realizing a synchronous processing service for a unit of information manageable by a hardware / software interface system
US20050055354A1 (en) Systems and methods for representing units of information manageable by a hardware/software interface system but independent of physical representation
JP4580390B2 (en) System and method for extending and inheriting information units manageable by a hardware / software interface system
JP4583375B2 (en) System for implementation of synchronization schema
JP4394644B2 (en) Storage platform for organizing, searching, and sharing data
RU2412461C2 (en) Systems and methods of interfacing application programs with article based storage platform
RU2371757C2 (en) Systems and methods of data modelling in storage platform based on subjects
KR101109390B1 (en) Systems and methods for providing synchronization services for units of information manageable by a hardware/software interface system
KR20060110733A (en) System and methods for synchronizing computer systems through an intermediary file system share or device
ZA200600644B (en) Systems and methods for interfacing application programs with an item-based storage platform

Legal Events

Date Code Title Description
PC41 Official registration of the transfer of exclusive right

Effective date: 20150526

MM4A The patent is invalid due to non-payment of fees

Effective date: 20150822