/// <summary> /// Возвращает метаданные всех версий файла. /// </summary> /// <param name="file">Метаданные файла.</param> /// <returns>Коллекцию метаданных версий файла.</returns> internal FileVersionsCollection GetFileVersions(FileMetadata file) { if (file == null) { throw new ArgumentNullException("file"); } FileVersionsCollection versions = new FileVersionsCollection(file); string query = String.Format("[FileID] = '{0}'", file.ID); string tableName = this.GetTableName(file); DBObjectDistributedTable table = this.MetadataAdapter.TableActivator.GetDistributedTable(this.DBSchemaAdapter, tableName); MetadataQueryBuilder queryBuilder = new MetadataQueryBuilder(table.TablePartition.Table, this.TypeDefinition); string resultQuery = @"{SelectQuery} WHERE {Query} ORDER BY [TimeCreated] ASC" .ReplaceKey("SelectQuery", queryBuilder.SelectQuery) .ReplaceKey("Query", query); DataTable resultTable = this.DataAdapter.GetDataTable(resultQuery); if (resultTable != null) { foreach (DataRow row in resultTable.Rows) { FileVersionMetadata metadata = new FileVersionMetadata(row, versions); versions.AddVersion(metadata); } } return(versions); }
/// <summary> /// Возвращает метаданные файла по уникальному идентификатору. /// </summary> /// <param name="uniqueID">Уникальный идентификатор.</param> /// <param name="folderMetadata">Метаданные папки в которой располагается файл.</param> /// <returns></returns> internal FileMetadata GetFile(Guid uniqueID, IFolderMetadata folderMetadata) { if (uniqueID == Guid.Empty) { throw new ArgumentNullException("uniqueID"); } if (folderMetadata == null) { throw new ArgumentNullException("folderMetadata"); } FileMetadata metadata = null; string query = String.Format("[UniqueID] = '{0}' AND Deleted != 1", uniqueID); string tableName = this.GetTableName(uniqueID, folderMetadata); DBObjectDistributedTable table = this.MetadataAdapter.TableActivator.GetDistributedTable(this.DBSchemaAdapter, tableName); MetadataQueryBuilder queryBuilder = new MetadataQueryBuilder(table.TablePartition.Table, this.TypeDefinition); string resultQuery = @"{SelectQuery} WHERE {Query}" .ReplaceKey("SelectQuery", queryBuilder.SelectQuery) .ReplaceKey("Query", query); DataRow resultRow = this.DataAdapter.GetDataRow(resultQuery); if (resultRow != null) { metadata = new FileMetadata(resultRow, this, folderMetadata); } return(metadata); }
public List <MetadataType> GetMetadata( string sensorNumber, int?sensorID, bool?onlyLast, [Service] IMetadataRepository repo ) { var queryString = MetadataQueryBuilder.CreateMetadataString(sensorID, sensorNumber, onlyLast); return(repo.GetMetadata(queryString).Result); }
public bool QueryAttributeDisplayNamesForTwoEntities() { MetadataQueryBuilder builder = new MetadataQueryBuilder(); builder.AddEntities(new List <string>("account", "contact"), new List <string>("Attributes", "DisplayName", "DisplayCollectionName")); builder.AddAttributes(new List <string>("name", "firstname", "statecode", "statuscode"), new List <string>("DisplayName")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(builder.Request); return(true); }
public bool QueryNameAttributeForAccount() { MetadataQueryBuilder builder = new MetadataQueryBuilder(); builder.AddEntities(new List <string>("account"), new List <string>("PrimaryNameAttribute")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(builder.Request); Assert.AreEqual(response.EntityMetadata[0].PrimaryNameAttribute, "name"); return(true); }
/// <summary> /// Получение токена доступа к версии файла по уникальносму идентификатору. /// </summary> /// <param name="fileVersionMetadata">Метаданные версии файла.</param> /// <param name="tokenUniqueID">Уникальный идентификатор токена.</param> /// <returns></returns> public IFileToken GetToken(IFileVersionMetadata fileVersionMetadata, Guid tokenUniqueID) { FileToken token = null; this.Logger.WriteFormatMessage("GetToken: Начало операции получения токена. tokenUniqueID='{0}' fileUniqueID='{1}' folderUrl='{2}'", tokenUniqueID, fileVersionMetadata.FileMetadata.UniqueID, fileVersionMetadata.FileMetadata.FolderMetadata.Url); string tableName = this.GetTableName(fileVersionMetadata.FileMetadata); DBObjectDistributedTable table = null; this.Logger.WriteMessage("GetToken: Получение таблицы."); try { table = this.TypedMetadataAdapter.TableActivator.GetDistributedTable(this.DBSchemaAdapter, tableName); } //В случае когда для данного файла и папки генерация токена не запрашивалась, таблица токенов могла быть не создана. //В данном случае ошибки нет, т.к. токен еще не генерировался. catch (DistributedTableNotFoundException notFoundEx) { return(null); } catch (Exception ex) { throw ex; } this.Logger.WriteMessage("GetToken: Конец получения таблицы."); MetadataQueryBuilder queryBuilder = new MetadataQueryBuilder(table.TablePartition.Table, this.TypeDefinition); string query = @" {SelectQuery} WHERE [UniqueID] = '{UniqueID}' AND [Expired] > GETDATE()" .ReplaceKey("SelectQuery", queryBuilder.SelectQuery) .ReplaceKey("UniqueID", tokenUniqueID); this.Logger.WriteFormatMessage("GetToken: Начало запроса в БД. Запрос:'{0}'", query); DataRow resultRow = this.DataAdapter.GetDataRow(query); this.Logger.WriteMessage("GetToken: Конец запроса в БД."); if (resultRow != null) { token = new FileToken(resultRow, fileVersionMetadata); } this.Logger.WriteMessage("GetToken: Конец."); return(token); }
/// <summary> /// Проверяет наличие уже выданного токена на файл и при отсутствии создает новый. /// </summary> /// <param name="fileVersionMetadata">Метаданные версии файла.</param> /// <returns>Токен доступа к версии файла.</returns> private FileToken EnsureFileToken(IFileVersionMetadata fileVersionMetadata) { if (fileVersionMetadata == null) { throw new ArgumentNullException("fileVersionMetadata"); } this.Logger.WriteFormatMessage("EnsureFileToken: Начало операции. fileUniqueID: {0}, folderUrl: {1}", fileVersionMetadata.FileMetadata.UniqueID, fileVersionMetadata.FileMetadata.FolderMetadata.Url); FileToken fileToken = null; this.Logger.WriteMessage("EnsureFileToken: Получение таблицы."); string tableName = this.GetTableName(fileVersionMetadata.FileMetadata); DBObjectDistributedTable table = this.TypedMetadataAdapter.TableActivator.EnsureDistributedTable(this.DBSchemaAdapter, tableName); MetadataQueryBuilder queryBuilder = new MetadataQueryBuilder(table.TablePartition.Table, this.TypeDefinition); this.Logger.WriteMessage("EnsureFileToken: Конец получения таблицы."); string resultQuery = @"DELETE FROM {TableName} WHERE [Expired] < GETDATE() {SelectQuery} WHERE [FileID] = {FileID} AND [VersionID] = {VersionID} AND ([SecurityIdentifier] IS NULL OR [SecurityIdentifier] = '')" .ReplaceKey("TableName", tableName) .ReplaceKey("SelectQuery", queryBuilder.SelectQuery) .ReplaceKey("FileID", fileVersionMetadata.FileMetadata.ID) .ReplaceKey("VersionID", fileVersionMetadata.ID); this.Logger.WriteFormatMessage("EnsureFileToken: Начало запроса в БД. Запрос:{0}", resultQuery); DataRow tokenRow = this.DataAdapter.GetDataRow(resultQuery); this.Logger.WriteMessage("EnsureFileToken: Конец запроса в БД."); if (tokenRow != null) { fileToken = new FileToken(tokenRow, fileVersionMetadata); } else { fileToken = this.CreateToken(fileVersionMetadata, null); } this.Logger.WriteMessage("EnsureFileToken: Конец операции."); return(fileToken); }
private void QueryQuickSearchEntities() { OrganizationServiceProxy.RegisterExecuteMessageResponseType("ExecuteFetch", typeof(ExecuteFetchResponse)); // Get the entities defined in the correct order string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='multientitysearchentities'> <attribute name='entityname' /> <order attribute='entityorder' descending='false' /> </entity> </fetch>"; // We have to use the deprecated ExecuteFetchRequest because you can't access the multientitysearchentities through RetrieveMultiple ExecuteFetchRequest request = new ExecuteFetchRequest(); request.FetchXml = fetchxml; ExecuteFetchResponse entityList = (ExecuteFetchResponse)OrganizationServiceProxy.Execute(request); jQueryObject entityListDOM = jQuery.FromHtml(entityList.FetchXmlResult); _entityTypeNames = new List <string>(); jQueryObject results = entityListDOM.First().Find("result"); results.Each(delegate(int index, Element element) { string entityName = XmlHelper.SelectSingleNodeValue((XmlNode)(object)element, "entityname"); _entityTypeNames.Add(entityName); }); MetadataQueryBuilder builder = new MetadataQueryBuilder(); builder.AddEntities(_entityTypeNames, new List <string>("ObjectTypeCode", "DisplayCollectionName")); builder.SetLanguage((int)Script.Literal("USER_LANGUAGE_CODE")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(builder.Request); _entityMetadata = new Dictionary <string, EntityMetadata>(); foreach (EntityMetadata entity in response.EntityMetadata) { _entityMetadata[entity.LogicalName] = entity; } }
public void QueryMetadata() { // Load the display Names MetadataQueryBuilder builder = new MetadataQueryBuilder(); List <string> entities = new List <string>(); List <string> attributes = new List <string>(); foreach (string entityLogicalName in EntityLookup.Keys) { entities.Add(entityLogicalName); EntityQuery entity = EntityLookup[entityLogicalName]; foreach (string attributeLogicalName in entity.Attributes.Keys) { AttributeQuery attribute = entity.Attributes[attributeLogicalName]; string fieldName = attribute.LogicalName; int pos = fieldName.IndexOf('.'); if (entity.AliasName != null && pos > -1) { fieldName = fieldName.Substr(pos); } attributes.Add(fieldName); } } builder.AddEntities(entities, new List <string>("Attributes", "DisplayName", "DisplayCollectionName", "PrimaryImageAttribute")); builder.AddAttributes(attributes, new List <string>("DisplayName", "AttributeType", "IsPrimaryName")); builder.SetLanguage((int)Script.Literal("USER_LANGUAGE_CODE")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)OrganizationServiceProxy.Execute(builder.Request); // Update the display names // TODO: Add the lookup relationship in brackets for alias entitie foreach (EntityMetadata entityMetadata in response.EntityMetadata) { // Get the entity EntityQuery entityQuery = EntityLookup[entityMetadata.LogicalName]; entityQuery.DisplayName = entityMetadata.DisplayName.UserLocalizedLabel.Label; entityQuery.DisplayCollectionName = entityMetadata.DisplayCollectionName.UserLocalizedLabel.Label; entityQuery.PrimaryImageAttribute = entityMetadata.PrimaryImageAttribute; entityQuery.EntityTypeCode = entityMetadata.ObjectTypeCode; foreach (AttributeMetadata attribute in entityMetadata.Attributes) { if (entityQuery.Attributes.ContainsKey(attribute.LogicalName)) { // Set the type AttributeQuery attributeQuery = entityQuery.Attributes[attribute.LogicalName]; attributeQuery.AttributeType = attribute.AttributeType; switch (attribute.AttributeType) { case AttributeTypeCode.Lookup: case AttributeTypeCode.Picklist: case AttributeTypeCode.Customer: case AttributeTypeCode.Owner: case AttributeTypeCode.Status: case AttributeTypeCode.State: case AttributeTypeCode.Boolean_: LookupAttributes[attribute.LogicalName] = attributeQuery; break; } attributeQuery.IsPrimaryName = attribute.IsPrimaryName; // If the type is a lookup, then add the 'name' on to the end in the fetchxml // this is so that we search the text value and not the numeric/guid value foreach (Column col in attributeQuery.Columns) { col.Name = attribute.DisplayName.UserLocalizedLabel.Label; col.DataType = attribute.IsPrimaryName.Value ? "PrimaryNameLookup" : attribute.AttributeType.ToString(); } } } } }