Exemple #1
0
        public async Task <IEnumerable <AppGroupResponse> > GetAppGroupsAsync(SqlQuery query)
        {
            ResourceWrapper <AppGroupResponse> response = await base.RequestAsync <ResourceWrapper <AppGroupResponse> >(
                method : HttpMethod.Get,
                resource : "app_group",
                query : query
                );

            return(response.Records);
        }
Exemple #2
0
 public override void StartHolding(ItemActionData _actionData)
 {
     ItemActionSpawnCustomVehicle.ItemActionDataSpawnCustomVehicle itemActionDataSpawnMinibike = (ItemActionSpawnCustomVehicle.ItemActionDataSpawnCustomVehicle)_actionData;
     if (itemActionDataSpawnMinibike.MinibikePreview == null && itemActionDataSpawnMinibike.invData.holdingEntity is EntityPlayerLocal)
     {
         GameObject gameObject = (GameObject)ResourceWrapper.Load1P(itemActionDataSpawnMinibike.invData.holdingEntity.inventory.holdingItem.MeshFile);
         itemActionDataSpawnMinibike.MinibikePreview = UnityEngine.Object.Instantiate <Transform>(gameObject.transform);
         this.BB(_actionData);
     }
 }
Exemple #3
0
        public void GivenResults_WhenInitialized_ThenCorrectResultsShouldBeSet()
        {
            var expectedResourceWrapper             = new ResourceWrapper[0];
            var expectedUnsupportedSearchParameters = new List <Tuple <string, string> >();

            var searchResult = new SearchResult(expectedResourceWrapper, expectedUnsupportedSearchParameters, null);

            Assert.Same(expectedResourceWrapper, searchResult.Results);
            Assert.Same(expectedUnsupportedSearchParameters, searchResult.UnsupportedSearchParameters);
        }
Exemple #4
0
        public async Task <IEnumerable <UserResponse> > GetUsersAsync(SqlQuery query)
        {
            ResourceWrapper <UserResponse> response = await base.RequestAsync <ResourceWrapper <UserResponse> >(
                method : HttpMethod.Get,
                resource : "user",
                query : query
                );

            return(response.Records);
        }
Exemple #5
0
        public async Task <ResourceWrapper> UpdateSearchParameterIndicesAsync(ResourceWrapper resource, WeakETag weakETag, CancellationToken cancellationToken)
        {
            int?eTag = weakETag == null
                ? null
                : (int.TryParse(weakETag.VersionId, out var parsedETag) ? parsedETag : -1); // Set the etag to a sentinel value to enable expected failure paths when updating with both existing and nonexistent resources.

            using (SqlConnectionWrapper sqlConnectionWrapper = await _sqlConnectionWrapperFactory.ObtainSqlConnectionWrapperAsync(cancellationToken, true))
                using (SqlCommandWrapper sqlCommandWrapper = sqlConnectionWrapper.CreateSqlCommand())
                {
                    if (_schemaInformation.Current >= SchemaVersionConstants.AddMinMaxForDateAndStringSearchParamVersion)
                    {
                        VLatest.ReindexResource.PopulateCommand(
                            sqlCommandWrapper,
                            resourceTypeId: _model.GetResourceTypeId(resource.ResourceTypeName),
                            resourceId: resource.ResourceId,
                            eTag,
                            searchParamHash: resource.SearchParameterHash,
                            tableValuedParameters: _reindexResourceTvpGeneratorVLatest.Generate(new List <ResourceWrapper> {
                            resource
                        }));
                    }
                    else
                    {
                        V17.ReindexResource.PopulateCommand(
                            sqlCommandWrapper,
                            resourceTypeId: _model.GetResourceTypeId(resource.ResourceTypeName),
                            resourceId: resource.ResourceId,
                            eTag,
                            searchParamHash: resource.SearchParameterHash,
                            tableValuedParameters: _reindexResourceTvpGeneratorV17.Generate(new List <ResourceWrapper> {
                            resource
                        }));
                    }

                    try
                    {
                        await sqlCommandWrapper.ExecuteScalarAsync(cancellationToken);

                        return(resource);
                    }
                    catch (SqlException e)
                    {
                        switch (e.Number)
                        {
                        case SqlErrorCodes.PreconditionFailed:
                            _logger.LogError(string.Format(Core.Resources.ResourceVersionConflict, weakETag));
                            throw new PreconditionFailedException(string.Format(Core.Resources.ResourceVersionConflict, weakETag));

                        default:
                            _logger.LogError(e, "Error from SQL database on reindex.");
                            throw;
                        }
                    }
                }
        }
 private async Tasks.Task <ResourceWrapper> UploadResource(ResourceWrapper resource, FhirClientWrapper client)
 {
     if (string.IsNullOrWhiteSpace(resource.Id))
     {
         return(await client.CreateAsync(resource));
     }
     else
     {
         return(await client.UpdateAsync(resource));
     }
 }
        public async Task GivenAResourceWithIncorrectId_WhenUpsertingConditionallyWithOneMatch_TheServerShouldFail()
        {
            ResourceWrapper mockResourceWrapper = CreateMockResourceWrapper(Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()), false);

            ConditionalUpsertResourceRequest message = SetupConditionalUpdate(
                SaveOutcomeType.Updated,
                Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()),
                mockResourceWrapper);

            await Assert.ThrowsAsync <BadRequestException>(() => _mediator.Send <UpsertResourceResponse>(message));
        }
Exemple #8
0
        public ResourceWrapper GetUsers(string roleName, bool isDbRole)
        {
            ResourceWrapper wrapper = new ResourceWrapper();

            IEnumerable <UserRoleDto> users = _Repository.GetUsers(roleName, isDbRole);

            wrapper.TotalRecords = users.Count();
            wrapper.Records      = users;

            return(wrapper);
        }
        static void Main(string[] args)
        {
            ResourceWrapper resource = new ResourceWrapper();
            GC.Collect();

            Console.WriteLine("\nНачало работы.");
            Console.WriteLine("Нажмите клавишу для завершения работы.");
            Console.WriteLine("и вызова Finalize() сборщика мусора.");

            Console.ReadKey();
        }
Exemple #10
0
        public ResourceElement Patch(ResourceWrapper resourceToPatch, JsonPatchDocument patchDocument, WeakETag weakETag)
        {
            EnsureArg.IsNotNull(resourceToPatch, nameof(resourceToPatch));

            Validate(resourceToPatch, weakETag, patchDocument);

            var node = (FhirJsonNode)FhirJsonNode.Parse(resourceToPatch.RawResource.Data);

            // Capture the state of properties that are immutable
            ITypedElement resource = node.ToTypedElement(_modelInfoProvider.StructureDefinitionSummaryProvider);

            (string path, object result)[] preState = _immutableProperties.Select(x => (path: x, result: resource.Scalar(x))).ToArray();
Exemple #11
0
        /// <inheritdoc />
        public byte[] Serialize(ResourceWrapper resourceWrapper)
        {
            EnsureArg.IsNotNull(resourceWrapper, nameof(resourceWrapper));

            ResourceElement resource = _resourceDeserializer.DeserializeRaw(resourceWrapper.RawResource, resourceWrapper.Version, resourceWrapper.LastModified);

            string resourceData = _fhirJsonSerializer.SerializeToString(resource.ToPoco <Resource>());

            byte[] bytesToWrite = Encoding.UTF8.GetBytes($"{resourceData}\n");

            return(bytesToWrite);
        }
        public Task <UpsertOutcome> UpsertAsync(
            ResourceWrapper resource,
            WeakETag weakETag,
            bool allowCreate,
            bool keepHistory,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            EnsureArg.IsNotNull(resource, nameof(resource));

            string lookupKey = GetKey(resource.ResourceTypeName, resource.ResourceId);

            var outcome = SaveOutcomeType.Updated;

            if (!List.ContainsKey(lookupKey) && !allowCreate && weakETag == null)
            {
                throw new MethodNotAllowedException(Core.Resources.ResourceCreationNotAllowed);
            }
            else if (!List.ContainsKey(lookupKey) && weakETag == null)
            {
                outcome         = SaveOutcomeType.Created;
                List[lookupKey] = new List <ResourceWrapper>();
            }
            else if (List.ContainsKey(lookupKey) && weakETag != null &&
                     List[lookupKey].OrderByDescending(x => x.LastModified).First().Version != weakETag.VersionId)
            {
                throw new ResourceConflictException(weakETag);
            }
            else if (!List.ContainsKey(lookupKey) && weakETag != null)
            {
                throw new ResourceConflictException(weakETag);
            }

            if (!keepHistory && List[lookupKey].Any())
            {
                List[lookupKey].RemoveAt(List[lookupKey].Count - 1);
            }

            var upsertedVersion = new ResourceWrapper(
                resource.ResourceId,
                Guid.NewGuid().ToString(),
                resource.ResourceTypeName,
                resource.RawResource,
                resource.Request,
                Clock.UtcNow,
                resource.IsDeleted,
                resource.SearchIndices,
                resource.CompartmentIndices,
                resource.LastModifiedClaims);

            List[lookupKey].Add(upsertedVersion);

            return(Task.FromResult(new UpsertOutcome(upsertedVersion, outcome)));
        }
Exemple #13
0
        public void GivenARawResource_WhenDeserializingFromJson_ThenTheObjectIsReturned()
        {
            var observation = Samples.GetDefaultObservation()
                              .UpdateId("id1");

            var wrapper = new ResourceWrapper(observation, _rawResourceFactory.Create(observation), new ResourceRequest(HttpMethod.Post, "http://fhir"), false, null, null, null);

            var newObject = Deserializers.ResourceDeserializer.Deserialize(wrapper);

            Assert.Equal(observation.Id, newObject.Id);
            Assert.Equal(observation.VersionId, newObject.VersionId);
        }
        public async Task GivenAResource_WhenCreatingConditionallyWithMultipleMatches_TheServerShouldFail()
        {
            ResourceWrapper mockResourceWrapper1 = CreateMockResourceWrapper(Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()), false);
            ResourceWrapper mockResourceWrapper2 = CreateMockResourceWrapper(Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()), false);

            ConditionalCreateResourceRequest message = SetupConditionalCreate(
                Samples.GetDefaultObservation(),
                mockResourceWrapper1,
                mockResourceWrapper2);

            await Assert.ThrowsAsync <PreconditionFailedException>(() => _mediator.Send <UpsertResourceResponse>(message));
        }
Exemple #15
0
        public void GivenARawResourceInXmlFormat_WhenSerialized_ThenCorrectByteArrayShouldBeProduced()
        {
            var rawResource = new RawResource(
                new FhirXmlSerializer().SerializeToString(_resource),
                FhirResourceFormat.Xml);

            ResourceWrapper resourceWrapper = CreateResourceWrapper(rawResource);

            byte[] actualBytes = _serializer.Serialize(resourceWrapper);

            Assert.Equal(_expectedBytes, actualBytes);
        }
        private async Task ProcessSearchResultsAsync(IEnumerable <SearchResultEntry> searchResults, string partId, CancellationToken cancellationToken)
        {
            foreach (SearchResultEntry result in searchResults)
            {
                ResourceWrapper resourceWrapper = result.Resource;

                string resourceType = resourceWrapper.ResourceTypeName;

                // Check whether we already have an existing file for the current resource type.
                if (!_resourceTypeToFileInfoMapping.TryGetValue(resourceType, out ExportFileInfo exportFileInfo))
                {
                    // Check whether we have seen this file previously (in situations where we are resuming an export)
                    if (_exportJobRecord.Output.TryGetValue(resourceType, out exportFileInfo))
                    {
                        // A file already exists for this resource type. Let us open the file on the client.
                        await _exportDestinationClient.OpenFileAsync(exportFileInfo.FileUri, cancellationToken);
                    }
                    else
                    {
                        // File does not exist. Create it.
                        string fileName;
                        if (_exportJobRecord.StorageAccountContainerName.Equals(_exportJobRecord.Id, StringComparison.OrdinalIgnoreCase))
                        {
                            fileName = $"{resourceType}.ndjson";
                        }
                        else
                        {
                            string dateTime = _exportJobRecord.QueuedTime.UtcDateTime.ToString("s")
                                              .Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase)
                                              .Replace(":", string.Empty, StringComparison.OrdinalIgnoreCase);
                            fileName = $"{dateTime}-{_exportJobRecord.Id}/{resourceType}.ndjson";
                        }

                        Uri fileUri = await _exportDestinationClient.CreateFileAsync(fileName, cancellationToken);

                        exportFileInfo = new ExportFileInfo(resourceType, fileUri, sequence: 0);

                        // Since we created a new file the JobRecord Output also needs to know about it.
                        _exportJobRecord.Output.TryAdd(resourceType, exportFileInfo);
                    }

                    _resourceTypeToFileInfoMapping.Add(resourceType, exportFileInfo);
                }

                // Serialize into NDJson and write to the file.
                byte[] bytesToWrite = _resourceToByteArraySerializer.Serialize(resourceWrapper);

                await _exportDestinationClient.WriteFilePartAsync(exportFileInfo.FileUri, partId, bytesToWrite, cancellationToken);

                // Increment the file information.
                exportFileInfo.IncrementCount(bytesToWrite.Length);
            }
        }
Exemple #17
0
        private SearchResultEntry CreateSearchResultEntry(string jsonName, IReadOnlyCollection <SearchIndexEntry> searchIndices)
        {
            var json               = Samples.GetJson(jsonName);
            var rawResource        = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);
            var resourceRequest    = Substitute.For <ResourceRequest>();
            var compartmentIndices = Substitute.For <CompartmentIndices>();
            var resourceElement    = _resourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow);
            var wrapper            = new ResourceWrapper(resourceElement, rawResource, resourceRequest, false, searchIndices, compartmentIndices, new List <KeyValuePair <string, string> >(), "hash");
            var entry              = new SearchResultEntry(wrapper);

            return(entry);
        }
Exemple #18
0
        public void GivenASearchResult_WhenCreateSearchBundle_ThenCorrectBundleShouldBeReturned()
        {
            _urlResolver.ResolveResourceUrl(Arg.Any <ResourceElement>()).Returns(x => new Uri(string.Format(_resourceUrlFormat, x.ArgAt <ResourceElement>(0).Id)));
            _urlResolver.ResolveRouteUrl(_unsupportedSearchParameters).Returns(_selfUrl);

            ResourceElement observation1 = Samples.GetDefaultObservation().UpdateId("123");
            ResourceElement observation2 = Samples.GetDefaultObservation().UpdateId("abc");

            var resourceWrappers = new ResourceWrapper[]
            {
                CreateResourceWrapper(observation1),
                CreateResourceWrapper(observation2),
            };

            var searchResult = new SearchResult(resourceWrappers, _unsupportedSearchParameters, continuationToken: null);

            ResourceElement actual = null;

            using (Mock.Property(() => Clock.UtcNowFunc, () => _dateTime))
            {
                actual = _bundleFactory.CreateSearchBundle(searchResult);
            }

            // Since there is no continuation token, there should not be next link.
            Assert.Null(actual.Scalar <string>("Bundle.link.where(relation='next').url"));
            Assert.Collection(
                actual.ToPoco <Bundle>().Entry,
                e => ValidateEntry(observation1.ToPoco <Observation>(), e),
                e => ValidateEntry(observation2.ToPoco <Observation>(), e));

            ResourceWrapper CreateResourceWrapper(ResourceElement resourceElement)
            {
                return(new ResourceWrapper(
                           resourceElement,
                           new RawResource(_fhirJsonSerializer.SerializeToString(resourceElement.ToPoco <Observation>()), FhirResourceFormat.Json),
                           null,
                           false,
                           null,
                           null,
                           null));
            }

            void ValidateEntry(Observation expected, Bundle.EntryComponent actualEntry)
            {
                Assert.NotNull(actualEntry);
                Assert.NotNull(actualEntry.Resource);
                Assert.Equal(expected.Id, actualEntry.Resource.Id);
                Assert.Equal(string.Format(_resourceUrlFormat, expected.Id), actualEntry.FullUrl);
                Assert.NotNull(actualEntry.Search);
                Assert.Equal(Bundle.SearchEntryMode.Match, actualEntry.Search.Mode);
            }
        }
        public void GivenARawResourceFromFhirNet1_WhenDeserializingFromJson_ThenTheObjectIsReturned()
        {
            var oldValidResource = @"{
  ""resourceType"": ""Patient"",
  ""birthDate"": ""1991-02-03T11:22:33Z""
    }";

            var observation = Samples.GetDefaultPatient();

            var wrapper = new ResourceWrapper(observation, new RawResource(oldValidResource, FhirResourceFormat.Json, false), new ResourceRequest(HttpMethod.Post, "http://fhir"), false, null, null, null);

            var newObject = Deserializers.ResourceDeserializer.Deserialize(wrapper);
        }
        public void WriteComplexColParameter_WithEmpty()
        {
            ResourceWrapper resource = new ResourceWrapper()
            {
                Resource = new ODataResource()
                {
                    TypeName = "NS.OtherInfo"
                }
            };

            WriteParameter(resource, true, (actual) => Assert.Equal("{\"@odata.type\":\"#NS.OtherInfo\"}", actual));
            WriteParameter(resource, false, (actual) => Assert.Equal("{\"@odata.type\":\"#NS.OtherInfo\"}", actual));
        }
Exemple #21
0
        public void GivenARawResourceInXmlFormat_WhenSerialized_ThenCorrectByteArrayShouldBeProduced()
        {
            var rawResource = new RawResource(
                new FhirXmlSerializer().SerializeToString(_resource),
                FhirResourceFormat.Xml);

            ResourceWrapper resourceWrapper = CreateResourceWrapper(rawResource);
            ResourceElement element         = _resourceDeserializaer.DeserializeRaw(resourceWrapper.RawResource, resourceWrapper.Version, resourceWrapper.LastModified);

            byte[] actualBytes = _serializer.Serialize(element);

            Assert.Equal(_expectedBytes, actualBytes);
        }
        public void ResourceRepoFetchesAudio()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Stream>(b => new MemoryStream(b), s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var sound = repo.Fetch("MiscAngelic");

                Assert.IsNotNull(sound);
            }
        }
        public RawResourceElement(ResourceWrapper wrapper)
        {
            EnsureArg.IsNotNull(wrapper, nameof(wrapper));
            EnsureArg.IsNotNull(wrapper.RawResource, nameof(wrapper.RawResource));

            RawResource = wrapper.RawResource;

            Format       = wrapper.RawResource.Format;
            Id           = wrapper.ResourceId;
            VersionId    = wrapper.Version;
            InstanceType = wrapper.ResourceTypeName;
            LastUpdated  = wrapper.LastModified;
        }
        public ResourceWrapper GetActivities([FromUri] ProcInstOverviewQueryParam param)
        {
            //ISmartObjectFactory soFactory = new SmartObjectFactory();
            //ActivityInstance actInst = soFactory.GetActivityInstance();
            //actInst.ProcessInstanceID = param.procInstId;
            //DataTable result = actInst.ActivityInstanceDetail();
            //var records = result.ToList<ActivityInstanceDto>();
            ResourceWrapper resource = new ResourceWrapper();

            //resource.Records = records;
            //resource.TotalRecords = records.Count;
            return(resource);
        }
        public void ResourceRepoFetches()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Bitmap>(b => ic.ConvertFrom(b) as Bitmap, s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var luna = repo.Fetch("Luna_DIFF");

                Assert.IsNotNull(luna);
            }
        }
Exemple #26
0
        public async Task <UpsertResourceResponse> Handle(ConditionalUpsertResourceRequest message, CancellationToken cancellationToken = default)
        {
            EnsureArg.IsNotNull(message, nameof(message));

            if (await AuthorizationService.CheckAccess(DataActions.Read | DataActions.Write) != (DataActions.Read | DataActions.Write))
            {
                throw new UnauthorizedFhirActionException();
            }

            SearchResultEntry[] matchedResults = await Search(message.Resource.InstanceType, message.ConditionalParameters, cancellationToken);

            int count = matchedResults.Length;

            if (count == 0)
            {
                if (string.IsNullOrEmpty(message.Resource.Id))
                {
                    // No matches, no id provided: The server creates the resource
                    // TODO: There is a potential contention issue here in that this could create another new resource with a different id
                    return(await _mediator.Send <UpsertResourceResponse>(new CreateResourceRequest(message.Resource), cancellationToken));
                }
                else
                {
                    // No matches, id provided: The server treats the interaction as an Update as Create interaction (or rejects it, if it does not support Update as Create)
                    // TODO: There is a potential contention issue here that this could replace an existing resource
                    return(await _mediator.Send <UpsertResourceResponse>(new UpsertResourceRequest(message.Resource), cancellationToken));
                }
            }
            else if (count == 1)
            {
                ResourceWrapper resourceWrapper = matchedResults.First().Resource;
                Resource        resource        = message.Resource.ToPoco();
                WeakETag        version         = WeakETag.FromVersionId(resourceWrapper.Version);

                // One Match, no resource id provided OR (resource id provided and it matches the found resource): The server performs the update against the matching resource
                if (string.IsNullOrEmpty(resource.Id) || string.Equals(resource.Id, resourceWrapper.ResourceId, StringComparison.Ordinal))
                {
                    resource.Id = resourceWrapper.ResourceId;
                    return(await _mediator.Send <UpsertResourceResponse>(new UpsertResourceRequest(resource.ToResourceElement(), version), cancellationToken));
                }
                else
                {
                    throw new BadRequestException(string.Format(Core.Resources.ConditionalUpdateMismatchedIds, resourceWrapper.ResourceId, resource.Id));
                }
            }
            else
            {
                // Multiple matches: The server returns a 412 Precondition Failed error indicating the client's criteria were not selective enough
                throw new PreconditionFailedException(Core.Resources.ConditionalOperationNotSelectiveEnough);
            }
        }
Exemple #27
0
        public async Task <IEnumerable <string> > GetEventsAsync()
        {
            ResourceWrapper <string> response = await base.RequestAsync <ResourceWrapper <string> >(
                method : HttpMethod.Get,
                resource : "event",
                query : new SqlQuery {
                Fields = null, CustomParameters = new Dictionary <string, object> {
                    { "as_list", true }
                }
            }
                );

            return(response.Records);
        }
Exemple #28
0
        public void ReferenceInterferenceOnSave()
        {
            // Arrange
            var instance = new InterferenceResource()
            {
                Id = 1
            };

            ResourceReferenceTools.InitializeCollections(instance);
            // Prepare reference objects
            var derived = new DerivedResource {
                Id = 2, Name = "Ref1"
            };
            var other = new OtherResource {
                Id = 3, Name = "Ref2"
            };
            var different = new DifferentResource {
                Id = 4, Name = "Different"
            };

            // Fill graph
            _graph[1] = new ResourceWrapper(instance);
            _graph[2] = new ResourceWrapper(derived);
            _graph[3] = new ResourceWrapper(other);
            _graph[4] = new ResourceWrapper(different);
            // Set references
            instance.Derived = derived;
            instance.Others.Add(other);
            instance.Different = different;

            // Setup uow and repo to simulate the current database
            var relations = new List <ResourceRelation>
            {
                // Current exchangable parts
                Relation(2, 1, ResourceRelationType.CurrentExchangablePart),
                Relation(3, 1, ResourceRelationType.CurrentExchangablePart),
                Relation(4, 1, ResourceRelationType.CurrentExchangablePart),
            };
            var mocks = SetupDbMocks(relations);

            // Act
            _linker.SaveReferences(mocks.Item1.Object, instance, new ResourceEntity {
                Id = 1
            });

            // Assert
            Assert.DoesNotThrow(() => mocks.Item2.Verify(repo => repo.Remove(It.Is <ResourceRelation>(removed => removed.SourceId == 1 && removed.TargetId == 2)), Times.Never), "Linker did remove relation 1-2");
            Assert.DoesNotThrow(() => mocks.Item2.Verify(repo => repo.Remove(It.Is <ResourceRelation>(removed => removed.SourceId == 1 && removed.TargetId == 3)), Times.Never), "Linker did remove relation 1-3");
            Assert.DoesNotThrow(() => mocks.Item2.Verify(repo => repo.Remove(It.Is <ResourceRelation>(removed => removed.SourceId == 1 && removed.TargetId == 3)), Times.Never), "Linker did remove relation 1-4");
        }
        public async Task <IEnumerable <StorageResource> > GetResourcesAsync(ListingFlags flags)
        {
            SqlQuery query = new SqlQuery();

            query.CustomParameters = AddListingParameters(query.CustomParameters, flags);

            ResourceWrapper <StorageResource> response = await base.RequestAsync <ResourceWrapper <StorageResource> >(
                method : HttpMethod.Get,
                resource : string.Empty,
                query : query
                );

            return(response.Records);
        }
        public void GivenABadResource_WhenDeserializingFromJson_ThenExceptionThrown()
        {
            var oldValidResource = @"{
  ""resourceType"": ""Patient"",
  ""birthDate"": ""1991-02-03"",
  ""mutlipleBirthBoolean"":""cat""
    }";

            var observation = Samples.GetDefaultPatient();

            var wrapper = new ResourceWrapper(observation, new RawResource(oldValidResource, FhirResourceFormat.Json, false), new ResourceRequest(HttpMethod.Post, "http://fhir"), false, null, null, null);

            Assert.Throws <StructuralTypeException>(() => Deserializers.ResourceDeserializer.Deserialize(wrapper));
        }
        public async Task <DeleteResourceResponse> Handle(DeleteResourceRequest message, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(message, nameof(message));

            DataActions requiredDataAction = message.HardDelete ? DataActions.Delete | DataActions.HardDelete : DataActions.Delete;

            if (await AuthorizationService.CheckAccess(requiredDataAction) != requiredDataAction)
            {
                throw new UnauthorizedFhirActionException();
            }

            var key = message.ResourceKey;

            if (!string.IsNullOrEmpty(key.VersionId))
            {
                throw new MethodNotAllowedException(Core.Resources.DeleteVersionNotAllowed);
            }

            string version = null;

            if (message.HardDelete)
            {
                await FhirDataStore.HardDeleteAsync(key, cancellationToken);
            }
            else
            {
                var emptyInstance = (Resource)Activator.CreateInstance(ModelInfo.GetTypeForFhirType(message.ResourceKey.ResourceType));
                emptyInstance.Id = message.ResourceKey.Id;

                ResourceWrapper deletedWrapper = CreateResourceWrapper(emptyInstance, deleted: true, keepMeta: false);

                bool keepHistory = await ConformanceProvider.Value.CanKeepHistory(key.ResourceType, cancellationToken);

                UpsertOutcome result = await FhirDataStore.UpsertAsync(
                    deletedWrapper,
                    weakETag : null,
                    allowCreate : true,
                    keepHistory : keepHistory,
                    cancellationToken : cancellationToken);

                version = result?.Wrapper.Version;
            }

            if (string.IsNullOrWhiteSpace(version))
            {
                return(new DeleteResourceResponse(new ResourceKey(key.ResourceType, key.Id)));
            }

            return(new DeleteResourceResponse(new ResourceKey(key.ResourceType, key.Id, version), WeakETag.FromVersionId(version)));
        }
        public async Task <DeleteResourceResponse> Handle(DeleteResourceRequest message, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(message, nameof(message));

            var key = message.ResourceKey;

            if (!string.IsNullOrEmpty(key.VersionId))
            {
                throw new MethodNotAllowedException(Core.Resources.DeleteVersionNotAllowed);
            }

            string version = null;

            if (message.HardDelete)
            {
                await FhirDataStore.HardDeleteAsync(key, cancellationToken);
            }
            else
            {
                ResourceWrapper existing = await FhirDataStore.GetAsync(key, cancellationToken);

                version = existing?.Version;

                if (existing?.IsDeleted == false)
                {
                    var emptyInstance = (Resource)Activator.CreateInstance(ModelInfo.GetTypeForFhirType(existing.ResourceTypeName));
                    emptyInstance.Id = existing.ResourceId;

                    ResourceWrapper deletedWrapper = CreateResourceWrapper(emptyInstance, deleted: true);

                    bool keepHistory = await ConformanceProvider.Value.CanKeepHistory(key.ResourceType, cancellationToken);

                    UpsertOutcome result = await FhirDataStore.UpsertAsync(
                        deletedWrapper,
                        WeakETag.FromVersionId(existing.Version),
                        allowCreate : true,
                        keepHistory : keepHistory,
                        cancellationToken : cancellationToken);

                    version = result.Wrapper.Version;
                }
            }

            if (string.IsNullOrWhiteSpace(version))
            {
                return(new DeleteResourceResponse(new ResourceKey(key.ResourceType, key.Id)));
            }

            return(new DeleteResourceResponse(new ResourceKey(key.ResourceType, key.Id, version), WeakETag.FromVersionId(version)));
        }
Exemple #33
0
        public async Task GivenAnUpdatedResource_WhenUpdateSearchIndexForResourceAsync_ThenResourceGetsUpdated()
        {
            ResourceElement patientResource = Samples.GetJsonSample("Patient");
            SaveOutcome     upsertResult    = await Mediator.UpsertResourceAsync(patientResource);

            (FhirCosmosResourceWrapper original, ResourceWrapper updated) = await CreateUpdatedWrapperFromExistingResource(upsertResult);

            ResourceWrapper replaceResult = await _dataStore.UpdateSearchIndexForResourceAsync(updated, original.ETag, CancellationToken.None);

            Assert.Equal(original.ResourceId, replaceResult.ResourceId);
            Assert.Equal(original.Version, replaceResult.Version);
            Assert.Equal(original.ResourceTypeName, replaceResult.ResourceTypeName);
            Assert.Equal(original.LastModified, replaceResult.LastModified);
        }
        public void ResourceRepoEnumerates()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Bitmap>(b => ic.ConvertFrom(b) as Bitmap, s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var bitmaps = repo.Where(s => s.Value != null).Select(s => s.Value).OfType<Bitmap>();

                Assert.AreEqual(4, bitmaps.Count());

                var en = repo.GetEnumerator();

                if (en.MoveNext())
                {
                    Assert.IsNotNull(en.Current);
                    en.Reset();
                }
            }
        }
        public void ResourceRepoFetchesString()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<string>(b => new ASCIIEncoding().GetString(b), s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var value = repo.Fetch("TestString");

                Assert.IsNotNull(value);

                var value2 = repo.GetContents("TestString");

                Assert.AreEqual(value, value2);

                Assert.AreEqual(repo.CastContentsAs<string>("TestString"), value2);

                repo.Clear();
            }
        }
Exemple #36
0
        public static void Main(string[] args)
        {
            // choose a skin or site "look" to present
            string skin = "blue";

            // allow overrides for language and skin from arguments on command line
            string language = null;
            if ( args.Length > 0 )
            {
                language = args[0];
            }
            if ( args.Length > 1)
            {
                if ( "blue".Equals(args[1]) || "red".Equals(args[1]) )
                    skin = args[1];
            }

            TryToSetRequestedLocale(language);

            // load strings from a properties files like en.strings
            ResourceManager resMgr = new ResourceManager("ST.Examples.i18n.Content.Strings", typeof(ResourceWrapper).Assembly);
            ResourceWrapper strings = new ResourceWrapper(resMgr);

            // get a template group rooted at appropriate skin
            string absoluteSkinRootDirectoryName = Path.Combine(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName, skin);
            StringTemplateGroup templates = new StringTemplateGroup("test", absoluteSkinRootDirectoryName);

            // generate some pages; every page gets strings table to pull strings from
            StringTemplate page1ST = templates.GetInstanceOf("page1");
            page1ST.SetAttribute("strings", strings);
            StringTemplate page2ST = templates.GetInstanceOf("page2");
            page2ST.SetAttribute("strings", strings);

            // render to text
            Console.Out.WriteLine(page1ST);
            Console.Out.WriteLine(page2ST);
        }
 public Controller3DBalder()
 {
     resourceWrapper = new ResourceWrapper();
 }
        public void ResourceRepoLoads()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Bitmap>(b => ic.ConvertFrom(b) as Bitmap, s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);
            }
        }
        public void ResourceRepoFetchesWavAudio()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Stream>(b => new MemoryStream(b), s => s, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var sound = repo.Fetch("Speech_Misrecognition");

                Assert.IsNotNull(sound);

                sound = repo.GetFileStream("Speech_Misrecognition");

                Assert.IsNotNull(sound);
            }
        }