/// <summary>
 /// Gets a resource permissions.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IPermissionOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource
 /// </param>
 /// <returns>
 /// Permissions information.
 /// </returns>
 public static PermissionGetResult ListForResource(this IPermissionOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IPermissionOperations)s).ListForResourceAsync(resourceGroupName, identity);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Gets a list of resource providers.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IResourceProviderOperationDetailsOperations.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// List of resource provider operations.
 /// </returns>
 public static ResourceProviderOperationDetailListResult List(this IResourceProviderOperationDetailsOperations operations, ResourceIdentity identity)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IResourceProviderOperationDetailsOperations)s).ListAsync(identity);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();
                StorageAccountName = StorageAccountName.ToLower();
                ResourceIdentity identity = new ResourceIdentity();
                identity.ResourceName = StorageAccountName;
                identity.ResourceProviderNamespace = "Microsoft.ClassicStorage/storageAccounts";
                identity.ResourceProviderApiVersion = "2015-12-01";
                identity.ResourceType = string.Empty;

                ResourcesNS.Models.ResourceGetResult resource = null;
                try
                {
                    WriteDebug(String.Format("Query Microsoft.ClassicStorage with name = {0}",
                        StorageAccountName));
                    resource = RmClient.Resources.GetAsync(StorageAccountResourceGroupName,
                        identity, CancellationToken.None).Result;
                }
                catch (Exception)
                {
                    identity.ResourceProviderNamespace = "Microsoft.Storage/storageAccounts";
                    identity.ResourceProviderApiVersion = "2016-01-01";
                    resource = RmClient.Resources.GetAsync(StorageAccountResourceGroupName,
                        identity, CancellationToken.None).Result;
                }

                string storageAccountId = resource.Resource.Id;
                string storageAccountlocation = resource.Resource.Location;
                string storageAccountType = resource.Resource.Type;

                WriteDebug(String.Format("StorageId = {0}", storageAccountId));

                PsBackupProviderManager providerManager = new PsBackupProviderManager(
                    new Dictionary<System.Enum, object>()
                {
                    {RestoreBackupItemParams.RecoveryPoint, RecoveryPoint},
                    {RestoreBackupItemParams.StorageAccountId, storageAccountId},
                    {RestoreBackupItemParams.StorageAccountLocation, storageAccountlocation},
                    {RestoreBackupItemParams.StorageAccountType, storageAccountType}
                }, ServiceClientAdapter);

                IPsBackupProvider psBackupProvider = providerManager.GetProviderInstance(
                    RecoveryPoint.WorkloadType, RecoveryPoint.BackupManagementType);
                var jobResponse = psBackupProvider.TriggerRestore();

                WriteDebug(String.Format("Restore submitted"));
                HandleCreatedJob(jobResponse, Resources.RestoreOperation);
            });
        }
コード例 #4
0
        /// <summary>
        /// Get a list of Provider operations in the case that the Actionstring input contains a wildcard
        /// </summary>
        private List<PSResourceProviderOperation> ProcessProviderOperationsWithWildCard(string actionString, Dictionary<string, string> resourceProvidersWithOperationsApi)
        {
            Dictionary<string, string> resourceProvidersToQuery = GetAzureProviderOperationCommand.FilterResourceProvidersToQueryForOperations(actionString, resourceProvidersWithOperationsApi);
            
            // Filter the list of all operation names to what matches the wildcard
            WildcardPattern wildcard = new WildcardPattern(actionString, WildcardOptions.IgnoreCase | WildcardOptions.Compiled);

            IList<ResourceIdentity> resourceidentities = new List<ResourceIdentity>();
            foreach (KeyValuePair<string, string> kvp in resourceProvidersToQuery)
            {
                ResourceIdentity identity = new ResourceIdentity()
                {
                    ResourceName = string.Empty,
                    ResourceType = "operations",
                    ResourceProviderNamespace = kvp.Key,
                    ResourceProviderApiVersion = kvp.Value
                };

                resourceidentities.Add(identity);
            }

            return this.ResourcesClient.ListPSProviderOperations(resourceidentities).Where(operation => wildcard.IsMatch(operation.OperationName)).ToList();
        }
コード例 #5
0
 /// <summary>
 /// Create a resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update resource parameters.
 /// </param>
 /// <returns>
 /// Resource information.
 /// </returns>
 public static ResourceCreateOrUpdateResult CreateOrUpdate(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters)
 {
     return Task.Factory.StartNew((object s) =>
     {
         return ((IResourceOperations)s).CreateOrUpdateAsync(resourceGroupName, identity, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
コード例 #6
0
ファイル: CreatePingWebTest.cs プロジェクト: cnq/insights-poc
        private static GenericResourceExtended CreateOrUpdateInsightsResource(
            ResourceManagementClient resourceClient, 
            string resourceGroupName, 
            string insightsResourceName, 
            string location)
        {
            var resourceGroupResult = resourceClient.ResourceGroups.CreateOrUpdateAsync(
                resourceGroupName,
                new ResourceGroup(location)).Result;

            if(resourceGroupResult.StatusCode != HttpStatusCode.Created && resourceGroupResult.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException(
                    string.Format("Unable to create resource group '{0}' (HTTP Status Code: {1}).",
                    resourceGroupName,
                    resourceGroupResult.StatusCode));
            }

            var resourceIdentity = new ResourceIdentity(
                insightsResourceName,
                "microsoft.insights/components",
                "2015-05-01");

            var resourceResult = resourceClient.Resources.CreateOrUpdateAsync(
                resourceGroupName,
                resourceIdentity,
                new GenericResource(location)).Result;

            if (resourceResult.StatusCode != HttpStatusCode.Created && resourceResult.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException(
                    string.Format("Unable to create resource '{0}' (HTTP Status Code: {1}).",
                    insightsResourceName,
                    resourceResult.StatusCode));
            }

            return resourceResult.Resource;
        }
コード例 #7
0
        private static KeyBundle CreateKeyVaultKeyAccessibleByIdentity(SqlManagementTestContext context,
                                                                       ResourceGroup resourceGroup, ResourceIdentity identity)
        {
            var sqlClient = context.GetClient <SqlManagementClient>();
            var keyVaultManagementClient = context.GetClient <KeyVaultManagementClient>();
            var keyVaultClient           = TestEnvironmentUtilities.GetKeyVaultClient();

            // Prepare vault permissions for the server
            var permissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.WrapKey,
                    KeyPermissions.UnwrapKey,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };

            var aclEntry = new AccessPolicyEntry(identity.TenantId.Value,
                                                 identity.PrincipalId.Value.ToString(), permissions);

            // Prepare vault permissions for the app used in this test
            var appPermissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.Create,
                    KeyPermissions.Delete,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };
            string authObjectId = TestEnvironmentUtilities.GetUserObjectId();
            var    aclEntryUser = new AccessPolicyEntry(identity.TenantId.Value, authObjectId, appPermissions);

            // Create a vault
            var accessPolicy = new List <AccessPolicyEntry>()
            {
                aclEntry, aclEntryUser
            };
            string vaultName     = SqlManagementTestUtilities.GenerateName();
            string vaultLocation = TestEnvironmentUtilities.DefaultLocation;
            var    vault         = keyVaultManagementClient.Vaults.CreateOrUpdate(resourceGroup.Name, vaultName,
                                                                                  new VaultCreateOrUpdateParameters()
            {
                Location   = vaultLocation,
                Properties = new VaultProperties()
                {
                    AccessPolicies   = accessPolicy,
                    TenantId         = identity.TenantId.Value,
                    EnableSoftDelete = true
                }
            });

            // Create a key
            // This can be flaky if attempted immediately after creating the vault. Adding short sleep to improve robustness.
            TestUtilities.Wait(TimeSpan.FromSeconds(3));
            string keyName = SqlManagementTestUtilities.GenerateName();

            return(keyVaultClient.CreateKeyAsync(vault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa,
                                                 keyOps: JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult());
        }
コード例 #8
0
        // Process request and craft response.
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            if (request.Method == "OPTIONS")
            {
                // This is the CORS request, and that's good
                base.StatusCode = 200;
                // base.Headers.Add("Access-Control-Allow-Origin", "*");
                base.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS");
                base.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, authorization");
                callback.Continue();
                return(CefReturnValue.Continue);
            }
            var uri = new Uri(request.Url);

            Console.WriteLine($"-----------------\r\n{request.Url}");

            // Check the bearer header
            if (!string.IsNullOrEmpty(_launchContext.Bearer))
            {
                string bearer = request.GetHeaderByName("authorization");
                if (bearer != "Bearer " + _launchContext.Bearer)
                {
                    base.StatusCode = (int)HttpStatusCode.Unauthorized;
                    callback.Continue();
                    return(CefReturnValue.Continue);
                }
            }

            try
            {
                // This is a regular request
                Hl7.Fhir.Rest.FhirClient server = new Hl7.Fhir.Rest.FhirClient("http://localhost:4178");
                server.OnAfterResponse += (sender, args) =>
                {
                    base.Charset = args.RawResponse.CharacterSet;
                    foreach (string header in args.RawResponse.Headers.AllKeys)
                    {
                        base.Headers.Add(header, args.RawResponse.Headers[header]);
                    }
                };
                server.PreferredFormat = Hl7.Fhir.Rest.ResourceFormat.Json;
                string redirectedUrl = server.Endpoint.OriginalString.TrimEnd('/') + uri.PathAndQuery;
                System.Diagnostics.Trace.WriteLine($"{redirectedUrl}");
                var headers = new List <KeyValuePair <string, IEnumerable <string> > >();
                ModelBaseInputs <IServiceProvider> requestDetails = new ModelBaseInputs <IServiceProvider>(null, null, request.Method, uri, new Uri($"https://{AuthProtocolSchemeHandlerFactory.FhirFacadeAddress(_launchContext)}"), null, headers, null);
                if (request.Method == "GET")
                {
                    if (uri.LocalPath == "/metadata")
                    {
                        _facade.GetConformance(requestDetails, Rest.SummaryType.False).ContinueWith <CapabilityStatement>(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            base.StatusCode = 200;

                            // As per the documentation http://hl7.org/fhir/smart-app-launch/conformance/index.html
                            CapabilityStatement cs = r.Result;

                            // Update the security node with our internal security node
                            if (cs.Rest[0].Security == null)
                            {
                                cs.Rest[0].Security = new Hl7.Fhir.Model.CapabilityStatement.SecurityComponent();
                            }
                            Hl7.Fhir.Model.CapabilityStatement.SecurityComponent security = cs.Rest[0].Security;
                            if (!security.Service.Any(cc => cc.Coding.Any(c => c.System == "http://hl7.org/fhir/restful-security-service" && c.Code == "SMART-on-FHIR")))
                            {
                                security.Service.Add(new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/restful-security-service", "SMART-on-FHIR"));
                            }
                            var extension = security.GetExtension("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris");
                            if (extension == null)
                            {
                                extension = new Extension()
                                {
                                    Url = "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"
                                };
                                security.Extension.Add(extension);
                            }
                            // remove the existing authentications, and put in our own
                            extension.Extension.Clear();
                            extension.AddExtension("token", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/token"));
                            extension.AddExtension("authorize", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/authorize"));

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    if (!uri.LocalPath.StartsWith("/$") && !uri.LocalPath.StartsWith("/_") && uri.LocalPath.Length > 2)
                    {
                        // This is not an operation or history, so it must be a resource type
                        string resourceType = uri.LocalPath.Substring(1);
                        if (resourceType.Contains("/"))
                        {
                            resourceType = resourceType.Substring(0, resourceType.IndexOf("/"));
                        }
                        var rs = _facade.GetResourceService(requestDetails, resourceType);
                        if (rs == null)
                        {
                            System.Diagnostics.Trace.WriteLine($"Error: resource type not handled {resourceType}");
                            base.StatusCode = (int)HttpStatusCode.BadRequest;
                            //    base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings() { Pretty = true }).SerializeToBytes(fe.Outcome));
                            //    base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(CefReturnValue.Continue);
                        }

                        // GET for a specific resource
                        ResourceIdentity ri = new ResourceIdentity(uri);
                        if (ri.IsRestResourceIdentity())
                        {
                            rs.Get(ri.Id, ri.VersionId, SummaryType.False).ContinueWith(r =>
                            {
                                if (r.Exception != null)
                                {
                                    System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                    if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                    {
                                        base.StatusCode = (int)fe.Status;
                                        if (fe.Outcome != null)
                                        {
                                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                            {
                                                Pretty = true
                                            }).SerializeToBytes(fe.Outcome));
                                            base.MimeType = "application/fhir+json";
                                        }
                                        callback.Continue();
                                        System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                        return(null);
                                    }
                                }
                                if (r.Result.HasAnnotation <HttpStatusCode>())
                                {
                                    base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                                }
                                else
                                {
                                    base.StatusCode = 200;
                                }

                                base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                {
                                    Pretty = true
                                }).SerializeToBytes(r.Result));
                                Console.WriteLine($"Success: {base.Stream.Length}");
                                base.MimeType = "application/fhir+json";
                                callback.Continue();
                                return(r.Result);
                            });
                            return(CefReturnValue.ContinueAsync);
                        }

                        // Search for the resource type
                        var parameters = TupledParameters(uri, SearchQueryParameterNames);
                        int?pagesize   = GetIntParameter(uri, FhirParameter.COUNT);
                        var summary    = GetSummaryParameter(uri);
                        rs.Search(parameters, pagesize, summary).ContinueWith(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            if (r.Result.HasAnnotation <HttpStatusCode>())
                            {
                                base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                            }
                            else
                            {
                                base.StatusCode = 200;
                            }

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    System.Threading.Tasks.Task <Hl7.Fhir.Model.Resource> t = server.GetAsync(redirectedUrl).ContinueWith <Hl7.Fhir.Model.Resource>(r =>
                    {
                        if (r.Exception != null)
                        {
                            System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                            if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            {
                                base.StatusCode = (int)fe.Status;
                                if (fe.Outcome != null)
                                {
                                    base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                    {
                                        Pretty = true
                                    }).SerializeToBytes(fe.Outcome));
                                    base.MimeType = "application/fhir+json";
                                }
                                callback.Continue();
                                System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                return(null);
                            }
                        }
                        base.StatusCode = 200;

                        if (r.Result is Hl7.Fhir.Model.CapabilityStatement cs)
                        {
                            // As per the documentation http://hl7.org/fhir/smart-app-launch/conformance/index.html

                            // Update the security node with our internal security node
                            if (cs.Rest[0].Security == null)
                            {
                                cs.Rest[0].Security = new Hl7.Fhir.Model.CapabilityStatement.SecurityComponent();
                            }
                            Hl7.Fhir.Model.CapabilityStatement.SecurityComponent security = cs.Rest[0].Security;
                            if (!security.Service.Any(cc => cc.Coding.Any(c => c.System == "http://hl7.org/fhir/restful-security-service" && c.Code == "SMART-on-FHIR")))
                            {
                                security.Service.Add(new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/restful-security-service", "SMART-on-FHIR"));
                            }
                            var extension = security.GetExtension("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris");
                            if (extension == null)
                            {
                                extension = new Extension()
                                {
                                    Url = "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"
                                };
                                security.Extension.Add(extension);
                            }
                            // remove the existing authentications, and put in our own
                            extension.Extension.Clear();
                            extension.AddExtension("token", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/token"));
                            extension.AddExtension("authorize", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/authorize"));
                        }

                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                        {
                            Pretty = true
                        }).SerializeToBytes(r.Result));
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = "application/fhir+json";
                        callback.Continue();
                        return(r.Result);
                    });
                }
                if (request.Method == "POST")
                {
                    if (uri.LocalPath == "/")
                    {
                        Bundle b = null;
                        if (request.PostData != null)
                        {
                            var data = request.PostData.Elements.FirstOrDefault();
                            var body = data.GetBody();
                            if (request.GetHeaderByName("Content-Type").Contains("xml"))
                            {
                                b = new Hl7.Fhir.Serialization.FhirXmlParser().Parse <Bundle>(body);
                            }
                            else
                            {
                                b = new Hl7.Fhir.Serialization.FhirJsonParser().Parse <Bundle>(body);
                            }
                        }

                        _facade.ProcessBatch(requestDetails, b).ContinueWith(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            if (r.Result.HasAnnotation <HttpStatusCode>())
                            {
                                base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                            }
                            else
                            {
                                base.StatusCode = 200;
                            }

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                    client.DefaultRequestHeaders.Add("Accept", request.GetHeaderByName("Accept"));
                    // client.DefaultRequestHeaders.Add("Content-Type", request.GetHeaderByName("Content-Type"));
                    HttpContent content = null;
                    if (request.PostData != null)
                    {
                        var data = request.PostData.Elements.FirstOrDefault();
                        var body = data.GetBody();
                        content = new System.Net.Http.StringContent(body, System.Text.Encoding.UTF8, request.GetHeaderByName("Content-Type"));
                    }
                    else
                    {
                        content = new System.Net.Http.StreamContent(null);
                    }
                    client.PostAsync(redirectedUrl, content).ContinueWith((System.Threading.Tasks.Task <HttpResponseMessage> r) =>
                    {
                        if (r.Exception != null)
                        {
                            Console.WriteLine($"Error: {r.Exception.Message}");
                            //if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            //{
                            //    base.StatusCode = (int)fe.Status;
                            //    if (fe.Outcome != null)
                            //        base.Stream = new MemoryStream(r.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                            //    callback.Continue();
                            //    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                            //    return;
                            //}
                        }
                        base.StatusCode = (int)r.Result.StatusCode;

                        base.Stream = r.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = r.Result.Content.Headers.ContentType.MediaType;
                        callback.Continue();
                        return;
                    });
                }
                if (request.Method == "PUT")
                {
                    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                    client.DefaultRequestHeaders.Add("Accept", request.GetHeaderByName("Accept"));
                    // client.DefaultRequestHeaders.Add("Content-Type", request.GetHeaderByName("Content-Type"));
                    HttpContent content = null;
                    if (request.PostData != null)
                    {
                        var data = request.PostData.Elements.FirstOrDefault();
                        var body = data.GetBody();
                        content = new System.Net.Http.StringContent(body, System.Text.Encoding.UTF8, request.GetHeaderByName("Content-Type"));
                    }
                    else
                    {
                        content = new System.Net.Http.StreamContent(null);
                    }
                    client.PutAsync(redirectedUrl, content).ContinueWith((System.Threading.Tasks.Task <HttpResponseMessage> r) =>
                    {
                        if (r.Exception != null)
                        {
                            Console.WriteLine($"Error: {r.Exception.Message}");
                            //if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            //{
                            //    base.StatusCode = (int)fe.Status;
                            //    if (fe.Outcome != null)
                            //        base.Stream = new MemoryStream(r.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                            //    callback.Continue();
                            //    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                            //    return;
                            //}
                        }
                        base.StatusCode = (int)r.Result.StatusCode;

                        base.Stream = r.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = r.Result.Content.Headers.ContentType.MediaType;
                        callback.Continue();
                        return;
                    });
                }
                return(CefReturnValue.ContinueAsync);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
                callback.Dispose();
                return(CefReturnValue.Cancel);
            }
        }
コード例 #9
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource <PolicyAssignmentProperties>();

            // get incoming object properties if present
            JObject inputMetadata = null;

            if (this.InputObject != null)
            {
                var newProperties = this.InputObject.Properties.ToJToken();
                inputMetadata = newProperties["metadata"] as JObject;
            }

            var parameterMetadata = this.Metadata != null?this.GetObjectFromParameter(this.Metadata, nameof(this.Metadata)) : null;

            PolicyAssignmentEnforcementMode?inputMode = null;

            if (Enum.TryParse(this.InputObject?.Properties?.EnforcementMode?.ToString(), true, out PolicyAssignmentEnforcementMode tempMode1))
            {
                inputMode = tempMode1;
            }

            // Grab the non-compliance messages from the parameter or input object or existing resource
            var nonComplianceMessages = this.NonComplianceMessage?.Where(message => message != null).SelectArray(message => message.ToModel());

            if (nonComplianceMessages == null && this.InputObject?.Properties.NonComplianceMessages != null)
            {
                nonComplianceMessages = this.InputObject.Properties.NonComplianceMessages.Where(message => message != null).SelectArray(message => message.ToModel());
            }
            else if (nonComplianceMessages == null)
            {
                nonComplianceMessages = resource.Properties.NonComplianceMessages;
            }

            if (this.AssignIdentity != null && this.AssignIdentity.IsPresent)
            {
                this.IdentityType = ManagedIdentityType.SystemAssigned;
            }

            ResourceIdentity identityObject = this.IdentityType != null ?
                                              (this.IdentityType == ManagedIdentityType.UserAssigned ?
                                               new ResourceIdentity
            {
                Type = IdentityType.ToString(),
                UserAssignedIdentities = new Dictionary <string, UserAssignedIdentityResource>
                {
                    { this.IdentityId, new UserAssignedIdentityResource {
                      } }
                }
            } :
                                               new ResourceIdentity {
                Type = IdentityType.ToString()
            }
                                              ) : null;

            var policyAssignmentObject = new PolicyAssignment
            {
                Name       = this.Name ?? this.InputObject?.Name ?? resource.Name,
                Identity   = identityObject,
                Location   = this.Location ?? this.InputObject?.Location ?? resource.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName           = this.DisplayName ?? this.InputObject?.Properties?.DisplayName ?? resource.Properties.DisplayName,
                    Description           = this.Description ?? this.InputObject?.Properties?.Description ?? resource.Properties.Description,
                    Scope                 = resource.Properties.Scope,
                    NotScopes             = this.NotScope ?? this.InputObject?.Properties?.NotScopes ?? resource.Properties.NotScopes,
                    PolicyDefinitionId    = resource.Properties.PolicyDefinitionId,
                    Metadata              = parameterMetadata ?? inputMetadata ?? resource.Properties.Metadata,
                    EnforcementMode       = this.EnforcementMode ?? inputMode ?? resource.Properties.EnforcementMode,
                    NonComplianceMessages = nonComplianceMessages,
                    Parameters            =
                        this.GetParameters(this.PolicyParameter, this.PolicyParameterObject)
                        ?? this.InputObject?.Properties?.Parameters?.ToResourcePropertiesBody() as JObject
                        ?? resource.Properties.Parameters
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var token         = request.DataStore.GetJson("AzureToken")["access_token"].ToString();
            var subscription  = request.DataStore.GetJson("SelectedSubscription")["SubscriptionId"].ToString();
            var resourceGroup = request.DataStore.GetValue("SelectedResourceGroup");

            string sfUsername = request.DataStore.GetValue("SalesforceUser");
            string sfPassword = request.DataStore.GetValue("SalesforcePassword");
            string sfToken    = request.DataStore.GetValue("SalesforceToken");
            string sfUrl      = request.DataStore.GetValue("SalesforceUrl");

            string fullServerUrl = request.DataStore.GetValue("SalesforceBaseUrl");
            string connString    = request.DataStore.GetValue("SqlConnectionString");
            string fiscalMonth   = request.DataStore.GetValue("fiscalMonth");
            string actuals       = request.DataStore.GetValue("actuals");
            string emails        = request.DataStore.GetValue("EmailAddresses");

            string baseUrl = string.Empty;

            if (!string.IsNullOrEmpty(fullServerUrl))
            {
                var uri = new Uri(fullServerUrl);
                baseUrl = uri.Scheme + "://" + uri.Host + "/";
            }

            this.InsertCustomizations(connString, fiscalMonth, actuals, baseUrl);

            string dataFactoryName = resourceGroup + "SalesforceCopyFactory";
            var    param           = new AzureArmParameterGenerator();
            var    sqlCreds        = SqlUtility.GetSqlCredentialsFromConnectionString(connString);

            param.AddStringParam("dataFactoryName", dataFactoryName);
            param.AddStringParam("sqlServerName", sqlCreds.Server.Split('.')[0]);
            param.AddStringParam("sqlServerUsername", sqlCreds.Username);
            param.AddStringParam("targetDatabaseName", sqlCreds.Database);
            param.AddStringParam("salesforceUsername", sfUsername);
            param.AddStringParam("subscriptionId", subscription);
            param.AddStringParam("environmentUrl", sfUrl);
            param.AddParameter("salesforcePassword", "securestring", sfPassword);
            param.AddParameter("sqlServerPassword", "securestring", sqlCreds.Password);
            param.AddParameter("salesforceSecurityToken", "securestring", sfToken);

            var armTemplate      = JsonUtility.GetJsonObjectFromJsonString(System.IO.File.ReadAllText(Path.Combine(request.Info.App.AppFilePath, "Service/ADF/linkedServices.json")));
            var armParamTemplate = JsonUtility.GetJObjectFromObject(param.GetDynamicObject());

            armTemplate.Remove("parameters");
            armTemplate.Add("parameters", armParamTemplate["parameters"]);

            if (string.IsNullOrEmpty(emails))
            {
                (armTemplate
                 .SelectToken("resources")[0]
                 .SelectToken("resources") as JArray)
                .RemoveAt(2);
            }
            else
            {
                var           addresses = emails.Split(',');
                List <string> adr       = new List <string>();

                foreach (var address in addresses)
                {
                    adr.Add(address);
                }

                var stringTemplate = armTemplate.ToString();

                stringTemplate = stringTemplate.Replace("\"EMAILS\"", JsonConvert.SerializeObject(adr));
                armTemplate    = JsonUtility.GetJObjectFromJsonString(stringTemplate);
            }

            SubscriptionCloudCredentials creds  = new TokenCloudCredentials(subscription, token);
            ResourceManagementClient     client = new ResourceManagementClient(creds);

            var deployment = new Microsoft.Azure.Management.Resources.Models.Deployment()
            {
                Properties = new DeploymentPropertiesExtended()
                {
                    Template   = armTemplate.ToString(),
                    Parameters = JsonUtility.GetEmptyJObject().ToString()
                }
            };

            var factoryIdenity = new ResourceIdentity
            {
                ResourceProviderApiVersion = "2015-10-01",
                ResourceName = dataFactoryName,
                ResourceProviderNamespace = "Microsoft.DataFactory",
                ResourceType = "datafactories"
            };

            var factory = client.Resources.CheckExistence(resourceGroup, factoryIdenity);

            if (factory.Exists)
            {
                client.Resources.Delete(resourceGroup, factoryIdenity);
            }

            string deploymentName = "SalesforceCopyFactory-linkedServices";

            var validate = client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result;

            if (!validate.IsValid)
            {
                return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetJObjectFromObject(validate), null,
                                          DefaultErrorCodes.DefaultErrorCode, $"Azure:{validate.Error.Message} Details:{validate.Error.Details}"));
            }

            var deploymentItem = client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result;

            var helper = new DeploymentHelper();

            return(helper.WaitForDeployment(resourceGroup, deploymentName, client));
        }
コード例 #11
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var aadTenant = request.DataStore.GetValue("AADTenant");

            string authBase;
            string clientId;
            string resource;

            string oauthType = (request.DataStore.GetLastValue("oauthType") ?? string.Empty).ToLowerInvariant();

            switch (oauthType)
            {
            case "powerbi":
                authBase = string.Format(Constants.AzureAuthUri, aadTenant);
                clientId = Constants.MicrosoftClientIdPowerBI;
                resource = Constants.PowerBIService;
                break;

            case "mscrm":
                authBase = string.Format(Constants.AzureAuthUri, aadTenant);
                clientId = Constants.MsCrmClientId;
                resource = Constants.AzureManagementApi;
                break;

            case "keyvault":
                string azureToken     = request.DataStore.GetJson("AzureToken", "access_token");
                string subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId");
                string resourceGroup  = request.DataStore.GetValue("SelectedResourceGroup");


                // Make sure the Key Vault is registered
                SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscriptionId, azureToken);

                using (ResourceManagementClient managementClient = new ResourceManagementClient(creds))
                {
                    ProviderListResult providersResult = managementClient.Providers.List(null);

                    bool kvExists = false;
                    foreach (var p in providersResult.Providers)
                    {
                        if (p.Namespace.EqualsIgnoreCase("Microsoft.KeyVault"))
                        {
                            kvExists = p.RegistrationState.EqualsIgnoreCase("Registered");
                            break;
                        }
                    }

                    AzureOperationResponse operationResponse;
                    if (!kvExists)
                    {
                        operationResponse = managementClient.Providers.Register("Microsoft.KeyVault");
                        if (operationResponse.StatusCode != System.Net.HttpStatusCode.OK && operationResponse.StatusCode != System.Net.HttpStatusCode.Accepted)
                        {
                            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv"));
                        }

                        Thread.Sleep(10000);     // Wait for it to register
                    }

                    string oid;
                    string tenantID;
                    ExtractUserandTenant(azureToken, out oid, out tenantID);

                    const string    vaultApiVersion = "2015-06-01";
                    string          tempVaultName   = "bpst-" + RandomGenerator.GetRandomLowerCaseCharacters(12);
                    GenericResource genRes          = new GenericResource("westus")
                    {
                        Properties = "{\"sku\": { \"family\": \"A\", \"name\": \"Standard\" }, \"tenantId\": \"" + tenantID + "\", \"accessPolicies\": [], \"enabledForDeployment\": true }"
                    };

                    operationResponse = managementClient.Resources.CreateOrUpdate(resourceGroup, new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion), genRes);
                    bool operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted);
                    Thread.Sleep(15000);     // The created vault has an Url. DNS propagation will take a while

                    if (operationSucceeded)
                    {
                        ResourceIdentity resIdent = new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion);
                        operationResponse  = managementClient.Resources.Delete(resourceGroup, resIdent);
                        operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted);
                    }

                    if (!operationSucceeded)
                    {
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv"));
                    }
                }

                clientId = Constants.MicrosoftClientIdCrm;
                resource = Constants.AzureKeyVaultApi;
                authBase = string.Format(Constants.AzureAuthUri, aadTenant);

                break;

            default:
                authBase = string.Format(Constants.AzureAuthUri, aadTenant);
                clientId = Constants.MicrosoftClientId;
                resource = Constants.AzureManagementApi;
                break;
            }

            StringBuilder builder = GetRawAzureAuthUri(request, authBase, clientId, resource);

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromStringValue(builder.ToString())));
        }
コード例 #12
0
 /// <summary>
 /// Create or update a management lock at the resource level or any
 /// level below resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IManagementLockOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='lockName'>
 /// Required. The name of lock.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update management lock parameters.
 /// </param>
 /// <returns>
 /// Management lock information.
 /// </returns>
 public static Task<ManagementLockReturnResult> CreateOrUpdateAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName, ManagementLockProperties parameters)
 {
     return operations.CreateOrUpdateAtResourceLevelAsync(resourceGroupName, identity, lockName, parameters, CancellationToken.None);
 }
コード例 #13
0
 /// <summary>
 /// Deletes the management lock of a resource or any level below
 /// resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IManagementLockOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='lockName'>
 /// Required. The name of lock.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<AzureOperationResponse> DeleteAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName)
 {
     return operations.DeleteAtResourceLevelAsync(resourceGroupName, identity, lockName, CancellationToken.None);
 }
 /// <summary>
 /// Gets a list of resource providers.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceProviderOperationDetailsOperations.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// List of resource provider operations.
 /// </returns>
 public static Task <ResourceProviderOperationDetailListResult> ListAsync(this IResourceProviderOperationDetailsOperations operations, ResourceIdentity identity)
 {
     return(operations.ListAsync(identity, CancellationToken.None));
 }
コード例 #15
0
 /// <summary>
 /// Create or update a management lock at the resource level or any
 /// level below resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IManagementLockOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='lockName'>
 /// Required. The name of lock.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update management lock parameters.
 /// </param>
 /// <returns>
 /// Management lock information.
 /// </returns>
 public static ManagementLockReturnResult CreateOrUpdateAtResourceLevel(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, string lockName, ManagementLockProperties parameters)
 {
     return Task.Factory.StartNew((object s) =>
     {
         return ((IManagementLockOperations)s).CreateOrUpdateAtResourceLevelAsync(resourceGroupName, identity, lockName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Gets a list of resource providers.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceProviderOperationDetailsOperations.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// List of resource provider operations.
 /// </returns>
 public static ResourceProviderOperationDetailListResult List(this IResourceProviderOperationDetailsOperations operations, ResourceIdentity identity)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IResourceProviderOperationDetailsOperations)s).ListAsync(identity);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
コード例 #17
0
 /// <summary>
 /// Gets a resource permissions.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IPermissionOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource
 /// </param>
 /// <returns>
 /// Permissions information.
 /// </returns>
 public static Task <PermissionGetResult> ListForResourceAsync(this IPermissionOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return(operations.ListForResourceAsync(resourceGroupName, identity, CancellationToken.None));
 }
コード例 #18
0
 /// <summary>
 /// Gets a resource permissions.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IPermissionOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource
 /// </param>
 /// <returns>
 /// Permissions information.
 /// </returns>
 public static PermissionGetResult ListForResource(this IPermissionOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IPermissionOperations)s).ListForResourceAsync(resourceGroupName, identity);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
コード例 #19
0
 /// <summary>
 /// Delete resource and all of its resources.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static AzureOperationResponse Delete(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return Task.Factory.StartNew((object s) =>
     {
         return ((IResourceOperations)s).DeleteAsync(resourceGroupName, identity);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
コード例 #20
0
 /// <summary>
 /// Gets all the management locks of a resource or any level below
 /// resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IManagementLockOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Optional. Query parameters. If empty is passed returns all locks at
 /// or below the resource.If atScope() is passed returns all locks at
 /// the resource level.
 /// </param>
 /// <returns>
 /// List of management locks.
 /// </returns>
 public static ManagementLockListResult ListAtResourceLevel(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, ManagementLockGetQueryParameter parameters)
 {
     return Task.Factory.StartNew((object s) =>
     {
         return ((IManagementLockOperations)s).ListAtResourceLevelAsync(resourceGroupName, identity, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
コード例 #21
0
 /// <summary>
 /// Returns a resource belonging to a resource group.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// Resource information.
 /// </returns>
 public static Task<ResourceGetResult> GetAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return operations.GetAsync(resourceGroupName, identity, CancellationToken.None);
 }
コード例 #22
0
ファイル: Country.cs プロジェクト: supertigerzou/Dolphin
 public Country(string code)
 {
     Id = new ResourceIdentity(RESOURCE_TYPE, code);
 }
コード例 #23
0
ファイル: Form1.cs プロジェクト: daghammer/FhirTool
        private void btnTest_Click(object sender, EventArgs e)
        {
            //FhirClient sfmClient = new FhirClient("https://fhir-api.test1.forskrivning.no/api");
            FhirClient sfmClient = new FhirClient("http://hapi.fhir.org/baseR4/");

            sfmClient.PreferredFormat = ResourceFormat.Json;

            // var task = sfmClient.Read<Task>("http://hapi.fhir.org/baseR4/Task/642258");
            SfmTask sTask = new SfmTask();

            Task t = (Task)sTask;



            var task = sfmClient.Read <Task>(ResourceIdentity.Build("Task", "642258"));

            if (task != null)
            {
                textBox1.Text += "Task: " + task.Id + Environment.NewLine;
                textBox1.Text += "Text.div: " + task.Text.Div + Environment.NewLine;
                if (task.Extension.Count > 0)
                {
                    Extension extension = task.Extension[0];
                    string    u         = extension.Url;
                }

                foreach (string p in task.Meta.Profile)
                {
                    textBox1.Text += "Profile: " + p + Environment.NewLine;
                }

                textBox1.Text += "Code: " + task.Code.Text + Environment.NewLine;
                textBox1.Text += "Status: " + task.Status.ToString() + Environment.NewLine;
                textBox1.Text += "Intent: " + task.Intent.ToString() + Environment.NewLine;
                textBox1.Text += "Priority: " + task.Priority.ToString() + Environment.NewLine;

                foreach (Resource r in task.Contained)
                {
                    textBox1.Text += "Contained resource: " + r.ResourceType.ToString() + Environment.NewLine;
                    textBox1.Text += "Id: " + r.Id + Environment.NewLine;

                    switch (r.ResourceType)
                    {
                    case ResourceType.Patient:
                        Patient p = (Patient)r;

                        foreach (string pr in p.Meta.Profile)
                        {
                            textBox1.Text += "Profile: " + pr + Environment.NewLine;
                        }

                        foreach (Identifier i in p.Identifier)
                        {
                            textBox1.Text += "Patient.identifier: " + i.Value + "(" + i.Use.ToString() + ")" + Environment.NewLine;
                        }

                        break;
                    }
                }
            }



            // SfmMedicationStatement sfmMS = new SfmMedicationStatement();
            // sfmMS.ReseptID = Guid.NewGuid().ToString();
            // String rID = sfmMS.ReseptID;
        }
コード例 #24
0
        public void TestDeserializerInvalidDefaultJson()
        {
            JsonElement invalid = default(JsonElement);

            Assert.Throws <ArgumentException>(delegate { ResourceIdentity.DeserializeResourceIdentity(invalid); });
        }
コード例 #25
0
        public void CRUDResourceLock()
        {
            var handler = new RecordedDelegatingHandler();

            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetAuthorizationClient(handler);

                string resourceGroupName = "Default-SQL-EastAsia";
                ResourceIdentity resourceIdentity = new ResourceIdentity
                {
                    ParentResourcePath = "servers/g6gsefjdal",
                    ResourceName = "AutomatedSqlExport_manikdb_20131123T091548Z",
                    ResourceProviderNamespace = "Microsoft.Sql",
                    ResourceProviderApiVersion = "2014-01-04",
                    ResourceType = "databases"
                };
                string lockName = TestUtilities.GenerateName("mylock");
                string lockType = "Microsoft.Authorization/locks";
                var lockProperties = new ManagementLockProperties()
                {
                    Level = "CanNotDelete",
                    Notes = "optional text."
                };
                
                // 1 Create lock
                var createResult = client.ManagementLocks.CreateOrUpdateAtResourceLevel(resourceGroupName, resourceIdentity, lockName, lockProperties);
                
                Assert.Equal(HttpStatusCode.Created, createResult.StatusCode);
                Assert.Equal(lockName, createResult.ManagementLock.Name);
                Assert.Equal(lockProperties.Level, createResult.ManagementLock.Properties.Level);
                Assert.Equal(lockProperties.Notes, createResult.ManagementLock.Properties.Notes);
                Assert.Equal(lockType, createResult.ManagementLock.Type);

                // 2 Get all RG locks with no filter
                var getResult1 = client.ManagementLocks.ListResourceLevel(resourceGroupName, resourceIdentity, new ManagementLockGetQueryParameter { AtScope = "" });

                Assert.Equal(HttpStatusCode.OK, getResult1.StatusCode);
                Assert.True(getResult1.Lock.Any(p => p.Name==lockName));
                
                // 3 Get all resource level locks with filter
                var getResult2 = client.ManagementLocks.ListResourceLevel(resourceGroupName, resourceIdentity, new ManagementLockGetQueryParameter() { AtScope = "atScope()" });

                Assert.Equal(HttpStatusCode.OK, getResult2.StatusCode);
                Assert.True(getResult2.Lock.Any(p => p.Name == lockName));

                //Delete lock
                var deleteResult = client.ManagementLocks.DeleteAtResourceLevel(resourceGroupName, resourceIdentity, lockName);
                Assert.Equal(HttpStatusCode.OK, deleteResult.StatusCode);
            }
        }
コード例 #26
0
        public void TestHttpUpdate()
        {
            ResourceIdentity identity1 = ResourceIdentity.Build("Observation", "2");
            ResourceIdentity identity2 = ResourceIdentity.Build("Observation", "3");

            Observation observation1 = fhirClient.Read <Observation>(identity1);

            observation1.Status = Observation.ObservationStatus.Amended;
            Observation observation2 = fhirClient.Read <Observation>(identity2);

            observation2.Device = new ResourceReference()
            {
                Reference = "Device/4"
            };


            // Successful update (JSON)
            string observation1Json = FhirSerializer.SerializeResourceToJson(observation1);
            string observation2Json = FhirSerializer.SerializeResourceToJson(observation2);

            HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/2")
            {
                Content = new StringContent(observation1Json, Encoding.UTF8, "application/json+fhir")
            };
            var response1 = httpClient.SendAsync(request1).Result;
            HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/3")
            {
                Content = new StringContent(observation2Json, Encoding.UTF8, "application/json+fhir")
            };
            var response2 = httpClient.SendAsync(request2).Result;

            // Successful update (XML)
            string observation1Xml = FhirSerializer.SerializeResourceToXml(observation1);
            string observation2Xml = FhirSerializer.SerializeResourceToXml(observation2);

            HttpRequestMessage request3 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/2")
            {
                Content = new StringContent(observation1Xml, Encoding.UTF8, "application/xml+fhir")
            };
            var response3 = httpClient.SendAsync(request3).Result;
            HttpRequestMessage request4 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/3")
            {
                Content = new StringContent(observation2Xml, Encoding.UTF8, "application/xml+fhir")
            };
            var response4 = httpClient.SendAsync(request4).Result;

            Assert.AreEqual(HttpStatusCode.OK, response1.StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, response2.StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, response3.StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, response4.StatusCode);

            // Check that record entries are created correctly
            var recordResponse1 = httpClient.GetAsync(baseUrl + "/ObservationRecord/4").Result;
            var recordResponse2 = httpClient.GetAsync(baseUrl + "/ObservationRecord/5").Result;
            var recordResponse3 = httpClient.GetAsync(baseUrl + "/ObservationRecord/6").Result;
            var recordResponse4 = httpClient.GetAsync(baseUrl + "/ObservationRecord/7").Result;

            string record1 = recordResponse1.Content.ReadAsStringAsync().Result;
            string record2 = recordResponse2.Content.ReadAsStringAsync().Result;
            string record3 = recordResponse3.Content.ReadAsStringAsync().Result;
            string record4 = recordResponse4.Content.ReadAsStringAsync().Result;

            Assert.IsTrue(record1.Contains("\"ObservationId\":2"));
            Assert.IsTrue(record1.Contains("\"VersionId\":2"));
            Assert.IsTrue(record1.Contains("Action\":\"UPDATE"));
            Assert.IsTrue(record2.Contains("\"ObservationId\":3"));
            Assert.IsTrue(record2.Contains("\"VersionId\":2"));
            Assert.IsTrue(record2.Contains("Action\":\"UPDATE"));
            Assert.IsTrue(record3.Contains("\"ObservationId\":2"));
            Assert.IsTrue(record3.Contains("\"VersionId\":3"));
            Assert.IsTrue(record3.Contains("Action\":\"UPDATE"));
            Assert.IsTrue(record4.Contains("\"ObservationId\":3"));
            Assert.IsTrue(record4.Contains("\"VersionId\":3"));
            Assert.IsTrue(record4.Contains("Action\":\"UPDATE"));

            // Successful create(JSON)
            observation1.Id = "4";
            observation2.Id = "5";
            string observation1CreateJson = FhirSerializer.SerializeResourceToJson(observation1);
            string observation2CreateJson = FhirSerializer.SerializeResourceToJson(observation2);

            HttpRequestMessage request5 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/4")
            {
                Content = new StringContent(observation1CreateJson, Encoding.UTF8, "application/json+fhir")
            };
            var response5 = httpClient.SendAsync(request5).Result;
            HttpRequestMessage request6 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/5")
            {
                Content = new StringContent(observation2CreateJson, Encoding.UTF8, "application/json+fhir")
            };
            var response6 = httpClient.SendAsync(request6).Result;

            // Successful create(XML)
            observation1.Id = "6";
            observation2.Id = "7";
            string observation1CreateXml = FhirSerializer.SerializeResourceToXml(observation1);
            string observation2CreateXml = FhirSerializer.SerializeResourceToXml(observation2);

            HttpRequestMessage request7 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/6")
            {
                Content = new StringContent(observation1CreateXml, Encoding.UTF8, "application/xml+fhir")
            };
            var response7 = httpClient.SendAsync(request7).Result;
            HttpRequestMessage request8 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/7")
            {
                Content = new StringContent(observation2CreateXml, Encoding.UTF8, "application/xml+fhir")
            };
            var response8 = httpClient.SendAsync(request8).Result;

            Assert.AreEqual(HttpStatusCode.Created, response5.StatusCode);
            Assert.AreEqual(HttpStatusCode.Created, response6.StatusCode);
            Assert.AreEqual(HttpStatusCode.Created, response7.StatusCode);
            Assert.AreEqual(HttpStatusCode.Created, response8.StatusCode);

            // Check that record entries are created correctly
            var recordResponse5 = httpClient.GetAsync(baseUrl + "/ObservationRecord/8").Result;
            var recordResponse6 = httpClient.GetAsync(baseUrl + "/ObservationRecord/9").Result;
            var recordResponse7 = httpClient.GetAsync(baseUrl + "/ObservationRecord/10").Result;
            var recordResponse8 = httpClient.GetAsync(baseUrl + "/ObservationRecord/11").Result;

            string record5 = recordResponse5.Content.ReadAsStringAsync().Result;
            string record6 = recordResponse6.Content.ReadAsStringAsync().Result;
            string record7 = recordResponse7.Content.ReadAsStringAsync().Result;
            string record8 = recordResponse8.Content.ReadAsStringAsync().Result;

            Assert.IsTrue(record5.Contains("\"ObservationId\":4"));
            Assert.IsTrue(record5.Contains("\"VersionId\":1"));
            Assert.IsTrue(record5.Contains("Action\":\"CREATE"));
            Assert.IsTrue(record6.Contains("\"ObservationId\":5"));
            Assert.IsTrue(record6.Contains("\"VersionId\":1"));
            Assert.IsTrue(record6.Contains("Action\":\"CREATE"));
            Assert.IsTrue(record7.Contains("\"ObservationId\":6"));
            Assert.IsTrue(record7.Contains("\"VersionId\":1"));
            Assert.IsTrue(record7.Contains("Action\":\"CREATE"));
            Assert.IsTrue(record8.Contains("\"ObservationId\":7"));
            Assert.IsTrue(record8.Contains("\"VersionId\":1"));
            Assert.IsTrue(record8.Contains("Action\":\"CREATE"));

            // Case where wrong type of resource is provided
            string             device   = FhirSerializer.SerializeResourceToJson(MockedResources.Device1);
            HttpRequestMessage request9 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/8")
            {
                Content = new StringContent(device, Encoding.UTF8, "application/json+fhir")
            };
            var response9 = httpClient.SendAsync(request9).Result;

            Assert.AreEqual(HttpStatusCode.NotFound, response9.StatusCode);

            // Case where resource does not have logical ID
            observation1.Id = null;
            string             observation1NoId = FhirSerializer.SerializeResourceToXml(observation1);
            HttpRequestMessage request10        = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/8")
            {
                Content = new StringContent(observation1NoId, Encoding.UTF8, "application/xml+fhir")
            };
            var response10 = httpClient.SendAsync(request10).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, response10.StatusCode);

            // Case where resource ID ! input resource logical ID
            observation1.Id = "2";
            string             observation1NotEqualId = FhirSerializer.SerializeResourceToXml(observation1);
            HttpRequestMessage request11 = new HttpRequestMessage(HttpMethod.Put, baseUrl + "/Observation/11")
            {
                Content = new StringContent(observation1NotEqualId, Encoding.UTF8, "application/xml+fhir")
            };
            var response11 = httpClient.SendAsync(request11).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, response11.StatusCode);
        }
コード例 #27
0
 /// <summary>
 /// Gets all the management locks of a resource or any level below
 /// resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IManagementLockOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Optional. Query parameters. If empty is passed returns all locks at
 /// or below the resource.If atScope() is passed returns all locks at
 /// the resource level.
 /// </param>
 /// <returns>
 /// List of management locks.
 /// </returns>
 public static Task<ManagementLockListResult> ListAtResourceLevelAsync(this IManagementLockOperations operations, string resourceGroupName, ResourceIdentity identity, ManagementLockGetQueryParameter parameters)
 {
     return operations.ListAtResourceLevelAsync(resourceGroupName, identity, parameters, CancellationToken.None);
 }
コード例 #28
0
        public void StorageAccountGetOperationsTest()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (var context = UndoContext.Current)
            {
                context.Start();

                var resourcesClient = StorageManagementTestUtilities.GetResourceManagementClient(handler);

                var resource = new ResourceIdentity();
                resource.ResourceProviderNamespace = "Microsoft.Storage";
                resource.ResourceProviderApiVersion = "2015-06-15";
                resource.ResourceName = "";
                resource.ResourceType = "";
                var ops = resourcesClient.ResourceProviderOperationDetails.List(resource);

                Assert.Equal(ops.ResourceProviderOperationDetails.Count, 7);
            }
        }
コード例 #29
0
        public void ProviderOperationsList()
        {
            TestUtilities.StartTest();
            const string DefaultApiVersion = "2014-06-01";

            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var client           = GetResourceManagementClient(handler);
            var insightsProvider = client.Providers.Get(ProviderName);

            // Validate result
            Assert.True(insightsProvider != null);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            Assert.NotEmpty(insightsProvider.Provider.ResourceTypes);
            var            operationResourceType          = insightsProvider.Provider.ResourceTypes.Single(x => x.Name == "operations");
            IList <string> operationsSupportedApiVersions = operationResourceType.ApiVersions;
            string         latestSupportedApiVersion      = DefaultApiVersion;

            if (operationsSupportedApiVersions != null && operationsSupportedApiVersions.Any())
            {
                latestSupportedApiVersion = operationsSupportedApiVersions.First();
            }

            ResourceIdentity identity = new ResourceIdentity
            {
                ResourceName = string.Empty,
                ResourceType = "operations",
                ResourceProviderNamespace  = ProviderName,
                ResourceProviderApiVersion = latestSupportedApiVersion
            };

            var operations = client.ResourceProviderOperationDetails.List(identity);

            Assert.NotNull(operations);
            Assert.NotEmpty(operations.ResourceProviderOperationDetails);
            Assert.NotEmpty(operations.ResourceProviderOperationDetails[0].Name);
            Assert.NotNull(operations.ResourceProviderOperationDetails[0].ResourceProviderOperationDisplayProperties);
            IEnumerable <ResourceProviderOperationDefinition> definitions =
                operations.ResourceProviderOperationDetails.Where(op => string.Equals(op.Name, "Microsoft.Insights/AlertRules/Write", StringComparison.InvariantCultureIgnoreCase));

            Assert.NotNull(definitions);
            Assert.NotEmpty(definitions);
            Assert.Equal(1, definitions.Count());

            // Negative case with unsupported api version
            identity = new ResourceIdentity
            {
                ResourceName = string.Empty,
                ResourceType = "operations",
                ResourceProviderNamespace  = ProviderName,
                ResourceProviderApiVersion = "2015-01-01"
            };

            Assert.Throws <Hyak.Common.CloudException>(() => client.ResourceProviderOperationDetails.List(identity));
            TestUtilities.EndTest();
        }
 /// <summary>
 /// Gets role assignments of the resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IRoleAssignmentOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Optional. List operation filters. If null will return all role
 /// assignments at, above or below the resource.
 /// </param>
 /// <returns>
 /// Role assignment list operation result.
 /// </returns>
 public static RoleAssignmentListResult ListForResource(this IRoleAssignmentOperations operations, string resourceGroupName, ResourceIdentity identity, ListAssignmentsFilterParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IRoleAssignmentOperations)s).ListForResourceAsync(resourceGroupName, identity, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
コード例 #31
0
        public void TestDeserializerInvalidNullType()
        {
            var identityJsonProperty = DeserializerHelper("InvalidTypeIsNull.json");

            Assert.Throws <InvalidOperationException>(delegate { ResourceIdentity.DeserializeResourceIdentity(identityJsonProperty.Value); });
        }
 /// <summary>
 /// Gets role assignments of the resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IRoleAssignmentOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Optional. List operation filters. If null will return all role
 /// assignments at, above or below the resource.
 /// </param>
 /// <returns>
 /// Role assignment list operation result.
 /// </returns>
 public static Task<RoleAssignmentListResult> ListForResourceAsync(this IRoleAssignmentOperations operations, string resourceGroupName, ResourceIdentity identity, ListAssignmentsFilterParameters parameters)
 {
     return operations.ListForResourceAsync(resourceGroupName, identity, parameters, CancellationToken.None);
 }
コード例 #33
0
        internal static GenericResourceData DeserializeGenericResource(JsonElement element)
        {
            Optional <DateTimeOffset>   createdTime       = default;
            Optional <DateTimeOffset>   changedTime       = default;
            Optional <string>           provisioningState = default;
            Optional <Plan>             plan              = default;
            Optional <object>           properties        = default;
            Optional <string>           kind              = default;
            Optional <string>           managedBy         = default;
            Optional <Sku>              sku               = default;
            Optional <ResourceIdentity> identity          = default;
            Optional <string>           id                = default;
            Optional <string>           name              = default;
            Optional <string>           type              = default;
            Optional <string>           location          = default;
            Optional <IDictionary <string, string> > tags = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("createdTime"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    createdTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("changedTime"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    changedTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("provisioningState"))
                {
                    provisioningState = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("plan"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    plan = Plan.DeserializePlan(property.Value);
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    properties = property.Value.GetObject();
                    continue;
                }
                if (property.NameEquals("kind"))
                {
                    kind = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("managedBy"))
                {
                    managedBy = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    sku = Sku.DeserializeSku(property.Value);
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = ResourceIdentity.DeserializeResourceIdentity(property.Value);
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
            }
            return(new GenericResourceData(id.Value, name.Value, type.Value, location.Value, Optional.ToDictionary(tags), plan.Value, properties.Value, kind.Value, managedBy.Value, sku.Value, identity.Value, Optional.ToNullable(createdTime), Optional.ToNullable(changedTime), provisioningState.Value));
        }
コード例 #34
0
ファイル: FhirService.cs プロジェクト: HowardEdidin/spark
        private BundleEntry findEntry(string collection, string id)
        {
            Uri location = ResourceIdentity.Build(collection, id);

            return(_store.FindEntryById(location));
        }
コード例 #35
0
ファイル: CreatePingWebTest.cs プロジェクト: cnq/insights-poc
        private static GenericResourceExtended CreateOrUpdateWebTest(
            ResourceManagementClient resourceClient, 
            string resourceGroupName, 
            string insightsResourceUri, 
            string webTestName, 
            string webTestUrl,
            string location)
        {
            string insightsResourceName = GetNameFromUri(insightsResourceUri);
            string webTestMonitorId = string.Format("{0}-{1}", webTestName, insightsResourceName);

            var webTestResourceIdentity = new ResourceIdentity(
                webTestMonitorId,
                "microsoft.insights/webtests",
                "2015-05-01");

            var webTestResource = new GenericResource(location)
            {
                Properties = new PingWebTestProperties
                {
                    Name = webTestName,
                    SyntheticMonitorId = webTestMonitorId,
                    Enabled = true,
                    Configuration = new PingWebTestConfiguration(webTestUrl),
                    Locations = { WebTestLocations.USSanAntonioTX },
                    RetryEnabled = true
                },
                Tags =
                {
                    { string.Format("hidden-link:{0}", insightsResourceUri), "Resource" }
                }
            };

            var webTestResourceCreateOrUpdateResult = resourceClient.Resources.CreateOrUpdateAsync(
                resourceGroupName,
                webTestResourceIdentity,
                webTestResource).Result;

            if (webTestResourceCreateOrUpdateResult.StatusCode != HttpStatusCode.Created && webTestResourceCreateOrUpdateResult.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException(
                    string.Format("Unable to create resource '{0}' (HTTP Status Code: {1}).",
                    insightsResourceName,
                    webTestResourceCreateOrUpdateResult.StatusCode));
            }

            return webTestResourceCreateOrUpdateResult.Resource;
        }
コード例 #36
0
        /// <summary>
        /// Initializes the target. Can be used by inheriting classes
        /// to initialize logging.
        /// </summary>
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

            string connectionString = string.Empty;
            string serviceUri       = string.Empty;
            string tenantIdentity   = string.Empty;
            string resourceIdentity = string.Empty;

            Dictionary <string, string> blobMetadata = null;
            Dictionary <string, string> blobTags     = null;

            var defaultLogEvent = LogEventInfo.CreateNullEvent();

            try
            {
                connectionString = ConnectionString?.Render(defaultLogEvent);
                if (string.IsNullOrEmpty(connectionString))
                {
                    serviceUri       = ServiceUri?.Render(defaultLogEvent);
                    tenantIdentity   = TenantIdentity?.Render(defaultLogEvent);
                    resourceIdentity = ResourceIdentity?.Render(defaultLogEvent);
                }

                if (BlobMetadata?.Count > 0)
                {
                    blobMetadata = new Dictionary <string, string>();
                    foreach (var metadata in BlobMetadata)
                    {
                        if (string.IsNullOrWhiteSpace(metadata.Name))
                        {
                            continue;
                        }

                        var metadataValue = metadata.Layout?.Render(defaultLogEvent);
                        if (string.IsNullOrEmpty(metadataValue))
                        {
                            continue;
                        }

                        blobMetadata[metadata.Name.Trim()] = metadataValue;
                    }
                }

                if (BlobTags?.Count > 0)
                {
                    blobTags = new Dictionary <string, string>();
                    foreach (var tag in BlobTags)
                    {
                        if (string.IsNullOrWhiteSpace(tag.Name))
                        {
                            continue;
                        }

                        var metadataValue = tag.Layout?.Render(defaultLogEvent);
                        blobTags[tag.Name.Trim()] = metadataValue ?? string.Empty;
                    }
                }

                _cloudBlobService.Connect(connectionString, serviceUri, tenantIdentity, resourceIdentity, blobMetadata, blobTags);
                InternalLogger.Trace("AzureBlobStorageTarget - Initialized");
            }
            catch (Exception ex)
            {
                if (string.IsNullOrEmpty(connectionString) && !string.IsNullOrEmpty(serviceUri))
                {
                    InternalLogger.Error(ex, "AzureBlobStorageTarget(Name={0}): Failed to create BlobClient with ServiceUri={1}.", Name, serviceUri);
                }
                else
                {
                    InternalLogger.Error(ex, "AzureBlobStorageTarget(Name={0}): Failed to create BlobClient with connectionString={1}.", Name, connectionString);
                }
                throw;
            }
        }
コード例 #37
0
 /// <summary>
 /// Checks whether resource exists.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// Resource group information.
 /// </returns>
 public static Task<ResourceExistsResult> CheckExistenceAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return operations.CheckExistenceAsync(resourceGroupName, identity, CancellationToken.None);
 }
コード例 #38
0
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <returns>System.Int32.</returns>
        public override int Execute(Arguments arguments)
        {
            // Get us the needed parameters first
            //
            var url = arguments["url"];

            var name      = arguments["name"];
            var firstname = arguments["firstname"];
            var gender    = arguments["gender"];
            var dob       = arguments["dob"];
            var phone     = arguments["phone"];
            var email     = arguments["email"];

            // Create an in-memory representation of a Patient resource

            var patient = new Patient();

            if (!(String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(firstname)))
            {
                patient.Name = new List <HumanName>();
                patient.Name.Add(HumanName.ForFamily(name).WithGiven(firstname));
            }

            if (!String.IsNullOrEmpty(gender))
            {
                patient.Gender = new CodeableConcept("http://dummy.org/gender", gender, gender);
            }

            if (!String.IsNullOrEmpty(dob))
            {
                var birthdate = DateTime.ParseExact(dob, "dd/MM/yyyy", new CultureInfo("en-US"));
                patient.BirthDate = birthdate.ToString("s");
            }

            patient.Telecom = new List <Contact>();
            if (!String.IsNullOrEmpty(phone))
            {
                patient.Telecom.Add(new Contact()
                {
                    Value  = phone,
                    System = Contact.ContactSystem.Phone,
                    Use    = Contact.ContactUse.Home
                });
            }

            if (!String.IsNullOrEmpty(email))
            {
                patient.Telecom.Add(new Contact()
                {
                    Value  = email,
                    System = Contact.ContactSystem.Email,
                    Use    = Contact.ContactUse.Home
                });
            }


            try
            {
                var client = new FhirClient(url);
                var entry  = client.Create(patient);

                if (entry == null)
                {
                    Console.WriteLine("Couldn not register patient on server {0}", url);
                    return(1);
                }

                var identity = new ResourceIdentity(entry.Id);
                ID = identity.Id;

                Console.WriteLine("Registered patient {0} on server {1}", ID, url);
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
        }
コード例 #39
0
 /// <summary>
 /// Create a resource.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <param name='parameters'>
 /// Required. Create or update resource parameters.
 /// </param>
 /// <returns>
 /// Resource information.
 /// </returns>
 public static Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, GenericResource parameters)
 {
     return operations.CreateOrUpdateAsync(resourceGroupName, identity, parameters, CancellationToken.None);
 }
コード例 #40
0
 internal GenericResourceData(string id, string name, string type, string location, IDictionary <string, string> tags, Plan plan, object properties, string kind, string managedBy, Sku sku, ResourceIdentity identity) : base(id, name, type, location, tags)
 {
     Plan       = plan;
     Properties = properties;
     Kind       = kind;
     ManagedBy  = managedBy;
     Sku        = sku;
     Identity   = identity;
 }
コード例 #41
0
 /// <summary>
 /// Delete resource and all of its resources.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Resources.IResourceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// A standard service response including an HTTP status code and
 /// request ID.
 /// </returns>
 public static Task<AzureOperationResponse> DeleteAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return operations.DeleteAsync(resourceGroupName, identity, CancellationToken.None);
 }
コード例 #42
0
 internal ExpressRoutePortData(string id, string name, string type, string location, IDictionary <string, string> tags, string etag, ResourceIdentity identity, string peeringLocation, int?bandwidthInGbps, float?provisionedBandwidthInGbps, string mtu, ExpressRoutePortsEncapsulation?encapsulation, string etherType, string allocationDate, IList <ExpressRouteLink> links, IReadOnlyList <Models.SubResource> circuits, ProvisioningState?provisioningState, string resourceGuid) : base(id, name, type, location, tags)
 {
     Etag                       = etag;
     Identity                   = identity;
     PeeringLocation            = peeringLocation;
     BandwidthInGbps            = bandwidthInGbps;
     ProvisionedBandwidthInGbps = provisionedBandwidthInGbps;
     Mtu               = mtu;
     Encapsulation     = encapsulation;
     EtherType         = etherType;
     AllocationDate    = allocationDate;
     Links             = links;
     Circuits          = circuits;
     ProvisioningState = provisioningState;
     ResourceGuid      = resourceGuid;
 }
コード例 #43
0
        public void UpdateSystemAssignedToUserAssigned()
        {
            var resourceGroupName = TestUtilities.GenerateName("SdkRg");
            var jobName           = TestUtilities.GenerateName("SdkJob");
            //var jobName = "SdkJob5929";
            ContactDetails  contactDetails          = GetDefaultContactDetails();
            ShippingAddress shippingAddress         = GetDefaultShippingAddress();
            Sku             sku                     = GetDefaultSku();
            var             destinationAccountsList = new List <StorageAccountDetails>
            {
                new StorageAccountDetails
                {
                    StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2"
                }
            };
            JobDetails jobDetails = new DataBoxJobDetails
            {
                ContactDetails  = contactDetails,
                ShippingAddress = shippingAddress
            };

            jobDetails.DataImportDetails = new List <DataImportDetails>();
            jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault()));

            var jobResource = new JobResource
            {
                Sku      = sku,
                Location = TestConstants.DefaultResourceLocation,
                Details  = jobDetails,
            };

            this.RMClient.ResourceGroups.CreateOrUpdate(
                resourceGroupName,
                new ResourceGroup
            {
                Location = TestConstants.DefaultResourceLocation
            });

            var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource);

            ValidateJobWithoutDetails(jobName, sku, job);
            Assert.Equal(StageName.DeviceOrdered, job.Status);

            // Set Msi details.
            string tenantId     = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            string identityType = "SystemAssigned";
            var    identity     = new ResourceIdentity(identityType, Guid.NewGuid().ToString(), tenantId);
            var    updateParams = new JobResourceUpdateParameter
            {
                Identity = identity
            };

            var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams);

            ValidateJobWithoutDetails(jobName, sku, updateJob);

            var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details);

            ValidateJobWithoutDetails(jobName, sku, job);
            ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled);

            Assert.Equal(StageName.DeviceOrdered, updateJob.Status);
            Assert.Equal(identityType, updateJob.Identity.Type);

            //Updating to User Assigned
            var uaiId            = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sdkIdentity";
            var keyEncryptionKey = new KeyEncryptionKey(KekType.CustomerManaged)
            {
                KekUrl             = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/",
                KekVaultResourceID =
                    "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault",
                IdentityProperties = new IdentityProperties
                {
                    Type         = "UserAssigned",
                    UserAssigned = new UserAssignedProperties {
                        ResourceId = uaiId
                    }
                }
            };

            UserAssignedIdentity uid = new UserAssignedIdentity();

            identity = new ResourceIdentity//ResourceIdentity checked by auto mapper
            {
                Type = "SystemAssigned,UserAssigned",
                UserAssignedIdentities = new Dictionary <string, UserAssignedIdentity>
                {
                    { uaiId, uid }
                },
            };

            var details = new UpdateJobDetails
            {
                KeyEncryptionKey = keyEncryptionKey
            };

            updateParams = new JobResourceUpdateParameter
            {
                Details  = details,
                Identity = identity
            };

            updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams);
            ValidateJobWithoutDetails(jobName, sku, updateJob);
            getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details);
            ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled);
            Assert.Equal(StageName.DeviceOrdered, getJob.Status);
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].ClientId));
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].PrincipalId));
        }
コード例 #44
0
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <returns>System.Int32.</returns>
        /// <remarks>N/A</remarks>
        public override int Execute(Arguments arguments)
        {
            // Get us the needed parameters first
            //
            var url = arguments["url"];
            var id  = arguments["id"];

            var name      = arguments["name"];
            var firstname = arguments["firstname"];
            var gender    = arguments["gender"];
            var dob       = arguments["dob"];
            var phone     = arguments["phone"];
            var email     = arguments["email"];


            // Try to retrieve patient from server and update it
            try
            {
                // Get patient representation from server
                //
                #region retrieve patient
                var client   = new FhirClient(url);
                var identity = ResourceIdentity.Build("Patient", id);
                var entry    = client.Read(identity) as ResourceEntry <Patient>;

                var patient = entry.Resource as Patient;
                if (patient == null)
                {
                    Console.WriteLine("Could not retrieve patient {0} from server {1}", id, url);
                    return(1);
                }
                #endregion

                // We have the patient now modify local representation
                //
                #region prepare patient update
                if (!(String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(firstname)))
                {
                    patient.Name = new List <HumanName>();
                    patient.Name.Add(HumanName.ForFamily(name).WithGiven(firstname));
                }

                if (!String.IsNullOrEmpty(gender))
                {
                    patient.Gender = new CodeableConcept("http://dummy.org/gender", gender, gender);
                }

                if (!String.IsNullOrEmpty(dob))
                {
                    var birthdate = DateTime.ParseExact(dob, "dd/MM/yyyy", new CultureInfo("en-US"));
                    patient.BirthDate = birthdate.ToString("s");
                }

                patient.Telecom = new List <Contact>();
                if (!String.IsNullOrEmpty(phone))
                {
                    patient.Telecom.Add(new Contact()
                    {
                        Value  = phone,
                        System = Contact.ContactSystem.Phone,
                        Use    = Contact.ContactUse.Home
                    });
                }

                if (!String.IsNullOrEmpty(email))
                {
                    patient.Telecom.Add(new Contact()
                    {
                        Value  = email,
                        System = Contact.ContactSystem.Email,
                        Use    = Contact.ContactUse.Home
                    });
                }
                #endregion

                // Finally send the update to the server
                //
                #region do patient update
                entry.Resource = patient;
                client.Update(entry, false);
                Console.WriteLine("Patient {0} updated on server {1}", id, url);
                return(0);

                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
        }
コード例 #45
0
        public void ResourceGetCreateOrUpdateDeleteAndExistsThrowExceptionWithoutApiVersion()
        {
            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetResourceManagementClient(handler);

            var identity = new ResourceIdentity
            {
                ResourceName = "site3",
                ResourceProviderNamespace = "Microsoft.Web",
                ResourceProviderApiVersion = null,
                ResourceType = "sites",
            };

            var resource = new GenericResource
            {
                Location = "South Central US",
                Properties = @"{
                                'name':'site3',
	                            'siteMode': 'Standard',
                                'computeMode':'Dedicated'
                            }"
            };


            Assert.Throws<ArgumentNullException>(() => client.Resources.Get("foo",
                identity));
            Assert.Throws<ArgumentNullException>(() => client.Resources.CheckExistence("foo",
                identity));
            Assert.Throws<ArgumentNullException>(() => client.Resources.CreateOrUpdate("foo",
                identity, resource));
            Assert.Throws<ArgumentNullException>(() => client.Resources.Delete("foo",
                identity));
        }
コード例 #46
0
        public void ProviderOperationsList()
        {
            TestUtilities.StartTest();
            const string DefaultApiVersion = "2014-06-01";

            var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetResourceManagementClient(handler);
            var insightsProvider = client.Providers.Get(ProviderName);

            // Validate result
            Assert.True(insightsProvider != null);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            Assert.NotEmpty(insightsProvider.Provider.ResourceTypes);
            var operationResourceType = insightsProvider.Provider.ResourceTypes.Single(x => x.Name == "operations");
            IList<string> operationsSupportedApiVersions = operationResourceType.ApiVersions;
            string latestSupportedApiVersion = DefaultApiVersion;
            
            if (operationsSupportedApiVersions != null && operationsSupportedApiVersions.Any())
            {
                latestSupportedApiVersion = operationsSupportedApiVersions.First();
            }

            ResourceIdentity identity = new ResourceIdentity
            {
                ResourceName = string.Empty,
                ResourceType = "operations",
                ResourceProviderNamespace = ProviderName,
                ResourceProviderApiVersion = latestSupportedApiVersion
            };

            var operations = client.ResourceProviderOperationDetails.List(identity);

            Assert.NotNull(operations);
            Assert.NotEmpty(operations.ResourceProviderOperationDetails);
            Assert.NotEmpty(operations.ResourceProviderOperationDetails[0].Name);
            Assert.NotNull(operations.ResourceProviderOperationDetails[0].ResourceProviderOperationDisplayProperties);
            IEnumerable<ResourceProviderOperationDefinition> definitions =
                operations.ResourceProviderOperationDetails.Where(op => string.Equals(op.Name, "Microsoft.Insights/AlertRules/Write", StringComparison.InvariantCultureIgnoreCase));
            Assert.NotNull(definitions);
            Assert.NotEmpty(definitions);
            Assert.Equal(1, definitions.Count());

            // Negative case with unsupported api version
            identity = new ResourceIdentity
            {
                ResourceName = string.Empty,
                ResourceType = "operations",
                ResourceProviderNamespace = ProviderName,
                ResourceProviderApiVersion = "2015-01-01"
            };

            Assert.Throws<Hyak.Common.CloudException>(() => client.ResourceProviderOperationDetails.List(identity));
            TestUtilities.EndTest();
        }
コード例 #47
0
        public void QueueNewDeletedEntry(string collection, string id)
        {
            var location = ResourceIdentity.Build(_endpoint, collection, id);

            QueueNewDeletedEntry(location);
        }
コード例 #48
0
        public static ActionResponse RegisterKeyVault(ActionRequest request)
        {
            string azureToken     = request.DataStore.GetJson("AzureToken", "access_token");
            string subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId");
            string resourceGroup  = request.DataStore.GetValue("SelectedResourceGroup");

            // Make sure the Key Vault is registered
            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscriptionId, azureToken);

            using (ResourceManagementClient managementClient = new ResourceManagementClient(creds))
            {
                ProviderListResult providersResult = managementClient.Providers.List(null);

                bool kvExists = false;
                foreach (var p in providersResult.Providers)
                {
                    if (p.Namespace.EqualsIgnoreCase("Microsoft.KeyVault"))
                    {
                        kvExists = p.RegistrationState.EqualsIgnoreCase("Registered");
                        break;
                    }
                }

                AzureOperationResponse operationResponse;
                if (!kvExists)
                {
                    operationResponse = managementClient.Providers.Register("Microsoft.KeyVault");
                    if (operationResponse.StatusCode != System.Net.HttpStatusCode.OK && operationResponse.StatusCode != System.Net.HttpStatusCode.Accepted)
                    {
                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv"));
                    }

                    Thread.Sleep(10000); // Wait for it to register
                }

                string oid;
                string tenantID;
                ExtractUserandTenant(azureToken, out oid, out tenantID);

                const string    vaultApiVersion = "2015-06-01";
                string          tempVaultName   = "bpst-" + RandomGenerator.GetRandomLowerCaseCharacters(12);
                GenericResource genRes          = new GenericResource("westus")
                {
                    Properties = "{\"sku\": { \"family\": \"A\", \"name\": \"Standard\" }, \"tenantId\": \"" + tenantID + "\", \"accessPolicies\": [], \"enabledForDeployment\": true }"
                };

                operationResponse = managementClient.Resources.CreateOrUpdate(resourceGroup, new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion), genRes);
                bool operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted);
                Thread.Sleep(15000); // The created vault has an Url. DNS propagation will take a while

                if (operationSucceeded)
                {
                    ResourceIdentity resIdent = new ResourceIdentity(tempVaultName, "Microsoft.KeyVault/vaults", vaultApiVersion);
                    operationResponse  = managementClient.Resources.Delete(resourceGroup, resIdent);
                    operationSucceeded = (operationResponse.StatusCode == System.Net.HttpStatusCode.OK) || (operationResponse.StatusCode == System.Net.HttpStatusCode.Accepted);
                }

                if (!operationSucceeded)
                {
                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "MsCrm_ErrorRegisterKv"));
                }

                return(new ActionResponse(ActionStatus.Success));
            }
        }
コード例 #49
0
 internal VirtualMachineData(ResourceIdentifier id, string name, ResourceType type, IDictionary <string, string> tags, Location location, Models.Plan plan, IReadOnlyList <VirtualMachineExtensionData> resources, ResourceIdentity identity, IList <string> zones, ExtendedLocation extendedLocation, HardwareProfile hardwareProfile, StorageProfile storageProfile, AdditionalCapabilities additionalCapabilities, OSProfile osProfile, NetworkProfile networkProfile, SecurityProfile securityProfile, DiagnosticsProfile diagnosticsProfile, Models.SubResource availabilitySet, Models.SubResource virtualMachineScaleSet, Models.SubResource proximityPlacementGroup, VirtualMachinePriorityTypes?priority, VirtualMachineEvictionPolicyTypes?evictionPolicy, BillingProfile billingProfile, Models.SubResource host, Models.SubResource hostGroup, string provisioningState, VirtualMachineInstanceView instanceView, string licenseType, string vmId, string extensionsTimeBudget, int?platformFaultDomain, ScheduledEventsProfile scheduledEventsProfile, string userData) : base(id, name, type, tags, location)
 {
     Plan                    = plan;
     Resources               = resources;
     Identity                = identity;
     Zones                   = zones;
     ExtendedLocation        = extendedLocation;
     HardwareProfile         = hardwareProfile;
     StorageProfile          = storageProfile;
     AdditionalCapabilities  = additionalCapabilities;
     OsProfile               = osProfile;
     NetworkProfile          = networkProfile;
     SecurityProfile         = securityProfile;
     DiagnosticsProfile      = diagnosticsProfile;
     AvailabilitySet         = availabilitySet;
     VirtualMachineScaleSet  = virtualMachineScaleSet;
     ProximityPlacementGroup = proximityPlacementGroup;
     Priority                = priority;
     EvictionPolicy          = evictionPolicy;
     BillingProfile          = billingProfile;
     Host                    = host;
     HostGroup               = hostGroup;
     ProvisioningState       = provisioningState;
     InstanceView            = instanceView;
     LicenseType             = licenseType;
     VmId                    = vmId;
     ExtensionsTimeBudget    = extensionsTimeBudget;
     PlatformFaultDomain     = platformFaultDomain;
     ScheduledEventsProfile  = scheduledEventsProfile;
     UserData                = userData;
 }
コード例 #50
0
        /// <summary>
        /// Gets a resource permissions.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group. The name is case
        /// insensitive.
        /// </param>
        /// <param name='identity'>
        /// Required. Resource
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Permissions information.
        /// </returns>
        public async Task <PermissionGetResult> ListForResourceAsync(string resourceGroupName, ResourceIdentity identity, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            if (identity.ResourceName == null)
            {
                throw new ArgumentNullException("identity.");
            }
            if (identity.ResourceProviderNamespace == null)
            {
                throw new ArgumentNullException("identity.");
            }
            if (identity.ResourceType == null)
            {
                throw new ArgumentNullException("identity.");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("identity", identity);
                TracingAdapter.Enter(invocationId, this, "ListForResourceAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourcegroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            url = url + Uri.EscapeDataString(identity.ResourceProviderNamespace);
            url = url + "/";
            if (identity.ParentResourcePath != null)
            {
                url = url + identity.ParentResourcePath;
            }
            url = url + "/";
            url = url + identity.ResourceType;
            url = url + "/";
            url = url + Uri.EscapeDataString(identity.ResourceName);
            url = url + "/providers/Microsoft.Authorization/permissions";
            List <string> queryParameters = new List <string>();

            queryParameters.Add(APIVersion);
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    PermissionGetResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new PermissionGetResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Permission permissionInstance = new Permission();
                                    result.Permissions.Add(permissionInstance);

                                    JToken actionsArray = valueValue["actions"];
                                    if (actionsArray != null && actionsArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken actionsValue in ((JArray)actionsArray))
                                        {
                                            permissionInstance.Actions.Add(((string)actionsValue));
                                        }
                                    }

                                    JToken notActionsArray = valueValue["notActions"];
                                    if (notActionsArray != null && notActionsArray.Type != JTokenType.Null)
                                    {
                                        foreach (JToken notActionsValue in ((JArray)notActionsArray))
                                        {
                                            permissionInstance.NotActions.Add(((string)notActionsValue));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
コード例 #51
0
        /// <summary>
        /// Retrieve the set of appointments that have mobile numbers with a status of booked, arrived, or fulfilled
        /// And attach the processing status data from local storage too
        /// </summary>
        /// <param name="model"></param>
        public async System.Threading.Tasks.Task <List <PmsAppointment> > SearchAppointments(DateTime date, IList <DoctorRoomLabelMapping> roomMappings, IArrivalsLocalStorage storage)
        {
            List <PmsAppointment> results = new List <PmsAppointment>();

            var server = GetServerConnection();

            if (server == null)
            {
                return(null);
            }

            var criteria = new SearchParams();

            criteria.Add("date", date.Date.ToString("yyyy-MM-dd"));
            criteria.Include.Add("Appointment:actor");
            var bundle = await server.SearchAsync <Appointment>(criteria);

            // Debugging
            var doc = System.Xml.Linq.XDocument.Parse(new Hl7.Fhir.Serialization.FhirXmlSerializer().SerializeToString(bundle));
            // Console.WriteLine(doc.ToString(System.Xml.Linq.SaveOptions.None));

            Func <ResourceReference, System.Threading.Tasks.Task <Resource> > resolveReference = async(reference) =>
            {
                if (string.IsNullOrEmpty(reference.Reference))
                {
                    return(null);
                }
                ResourceIdentity ri = new ResourceIdentity(reference.Reference);
                var resource        = bundle.Entry.FirstOrDefault(e => e.Resource.ResourceType.GetLiteral() == ri.ResourceType && e.Resource.Id == ri.Id)?.Resource;
                if (resource == null)
                {
                    // wasn't returned in the bundle, so go searching for it
                    resource = await server.ReadAsync <Resource>(reference.Reference);
                }
                return(resource);
            };

            foreach (var entry in bundle.Entry.Select(e => e.Resource as Appointment).Where(e => e != null))
            {
                PmsAppointment appt = null;
                if (entry.Status == Appointment.AppointmentStatus.Booked ||
                    entry.Status == Appointment.AppointmentStatus.Arrived ||
                    entry.Status == Appointment.AppointmentStatus.Fulfilled)
                {
                    appt = await ToPmsAppointment(entry, resolveReference);

                    if (appt != null)
                    {
                        if (!string.IsNullOrEmpty(appt.PatientMobilePhone))
                        {
                            results.Add(appt);

                            // Check if the practitioner has a mapping already
                            if (!roomMappings.Any(m => m.PractitionerFhirID == appt.PractitionerFhirID))
                            {
                                // Add in an empty room mapping
                                roomMappings.Add(new DoctorRoomLabelMapping()
                                {
                                    PractitionerFhirID = appt.PractitionerFhirID,
                                    PractitionerName   = appt.PractitionerName
                                });
                            }

                            // And read in the extended content from storage
                            await storage.LoadAppointmentStatus(appt);
                        }
                    }
                }
            }
            return(results);
        }
コード例 #52
0
 internal VirtualMachineScaleSetData(ResourceIdentifier id, string name, ResourceType type, IDictionary <string, string> tags, Location location, Models.Sku sku, Models.Plan plan, ResourceIdentity identity, IList <string> zones, ExtendedLocation extendedLocation, UpgradePolicy upgradePolicy, AutomaticRepairsPolicy automaticRepairsPolicy, VirtualMachineScaleSetVMProfile virtualMachineProfile, string provisioningState, bool?overprovision, bool?doNotRunExtensionsOnOverprovisionedVMs, string uniqueId, bool?singlePlacementGroup, bool?zoneBalance, int?platformFaultDomainCount, WritableSubResource proximityPlacementGroup, WritableSubResource hostGroup, AdditionalCapabilities additionalCapabilities, ScaleInPolicy scaleInPolicy, OrchestrationMode?orchestrationMode) : base(id, name, type, tags, location)
 {
     Sku                    = sku;
     Plan                   = plan;
     Identity               = identity;
     Zones                  = zones;
     ExtendedLocation       = extendedLocation;
     UpgradePolicy          = upgradePolicy;
     AutomaticRepairsPolicy = automaticRepairsPolicy;
     VirtualMachineProfile  = virtualMachineProfile;
     ProvisioningState      = provisioningState;
     Overprovision          = overprovision;
     DoNotRunExtensionsOnOverprovisionedVMs = doNotRunExtensionsOnOverprovisionedVMs;
     UniqueId                 = uniqueId;
     SinglePlacementGroup     = singlePlacementGroup;
     ZoneBalance              = zoneBalance;
     PlatformFaultDomainCount = platformFaultDomainCount;
     ProximityPlacementGroup  = proximityPlacementGroup;
     HostGroup                = hostGroup;
     AdditionalCapabilities   = additionalCapabilities;
     ScaleInPolicy            = scaleInPolicy;
     OrchestrationMode        = orchestrationMode;
 }
コード例 #53
0
        public void CreateResourceWithPlan()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };

            using (UndoContext context = UndoContext.Current)
            {

                context.Start();
                string groupName = TestUtilities.GenerateName("csmrg");
                string resourceName = TestUtilities.GenerateName("csmr");
                var client = GetResourceManagementClient(handler);
                string mySqlLocation = GetMySqlLocation(client);
                var groupIdentity = new ResourceIdentity
                    {
                        ResourceName = resourceName,
                        ResourceProviderNamespace = "SuccessBricks.ClearDB",
                        ResourceType = "databases",
                        ResourceProviderApiVersion = StoreResourceProviderVersion
                    };

                client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));

                client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
                var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity,
                    new GenericResource
                    {
                        Location = mySqlLocation,
                        Plan = new Plan {Name = "Free"},
                        Tags = new Dictionary<string, string> { { "provision_source", "RMS" } }
                    }
                );

                Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode);
                Assert.Equal(resourceName, createOrUpdateResult.Resource.Name);
                Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Resource.Location),
                    string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Resource.Location, mySqlLocation));
                Assert.NotNull(createOrUpdateResult.Resource.Plan);
                Assert.Equal("Free", createOrUpdateResult.Resource.Plan.Name);

                var getResult = client.Resources.Get(groupName, groupIdentity);

                Assert.Equal(HttpStatusCode.OK, getResult.StatusCode);
                Assert.Equal(resourceName, getResult.Resource.Name);
                Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Resource.Location),
                    string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Resource.Location, mySqlLocation));
                Assert.NotNull(getResult.Resource.Plan);
                Assert.Equal("Free", getResult.Resource.Plan.Name);
            }
        }
コード例 #54
0
 internal FirewallPolicyData(string id, string name, string type, string location, IDictionary <string, string> tags, string etag, ResourceIdentity identity, IReadOnlyList <Models.SubResource> ruleCollectionGroups, ProvisioningState?provisioningState, Models.SubResource basePolicy, IReadOnlyList <Models.SubResource> firewalls, IReadOnlyList <Models.SubResource> childPolicies, AzureFirewallThreatIntelMode?threatIntelMode, FirewallPolicyThreatIntelWhitelist threatIntelWhitelist, FirewallPolicyInsights insights, FirewallPolicySnat snat, DnsSettings dnsSettings, FirewallPolicyIntrusionDetection intrusionDetection, FirewallPolicyTransportSecurity transportSecurity, FirewallPolicySku sku) : base(id, name, type, location, tags)
 {
     Etag                 = etag;
     Identity             = identity;
     RuleCollectionGroups = ruleCollectionGroups;
     ProvisioningState    = provisioningState;
     BasePolicy           = basePolicy;
     Firewalls            = firewalls;
     ChildPolicies        = childPolicies;
     ThreatIntelMode      = threatIntelMode;
     ThreatIntelWhitelist = threatIntelWhitelist;
     Insights             = insights;
     Snat                 = snat;
     DnsSettings          = dnsSettings;
     IntrusionDetection   = intrusionDetection;
     TransportSecurity    = transportSecurity;
     Sku = sku;
 }
 /// <summary>
 /// Gets a list of resource providers.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Internal.Resources.IResourceProviderOperationDetailsOperations.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource identity.
 /// </param>
 /// <returns>
 /// List of resource provider operations.
 /// </returns>
 public static Task<ResourceProviderOperationDetailListResult> ListAsync(this IResourceProviderOperationDetailsOperations operations, ResourceIdentity identity)
 {
     return operations.ListAsync(identity, CancellationToken.None);
 }
コード例 #56
0
        /// <summary>
        /// Creates a new resource.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created resource</returns>
        public virtual PSResource CreatePSResource(CreatePSResourceParameters parameters)
        {
            ResourceIdentity resourceIdentity = parameters.ToResourceIdentity();

            if (ResourceManagementClient.ResourceGroups.CheckExistence(parameters.ResourceGroupName).Exists)
            {
                WriteVerbose(string.Format("Resource group \"{0}\" is found.", parameters.ResourceGroupName));
            }
            else
            {
                parameters.ConfirmAction(parameters.Force,
                                         ProjectResources.ResourceGroupDoesntExistsAdd,
                                         ProjectResources.AddingResourceGroup,
                                         parameters.Name,
                                         () => CreateResourceGroup(parameters.ResourceGroupName, parameters.Location));

                if (!ResourceManagementClient.ResourceGroups.CheckExistence(parameters.ResourceGroupName).Exists)
                {
                    throw new ArgumentException(ProjectResources.ResourceGroupDoesntExists);
                }
            }

            bool resourceExists = ResourceManagementClient.Resources.CheckExistence(parameters.ResourceGroupName, resourceIdentity).Exists;

            Action createOrUpdateResource = () =>
            {
                WriteVerbose(string.Format("Creating resource \"{0}\" started.", parameters.Name));

                ResourceCreateOrUpdateResult createOrUpdateResult = ResourceManagementClient.Resources.CreateOrUpdate(parameters.ResourceGroupName,
                                                                                                                      resourceIdentity,
                                                                                                                      new ResourceCreateOrUpdateParameters
                {
                    Resource = new BasicResource
                    {
                        Location   = parameters.Location,
                        Properties = SerializeHashtable(parameters.PropertyObject, addValueLayer: false)
                    }
                });

                if (createOrUpdateResult.Resource != null)
                {
                    WriteVerbose(string.Format("Creating resource \"{0}\" complete.", parameters.Name));
                }
            };

            if (resourceExists && !parameters.Force)
            {
                parameters.ConfirmAction(parameters.Force,
                                         ProjectResources.ResourceAlreadyExists,
                                         ProjectResources.NewResourceMessage,
                                         parameters.Name,
                                         createOrUpdateResource);
            }
            else
            {
                createOrUpdateResource();
            }

            ResourceGetResult getResult = ResourceManagementClient.Resources.Get(parameters.ResourceGroupName, resourceIdentity);

            return(getResult.Resource.ToPSResource(this));
        }
 /// <summary>
 /// Gets a resource permissions.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Authorization.IPermissionOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group. The name is case
 /// insensitive.
 /// </param>
 /// <param name='identity'>
 /// Required. Resource
 /// </param>
 /// <returns>
 /// Permissions information.
 /// </returns>
 public static Task<PermissionGetResult> ListForResourceAsync(this IPermissionOperations operations, string resourceGroupName, ResourceIdentity identity)
 {
     return operations.ListForResourceAsync(resourceGroupName, identity, CancellationToken.None);
 }
コード例 #58
0
        /// <summary>
        /// Gets a list of Provider operations in the case that the Actionstring input does not contain a wildcard
        /// </summary>
        private List<PSResourceProviderOperation> ProcessProviderOperationsWithoutWildCard(string actionString, Dictionary<string, string> resourceProvidersWithOperationsApi)
        {
            Dictionary<string, string> resourceProvidersToQuery = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
            string providerFullName = GetAzureProviderOperationCommand.GetResourceProviderFullName(actionString);

            string apiVersion;
            if (resourceProvidersWithOperationsApi.TryGetValue(providerFullName, out apiVersion))
            {
                // We have the full name of the provider and it supports the operations api - so it can be queried
                resourceProvidersToQuery.Add(providerFullName, apiVersion);
            }

            List<PSResourceProviderOperation> operationsToDisplay = new List<PSResourceProviderOperation>();

            if(resourceProvidersToQuery.Count() > 0)
            {
                // Get all operations exposed by this single provider and find the one where the name matches the actionstring input
                 ResourceIdentity identity = new ResourceIdentity()
                {
                    ResourceName = string.Empty,
                    ResourceType = "operations",
                    ResourceProviderNamespace = resourceProvidersToQuery.Single().Key,
                    ResourceProviderApiVersion = resourceProvidersToQuery.Single().Value
                };

                IList<PSResourceProviderOperation> allResourceProviderOperations = this.ResourcesClient.ListPSProviderOperations(new List<ResourceIdentity>() { identity });
                operationsToDisplay.AddRange(allResourceProviderOperations.Where(op => string.Equals(op.OperationName, actionString, StringComparison.InvariantCultureIgnoreCase)));
            }

            return operationsToDisplay;
        }