Beispiel #1
0
        private void WriteResourceToOutputDirectory(ResourceReference<XmlTestElement> resourceRef, Type testClass, String outputPath)
        {
            string path = resourceRef.getResourcePath();
            Stream resource = new ResourceFinder(testClass).GetResource(path);
            if (resource == null)
            {
                resource = new ResourceFinder(typeof(MarkupWriter)).GetResource(path);
                if (resource == null)
                {
                    StringBuilder sb = new StringBuilder();
                    string[] resourceNames = typeof(MarkupWriter).Assembly.GetManifestResourceNames();
                    sb.AppendLine("resource count: " + resourceNames.Length);
                    foreach (string s in resourceNames) {
                        sb.AppendLine("resource: " + s);
                    }
                    throw new XcordionBug(sb.ToString() + "Cannot find resource: " + path);
                }
            }

            using (resource)
            {
                path = path.Replace('/', Path.DirectorySeparatorChar);
                while (path[0] == Path.DirectorySeparatorChar)
                {
                    path = path.Substring(1);
                }

                FileInfo outputFile = new FileInfo(outputDirectory.FullName + Path.DirectorySeparatorChar + path);
                if (!outputFile.Directory.Exists)
                {
                    Mkdirs(outputFile.Directory);
                }

                resourceRef.setResourceReferenceUri(FileUtils.relativePath(outputPath, path, false, Path.DirectorySeparatorChar));

                if (outputFile.Exists && outputFile.LastWriteTime < DateTime.Now.AddSeconds(5))
                {
                    return;
                }

                byte[] bytes = new byte[resource.Length];
                resource.Read(bytes, 0, bytes.Length);
                File.WriteAllBytes(outputFile.FullName, bytes);
            }
        }
Beispiel #2
0
        public string Cast(ResourceReference reference)
        {
            if (reference == null)
            {
                return(null);
            }
            if (reference.Url == null)
            {
                return(null);
            }
            string uri = reference.Url.ToString();

            string[] s = uri.ToString().Split('#');
            if (s.Count() == 2)
            {
                string system = s[0];
                string code   = s[1];
                if (string.IsNullOrEmpty(system))
                {
                    return(container_id + "#" + code);
                }
            }
            return(uri.ToString());
        }
Beispiel #3
0
        public void GetAbsoluteUri()
        {
            var r = new ResourceReference {
                Reference = "Patient/4"
            };

            Assert.AreEqual("http://someserver.org/fhir/Patient/4", r.GetAbsoluteUriForReference("http://someserver.org/fhir/Observation/5").ToString());

            r.Reference = "http://otherserver.org/fhir/Patient/4";
            Assert.AreEqual("http://otherserver.org/fhir/Patient/4", r.GetAbsoluteUriForReference("http://someserver.org/fhir/Observation/5").ToString());
            Assert.AreEqual("http://otherserver.org/fhir/Patient/4", r.GetAbsoluteUriForReference("urn:uuid:d0dd51d3-3ab2-4c84-b697-a630c3e40e7a").ToString());

            r.Reference = "urn:uuid:d0dd51d3-3ab2-4c84-b697-a630c3e40e7a";
            Assert.AreEqual("urn:uuid:d0dd51d3-3ab2-4c84-b697-a630c3e40e7a", r.GetAbsoluteUriForReference("http://someserver.org/fhir/Observation/5").ToString());

            try
            {
                r.Reference = "Patient/4";
                var dummy = r.GetAbsoluteUriForReference("urn:uuid:d0dd51d3-3ab2-4c84-b697-a630c3e40e7a");
                Assert.Fail();
            }
            catch
            { }
        }
Beispiel #4
0
 /**
  * Build out this source description with a descriptor ref.
  *
  * @param descriptorRef The descriptor ref.
  * @return this.
  */
 public SourceDescription SetDescriptorRef(ResourceReference descriptorRef)
 {
     DescriptorRef = descriptorRef;
     return(this);
 }
        public static CapabilityStatement AddSingleResourceComponent(this CapabilityStatement conformance, String resourcetype, Boolean readhistory, Boolean updatecreate, CapabilityStatement.ResourceVersionPolicy versioning, ResourceReference profile = null)
        {
            var resource = new CapabilityStatement.ResourceComponent();

            resource.Type         = Hacky.GetResourceTypeForResourceName(resourcetype);
            resource.Profile      = profile;
            resource.ReadHistory  = readhistory;
            resource.UpdateCreate = updatecreate;
            resource.Versioning   = versioning;
            conformance.Server().Resource.Add(resource);
            return(conformance);
        }
Beispiel #6
0
 ///<summary>
 /// Set a live varible value
 ///</summary>
 ///<param name="variable">The variable to write</param>
 ///<param name="value">The value to set the variable to</param>
 public void SetValue(ResourceReference variable, object value)
 {
     ProvideValues.SetValue(DeployPath.GetDeployPath(variable), value);
 }
Beispiel #7
0
 /**
  * Build out this source description with an analyis.
  * @param analysis The analysis.
  * @return this.
  */
 public SourceDescription AddAnalysis(ResourceReference analysis)
 {
     Analysis = analysis;
     return(this);
 }
        public void InjectDds(TagSerializer serializer, TagDeserializer deserializer, Bitmap bitmap, int imageIndex, Stream ddsStream)
        {
            var resource = bitmap.Resources[imageIndex].Resource;
            var newResource = (resource == null);
            ResourceSerializationContext resourceContext;
            BitmapTextureResourceDefinition definition;
            if (newResource)
            {
                // Create a new resource reference
                resource = new ResourceReference
                {
                    DefinitionFixups = new List<ResourceDefinitionFixup>(),
                    D3DObjectFixups = new List<D3DObjectFixup>(),
                    Type = 1, // TODO: Map out this type enum instead of using numbers
                    Unknown68 = 1
                };
                bitmap.Resources[imageIndex].Resource = resource;
                resourceContext = new ResourceSerializationContext(resource);
                definition = new BitmapTextureResourceDefinition
                {
                    Texture = new D3DPointer<BitmapTextureResourceDefinition.BitmapDefinition>
                    {
                        Definition = new BitmapTextureResourceDefinition.BitmapDefinition()
                    }
                };
            }
            else
            {
                // Deserialize the old definition
                resourceContext = new ResourceSerializationContext(resource);
                definition = deserializer.Deserialize<BitmapTextureResourceDefinition>(resourceContext);
            }
            if (definition.Texture == null || definition.Texture.Definition == null)
                throw new ArgumentException("Invalid bitmap definition");
            var texture = definition.Texture.Definition;
            var imageData = bitmap.Images[imageIndex];

            // Read the DDS header and modify the definition to match
            var dds = DdsHeader.Read(ddsStream);
            var dataSize = (int)(ddsStream.Length - ddsStream.Position);
            texture.Data = new ResourceDataReference(dataSize, new ResourceAddress(ResourceAddressType.Resource, 0));
            texture.Width = (short)dds.Width;
            texture.Height = (short)dds.Height;
            texture.Depth = (sbyte)Math.Max(1, dds.Depth);
            texture.Levels = (sbyte)Math.Max(1, dds.MipMapCount);
            texture.Type = BitmapDdsFormatDetection.DetectType(dds);
            texture.D3DFormatUnused = (int)((dds.D3D10Format != DxgiFormat.Bc5UNorm) ? dds.FourCc : DdsFourCc.FromString("ATI2"));
            texture.Format = BitmapDdsFormatDetection.DetectFormat(dds);

            // Set flags based on the format
            switch (texture.Format)
            {
                case BitmapFormat.Dxt1:
                case BitmapFormat.Dxt3:
                case BitmapFormat.Dxt5:
                case BitmapFormat.Dxn:
                    texture.Flags = BitmapFlags.Compressed;
                    break;
                default:
                    texture.Flags = BitmapFlags.None;
                    break;
            }
            if ((texture.Width & (texture.Width - 1)) == 0 && (texture.Height & (texture.Height - 1)) == 0)
                texture.Flags |= BitmapFlags.PowerOfTwoDimensions;

            // If creating a new image, then add a new resource, otherwise replace the existing one
            if (newResource)
                _resourceManager.Add(resource, ResourceLocation.Textures, ddsStream);
            else
                _resourceManager.Replace(resource, ddsStream);

            // Serialize the new resource definition
            serializer.Serialize(resourceContext, definition);

            // Modify the image data in the bitmap tag to match the definition
            imageData.Width = texture.Width;
            imageData.Height = texture.Height;
            imageData.Depth = texture.Depth;
            imageData.Type = texture.Type;
            imageData.Format = texture.Format;
            imageData.Flags = texture.Flags;
            imageData.MipmapCount = (sbyte)(texture.Levels - 1);
            imageData.DataOffset = texture.Data.Address.Offset;
            imageData.DataSize = texture.Data.Size;
            imageData.Unknown15 = texture.Unknown35;
        }
Beispiel #9
0
 public string GetSubjectReferenceId(ResourceReference reference)
 {
     return(_validationHelper.GetResourceReferenceId(reference, FhirConstants.SystemPDS));
 }
Beispiel #10
0
 private static Boolean isTheListSubjectValid(ResourceReference subject)
 {
     return(!(null == subject.Reference && null == subject.Identifier));
 }
 internal IResource ResolveResource(
   ResourceReference resourceReference,
   ResourceReference originalReference
 ) {
   ManifestResourceRow resRow = this.PEFileReader.ManifestResourceTable[resourceReference.ResourceRowId];
   uint tokenType = resRow.Implementation & TokenTypeIds.TokenTypeMask;
   if (tokenType == TokenTypeIds.AssemblyRef) {
     AssemblyReference/*?*/ assemblyReference = this.GetAssemblyReferenceAt(resRow.Implementation & TokenTypeIds.RIDMask);
     if (assemblyReference == null) {
       //  MDError
       return Dummy.Resource;
     }
     var assembly = assemblyReference.ResolvedAssembly as Assembly;
     if (assembly == null) {
       //  MDError
       return Dummy.Resource;
     }
     ResourceReference/*?*/ resRef = assembly.PEFileToObjectModel.LookupResourceReference(resourceReference.Name);
     if (resRef == originalReference) {
       //  MDError
       return Dummy.Resource;
     }
     if (resRef == null)
       return Dummy.Resource;
     return assembly.PEFileToObjectModel.ResolveResource(resRef, originalReference);
   } else {
     return new Resource(this, resourceReference.ResourceRowId, resourceReference.Name, resRow.Flags, (resRow.Implementation & TokenTypeIds.RIDMask) != 0);
   }
 }
 private static string GetIdFromRef(ResourceReference refer, string resourceName)
 {
     return(string.IsNullOrEmpty(refer.ElementId)
         ? refer.Reference.Replace($"{resourceName}/", string.Empty)
         : refer.ElementId);
 }
        /// <summary>
        /// Deserialize JSON into a FHIR Reference
        /// </summary>
        public static void DeserializeJsonProperty(this ResourceReference current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
        {
            switch (propertyName)
            {
            case "reference":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.ReferenceElement = new FhirString();
                    reader.Skip();
                }
                else
                {
                    current.ReferenceElement = new FhirString(reader.GetString());
                }
                break;

            case "_reference":
                if (current.ReferenceElement == null)
                {
                    current.ReferenceElement = new FhirString();
                }
                ((Hl7.Fhir.Model.Element)current.ReferenceElement).DeserializeJson(ref reader, options);
                break;

            case "type":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.TypeElement = new FhirUri();
                    reader.Skip();
                }
                else
                {
                    current.TypeElement = new FhirUri(reader.GetString());
                }
                break;

            case "_type":
                if (current.TypeElement == null)
                {
                    current.TypeElement = new FhirUri();
                }
                ((Hl7.Fhir.Model.Element)current.TypeElement).DeserializeJson(ref reader, options);
                break;

            case "identifier":
                current.Identifier = new Hl7.Fhir.Model.Identifier();
                ((Hl7.Fhir.Model.Identifier)current.Identifier).DeserializeJson(ref reader, options);
                break;

            case "display":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.DisplayElement = new FhirString();
                    reader.Skip();
                }
                else
                {
                    current.DisplayElement = new FhirString(reader.GetString());
                }
                break;

            case "_display":
                if (current.DisplayElement == null)
                {
                    current.DisplayElement = new FhirString();
                }
                ((Hl7.Fhir.Model.Element)current.DisplayElement).DeserializeJson(ref reader, options);
                break;

            // Complex: Reference, Export: ResourceReference, Base: Element
            default:
                ((Hl7.Fhir.Model.Element)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
Beispiel #14
0
 public static ResourceReference GetComponentDefinition(this ResourceReference component)
 {
     return(component);
 }
 public ResourceSerializationContext(ResourceReference resource)
 {
     _resource = resource;
 }
Beispiel #16
0
 /**
  * Build up this event role with a person.
  * @param person The person.
  * @return this.
  */
 public EventRole SetPerson(ResourceReference person)
 {
     Person = person;
     return(this);
 }
        /// <summary>
        /// Checks whether the <see cref="ResourceReference"/> instance is empty or not.
        /// </summary>
        /// <param name="reference">The reference instance to check.</param>
        /// <returns><c>true</c> if the instance is empty; <c>false</c> otherwise.</returns>
        public static bool IsEmpty(this ResourceReference reference)
        {
            EnsureArg.IsNotNull(reference, nameof(reference));

            return(string.IsNullOrWhiteSpace(reference.Reference));
        }
Beispiel #18
0
        public void GivenAReferenceNode_WhenCryptoHash_PartlyHashedNodeShouldBeReturned(ResourceReference reference, string expectedValue)
        {
            var processor     = new CryptoHashProcessor(TestHashKey);
            var referenceNode = CreateNodeFromElement(reference)
                                .Children("reference").FirstOrDefault() as ElementNode;

            processor.Process(referenceNode);
            Assert.Equal(expectedValue, referenceNode.Value);
        }
Beispiel #19
0
 /// <summary>
 /// When a ResourceReference is relative, use the parent resource's fullUrl (e.g. from a Bundle's entry)
 /// to make it absolute.
 /// </summary>
 /// <param name="reference">The ResourceReference to get the (possibily relative) url from</param>
 /// <param name="parentResourceUri">Absolute uri representing the location of the resource this reference is in.</param>
 /// <remarks>Implements (part of the logic) as described in bundle.html#6.7.4.1</remarks>
 /// <returns></returns>
 public static Uri GetAbsoluteUriForReference(this ResourceReference reference, string parentResourceUri)
 {
     return(reference.GetAbsoluteUriForReference(new Uri(parentResourceUri, UriKind.RelativeOrAbsolute)));
 }
        public static void AddOperation(this CapabilityStatement conformance, String name, ResourceReference definition)
        {
            var operation = new CapabilityStatement.OperationComponent();

            operation.Name       = name;
            operation.Definition = definition;

            conformance.Server().Operation.Add(operation);
        }
 /// <summary>
 /// Populates the Resource reference cache
 /// </summary>
 void InitResourceReferenceArray()
   //^ ensures this.ResourceReferenceArray != null;
 {
   lock (GlobalLock.LockingObject) {
     if (this.ResourceReferenceArray == null) {
       uint num = this.PEFileReader.ManifestResourceTable.NumberOfRows;
       ResourceReference[] resourceReferenceArray = new ResourceReference[num + 1];
       for (uint i = 1; i <= num; ++i) {
         ManifestResourceRow resRow = this.PEFileReader.ManifestResourceTable[i];
         IName name = this.GetNameFromOffset(resRow.Name);
         uint tokenType = resRow.Implementation & TokenTypeIds.TokenTypeMask;
         IAssemblyReference defAssemRef = Dummy.AssemblyReference;
         if (tokenType == TokenTypeIds.File || resRow.Implementation == 0) {
           resourceReferenceArray[i] = new Resource(this, i, name, resRow.Flags, tokenType == TokenTypeIds.File);
         } else if (tokenType == TokenTypeIds.AssemblyRef) {
           AssemblyReference/*?*/ assemblyRef = this.GetAssemblyReferenceAt(resRow.Implementation & TokenTypeIds.RIDMask);
           if (assemblyRef == null) {
             //  MDError
           } else {
             resourceReferenceArray[i] = new ResourceReference(this, i, assemblyRef, resRow.Flags, name);
           }
         } else {
           //  MDError
         }
       }
       this.ResourceReferenceArray = resourceReferenceArray;
     }
   }
 }
Beispiel #22
0
        protected override async Task OnInitializedAsync()
        {
            // Test case #1
            // Create resources that directly referenced by the Patient resource
            Organization = await TestFhirClient.CreateAsync(Samples.GetJsonSample <Organization>("Organization"));

            string organizationReference = $"Organization/{Organization.Id}";

            // Create Patient resource
            Patient patientToCreate = Samples.GetJsonSample <Patient>("Patient-f001");

            patientToCreate.ManagingOrganization.Reference = organizationReference;
            patientToCreate.GeneralPractitioner            = new List <ResourceReference>
            {
                new(organizationReference),
            };
            Patient = await TestFhirClient.CreateAsync(patientToCreate);

            string patientReference = $"Patient/{Patient.Id}";

            // Create resources that references the Patient resource
            Device deviceToCreate = Samples.GetJsonSample <Device>("Device-d1");

            deviceToCreate.Patient = new ResourceReference(patientReference);
            Device = await TestFhirClient.CreateAsync(deviceToCreate);

            // Create Patient compartment resources
            Observation observationToCreate = Samples.GetJsonSample <Observation>("Observation-For-Patient-f001");

            observationToCreate.Subject.Reference = patientReference;
            Observation = await TestFhirClient.CreateAsync(observationToCreate);

            Encounter encounterToCreate = Samples.GetJsonSample <Encounter>("Encounter-For-Patient-f001");

            encounterToCreate.Subject.Reference = patientReference;
            Encounter = await TestFhirClient.CreateAsync(encounterToCreate);

            Appointment appointmentToCreate = Samples.GetJsonSample <Appointment>("Appointment");

            appointmentToCreate.Participant = new List <Appointment.ParticipantComponent>
            {
                new()
                {
                    Actor = new ResourceReference(patientReference),
                },
            };
            Appointment = await TestFhirClient.CreateAsync(appointmentToCreate);

            // Test case #2
            // Create resources for a non-existent patient
            patientToCreate.Id = "non-existent-patient-id";
            NonExistentPatient = await TestFhirClient.CreateAsync(patientToCreate);

            patientReference = $"Patient/{NonExistentPatient.Id}";

            deviceToCreate.Patient     = new ResourceReference(patientReference);
            DeviceOfNonExistentPatient = await TestFhirClient.CreateAsync(deviceToCreate);

            observationToCreate.Subject.Reference = patientReference;
            ObservationOfNonExistentPatient       = await TestFhirClient.CreateAsync(observationToCreate);

            await TestFhirClient.DeleteAsync(NonExistentPatient);
        }
Beispiel #23
0
        public void InjectDds(TagSerializer serializer, TagDeserializer deserializer, Bitmap bitmap, int imageIndex, Stream ddsStream)
        {
            var resource    = bitmap.Resources[imageIndex].Resource;
            var newResource = (resource == null);
            ResourceSerializationContext    resourceContext;
            BitmapTextureResourceDefinition definition;

            if (newResource)
            {
                // Create a new resource reference
                resource = new ResourceReference
                {
                    DefinitionFixups = new List <ResourceDefinitionFixup>(),
                    D3DObjectFixups  = new List <D3DObjectFixup>(),
                    Type             = 1, // TODO: Map out this type enum instead of using numbers
                    Unknown68        = 1
                };
                bitmap.Resources[imageIndex].Resource = resource;
                resourceContext = new ResourceSerializationContext(resource);
                definition      = new BitmapTextureResourceDefinition
                {
                    Texture = new D3DPointer <BitmapTextureResourceDefinition.BitmapDefinition>
                    {
                        Definition = new BitmapTextureResourceDefinition.BitmapDefinition()
                    }
                };
            }
            else
            {
                // Deserialize the old definition
                resourceContext = new ResourceSerializationContext(resource);
                definition      = deserializer.Deserialize <BitmapTextureResourceDefinition>(resourceContext);
            }
            if (definition.Texture == null || definition.Texture.Definition == null)
            {
                throw new ArgumentException("Invalid bitmap definition");
            }
            var texture   = definition.Texture.Definition;
            var imageData = bitmap.Images[imageIndex];

            // Read the DDS header and modify the definition to match
            var dds      = DdsHeader.Read(ddsStream);
            var dataSize = (int)(ddsStream.Length - ddsStream.Position);

            texture.Data            = new ResourceDataReference(dataSize, new ResourceAddress(ResourceAddressType.Resource, 0));
            texture.Width           = (short)dds.Width;
            texture.Height          = (short)dds.Height;
            texture.Depth           = (sbyte)Math.Max(1, dds.Depth);
            texture.Levels          = (sbyte)Math.Max(1, dds.MipMapCount);
            texture.Type            = BitmapDdsFormatDetection.DetectType(dds);
            texture.D3DFormatUnused = (int)((dds.D3D10Format != DxgiFormat.Bc5UNorm) ? dds.FourCc : DdsFourCc.FromString("ATI2"));
            texture.Format          = BitmapDdsFormatDetection.DetectFormat(dds);

            // Set flags based on the format
            switch (texture.Format)
            {
            case BitmapFormat.Dxt1:
            case BitmapFormat.Dxt3:
            case BitmapFormat.Dxt5:
            case BitmapFormat.Dxn:
                texture.Flags = BitmapFlags.Compressed;
                break;

            default:
                texture.Flags = BitmapFlags.None;
                break;
            }
            if ((texture.Width & (texture.Width - 1)) == 0 && (texture.Height & (texture.Height - 1)) == 0)
            {
                texture.Flags |= BitmapFlags.PowerOfTwoDimensions;
            }

            // If creating a new image, then add a new resource, otherwise replace the existing one
            if (newResource)
            {
                _resourceManager.Add(resource, ResourceLocation.Textures, ddsStream);
            }
            else
            {
                _resourceManager.Replace(resource, ddsStream);
            }

            // Serialize the new resource definition
            serializer.Serialize(resourceContext, definition);

            // Modify the image data in the bitmap tag to match the definition
            imageData.Width       = texture.Width;
            imageData.Height      = texture.Height;
            imageData.Depth       = texture.Depth;
            imageData.Type        = texture.Type;
            imageData.Format      = texture.Format;
            imageData.Flags       = texture.Flags;
            imageData.MipmapCount = (sbyte)(texture.Levels - 1);
            imageData.DataOffset  = texture.Data.Address.Offset;
            imageData.DataSize    = texture.Data.Size;
            imageData.Unknown15   = texture.Unknown35;
        }
 /// <summary>
 /// Validate a Secret in the profile.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='secretSource'>
 /// The secret source.
 /// </param>
 /// <param name='secretType'>
 /// The secret type. Possible values include: 'UrlSigningKey',
 /// 'ManagedCertificate', 'CustomerCertificate'
 /// </param>
 public static ValidateSecretOutput SecretMethod(this IValidateOperations operations, ResourceReference secretSource, string secretType)
 {
     return(operations.SecretMethodAsync(secretSource, secretType).GetAwaiter().GetResult());
 }
Beispiel #25
0
 public string GetOrganizationReferenceId(ResourceReference reference)
 {
     return(_validationHelper.GetResourceReferenceId(reference, FhirConstants.SystemODS));
 }
 /// <summary>
 /// Validate a Secret in the profile.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='secretSource'>
 /// The secret source.
 /// </param>
 /// <param name='secretType'>
 /// The secret type. Possible values include: 'UrlSigningKey',
 /// 'ManagedCertificate', 'CustomerCertificate'
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ValidateSecretOutput> SecretMethodAsync(this IValidateOperations operations, ResourceReference secretSource, string secretType, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.SecretMethodWithHttpMessagesAsync(secretSource, secretType, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Beispiel #27
0
 /// <summary>
 /// Get a single live value
 /// </summary>
 /// <param name="variable">The variable to read</param>
 /// <returns>The value of that variable</returns>
 /// <remarks>Will return null if the variable does not exist</remarks>
 public object GetValue(ResourceReference variable)
 {
     return(ProvideValues.GetValue(DeployPath.GetDeployPath(variable)));
 }
Beispiel #28
0
        /// <summary>
        /// Validate a Secret in the profile.
        /// </summary>
        /// <param name='secretSource'>
        /// The secret source.
        /// </param>
        /// <param name='secretType'>
        /// The secret type. Possible values include: 'UrlSigningKey',
        /// 'ManagedCertificate', 'CustomerCertificate'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="AfdErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <ValidateSecretOutput> > SecretMethodWithHttpMessagesAsync(ResourceReference secretSource, string secretType, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (secretSource == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "secretSource");
            }
            if (secretType == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "secretType");
            }
            ValidateSecretInput validateSecretInput = new ValidateSecretInput();

            if (secretSource != null || secretType != null)
            {
                validateSecretInput.SecretSource = secretSource;
                validateSecretInput.SecretType   = secretType;
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("validateSecretInput", validateSecretInput);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "SecretMethod", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (validateSecretInput != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(validateSecretInput, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new AfdErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    AfdErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <AfdErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <ValidateSecretOutput>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <ValidateSecretOutput>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Beispiel #29
0
 /**
  * Build out this source description with a mediator.
  *
  * @param mediator The mediator.
  * @return this.
  */
 public SourceDescription SetMediator(ResourceReference mediator)
 {
     Mediator = mediator;
     return(this);
 }
 public DirectionalLightActor(string name, ResourceReference archetype, string actorLabel, SpawnCollisionHandlingMethod spawnCollisionHandlingMethod, string folderPath, string rootComponentName, Node[] children, string directionalLightComponentName)
     : base(name, actorLabel, spawnCollisionHandlingMethod, folderPath, rootComponentName, archetype, children)
 {
     DirectionalLightComponentName = directionalLightComponentName;
 }
Beispiel #31
0
 /**
  * Build out this source description with a repository.
  *
  * @param repository The repository.
  * @return this.
  */
 public SourceDescription SetRepository(ResourceReference repository)
 {
     Repository = repository;
     return(this);
 }
Beispiel #32
0
        private void button1_Click_2(object sender, EventArgs e)
        {
            var endpoint = new Uri("http://fhirtest.uhn.ca/baseDstu2");
            var client   = new FhirClient(endpoint);

            // Create new value for observation
            SampledData     val     = new SampledData();
            CodeableConcept concept = new CodeableConcept();

            concept.Coding = new List <Coding>();

            if (conversionList.Text.Equals("age"))
            {
                val.Data = CurrentMeasurement.age.ToString();
                Coding code = new Coding();
                code.Code = "410668003";
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("bmr"))
            {
                val.Data = CurrentMeasurement.bmr.ToString();
                Coding code = new Coding();
                code.Code = "60621009";
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("height"))
            {
                val.Data = CurrentMeasurement.height.ToString();
                Coding code = new Coding();
                code.Code = "60621009"; //SNOMED CT code
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("m_active_time"))
            {
                val.Data = CurrentMeasurement.m_active_time.ToString();
            }
            else if (conversionList.Text.Equals("m_calories"))
            {
                val.Data = CurrentMeasurement.m_calories.ToString();
            }
            else if (conversionList.Text.Equals("m_distance"))
            {
                val.Data = CurrentMeasurement.m_distance.ToString();
            }
            else if (conversionList.Text.Equals("m_inactive_time"))
            {
                val.Data = CurrentMeasurement.m_inactive_time.ToString();
            }
            else if (conversionList.Text.Equals("m_lcat"))
            {
                val.Data = CurrentMeasurement.m_lcat.ToString();
            }
            else if (conversionList.Text.Equals("m_lcit"))
            {
                val.Data = CurrentMeasurement.m_lcit.ToString();
            }
            else if (conversionList.Text.Equals("m_steps"))
            {
                val.Data = CurrentMeasurement.m_steps.ToString();
            }
            else if (conversionList.Text.Equals("m_total_calories"))
            {
                val.Data = CurrentMeasurement.m_total_calories.ToString();
            }
            else if (conversionList.Text.Equals("s_asleep_time"))
            {
                val.Data = CurrentMeasurement.s_asleep_time.ToString();
            }
            else if (conversionList.Text.Equals("s_awake"))
            {
                val.Data = CurrentMeasurement.s_awake.ToString();
            }
            else if (conversionList.Text.Equals("s_awake_time"))
            {
                val.Data = CurrentMeasurement.s_awake_time.ToString();
            }
            else if (conversionList.Text.Equals("s_awakenings"))
            {
                val.Data = CurrentMeasurement.s_awakenings.ToString();
            }
            else if (conversionList.Text.Equals("s_bedtime"))
            {
                val.Data = CurrentMeasurement.s_bedtime.ToString();
            }
            else if (conversionList.Text.Equals("s_clinical_deep"))
            {
                val.Data = CurrentMeasurement.s_clinical_deep.ToString();
            }
            else if (conversionList.Text.Equals("s_count"))
            {
                val.Data = CurrentMeasurement.s_count.ToString();
            }
            else if (conversionList.Text.Equals("s_duration"))
            {
                val.Data = CurrentMeasurement.s_duration.ToString();
            }
            else if (conversionList.Text.Equals("s_light"))
            {
                val.Data = CurrentMeasurement.s_light.ToString();
            }
            else if (conversionList.Text.Equals("s_quality"))
            {
                val.Data = CurrentMeasurement.s_quality.ToString();
            }
            else if (conversionList.Text.Equals("s_rem"))
            {
                val.Data = CurrentMeasurement.s_rem.ToString();
            }
            else if (conversionList.Text.Equals("weight"))
            {
                val.Data = CurrentMeasurement.weight.ToString();
            }
            else
            {
                val.Data = "E";  // Error
            }
            Console.WriteLine("Value data: " + val.Data);

            ResourceReference dev = new ResourceReference();

            dev.Reference = "Device/" + CurrentDevice.Id;

            ResourceReference pat = new ResourceReference();

            pat.Reference = "Patient/" + CurrentPatient.Id;

            Console.WriteLine("Patient reference: " + pat.Reference);

            Console.WriteLine("Conversion: " + conversionList.Text);

            CodeableConcept naam = new CodeableConcept();

            naam.Text = conversionList.Text;

            DateTime date = DateTime.ParseExact(CurrentMeasurement.date, "yyyymmdd", null);

            Console.WriteLine("" + date.ToString());
            var obs = new Observation()
            {
                Device = dev, Subject = pat, Value = val, Issued = date, Code = naam, Category = concept, Status = Observation.ObservationStatus.Final
            };

            client.Create(obs);

            conversionStatus.Text = "Done!";
        }
 public static void ValidateResourceReference(string expectedReference, ResourceReference actualResourceReference)
 {
     Assert.NotNull(actualResourceReference);
     Assert.Equal(expectedReference, actualResourceReference.Reference);
 }
Beispiel #34
0
        public void AFDSecretGetListTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                try
                {
                    // Create a standard Azure frontdoor profile
                    string  profileName      = TestUtilities.GenerateName("profile");
                    Profile createParameters = new Profile
                    {
                        Location = "WestUs",
                        Sku      = new Sku {
                            Name = SkuName.StandardAzureFrontDoor
                        },
                        Tags = new Dictionary <string, string>
                        {
                            { "key1", "value1" },
                            { "key2", "value2" }
                        }
                    };
                    var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                    // Create a standard Azure frontdoor profile
                    string secretName   = TestUtilities.GenerateName("secretName");
                    var    secretSource = new ResourceReference("/subscriptions/d7cfdb98-c118-458d-8bdf-246be66b1f5e/resourceGroups/cdn-powershell-test/providers/Microsoft.KeyVault/vaults/cdn-powershell-test-kv/certificates/cdn-powershell-test-cer");
                    CustomerCertificateParameters parameters = new CustomerCertificateParameters(secretSource)
                    {
                        UseLatestVersion        = true,
                        SubjectAlternativeNames = new List <string>(),
                    };

                    var secret = cdnMgmtClient.Secrets.Create(resourceGroupName, profileName, secretName, parameters);
                    Assert.NotNull(secret);
                    Assert.Equal(secretName, secret.Name);

                    var getSecret = cdnMgmtClient.Secrets.Get(resourceGroupName, profileName, secretName);
                    Assert.NotNull(getSecret);
                    Assert.Equal(secretName, getSecret.Name);

                    var listSecrets = cdnMgmtClient.Secrets.ListByProfile(resourceGroupName, profileName);
                    Assert.NotNull(listSecrets);
                    Assert.Single(listSecrets);

                    string secretName2 = TestUtilities.GenerateName("secretName");
                    var    secrets     = cdnMgmtClient.Secrets.Create(resourceGroupName, profileName, secretName2, parameters);

                    listSecrets = cdnMgmtClient.Secrets.ListByProfile(resourceGroupName, profileName);
                    Assert.NotNull(listSecrets);
                    Assert.Equal(2, listSecrets.Count());
                }
                finally
                {
                    // Delete resource group
                    _ = CdnTestUtilities.DeleteResourceGroupAsync(resourcesClient, resourceGroupName);
                }
            }
        }