コード例 #1
0
ファイル: LinkedServiceArm.cs プロジェクト: girays/adfToArm
        public LinkedServiceArm(string factoryName, LinkedService linkedService)
        {
            Name       = linkedService.Name;
            Properties = linkedService.Properties;

            Type       = Constants.LinkedServiceType;
            ApiVersion = Constants.DataFactoryApiVersion;

            switch (linkedService.Properties.TypeProperties)
            {
            case AzureBatchTypeProperties batch:
                DependsOn = new string[2] {
                    factoryName, batch.LinkedServiceName
                };
                break;

            case HDInsightTypeProperties insights:
                DependsOn = new string[2] {
                    factoryName, insights.LinkedServiceName
                };
                break;

            default:
                DependsOn = new string[1] {
                    factoryName
                };
                break;
            }
        }
コード例 #2
0
        private LinkedService ConvertAndTestJson(string json, bool customTest = false, HashSet <string> propertyBagKeys = null)
        {
            LinkedService linkedService = this.ConvertToWrapper(json);

            CoreModel.LinkedService actual = this.Operations.Converter.ToCoreType(linkedService);

            // after converting to intermediate object, ensure that ServiceExtraProperties is still set
            if (customTest)
            {
                IGenericTypeProperties typeProperties =
                    linkedService.Properties.TypeProperties as IGenericTypeProperties;

                Assert.NotNull(typeProperties);
            }

            string actualJson = Core.DataFactoryManagementClient.SerializeInternalLinkedServiceToJson(actual);

            JsonComparer.ValidateAreSame(json, actualJson, ignoreDefaultValues: true);
            Assert.DoesNotContain("ServiceExtraProperties", actualJson);

            JObject actualJObject = JObject.Parse(actualJson);

            JsonComparer.ValidatePropertyNameCasing(actualJObject, true, string.Empty, propertyBagKeys);

            return(linkedService);
        }
コード例 #3
0
        private Instance GetInstance(IEnumerable <LinkedService> linkedServices, IDictionary <string, string> extendedProperties)
        {
            // Valiate input
            linkedServices.ThrowIfNull();

            // Get the details on the datastore-sqldw instance
            LinkedService linkedService = linkedServices
                                          .Where(ls => ls.Name == "datastore-sqldw")
                                          .First();

            // Get the extended properties for the data store
            var properties = linkedService.Properties.TypeProperties as AzureSqlDataWarehouseLinkedService;

            // Get the connection string
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(properties.ConnectionString);

            var instance = new Instance();

            // Get the server and database
            instance.Server   = scsb.DataSource;
            instance.Database = scsb.InitialCatalog;

            instance.Location       = extendedProperties[EXTENDED_PROPERTY_LOCATION];
            instance.ResourceGroup  = extendedProperties[EXTENDED_PROPERTY_RESOURCE_GROUP];
            instance.SubscriptionId = new Guid(extendedProperties[EXTENDED_PROPERTY_SUBSCRIPTION_ID]);

            return(instance);
        }
コード例 #4
0
        public LinkedServiceResource ToSdkObject()
        {
            LinkedService         linkedService         = this.Properties?.ToSdkObject();
            LinkedServiceResource linkedServiceResource = new LinkedServiceResource(linkedService);

            return(linkedServiceResource);
        }
コード例 #5
0
        public virtual LinkedService ToSdkObject()
        {
            LinkedService linkedService = new LinkedService();

            SetProperties(linkedService);
            return(linkedService);
        }
コード例 #6
0
        public string GetSqlConnectionString(string datasetName)
        {
            Dataset       dataset       = Datasets.Single(x => x.Name == datasetName);
            LinkedService linkedService = LinkedServices.First(x => x.Name == dataset.Properties.LinkedServiceName);

            if (linkedService.Properties.Type != "AzureSqlDatabase")
            {
                throw new Exception($"The linked service is of type '{linkedService.Properties.Type}'. It should be of type 'AzureSqlDatabase'.");
            }

            AzureSqlDatabaseLinkedService sqlLinkedService = linkedService.Properties.TypeProperties as AzureSqlDatabaseLinkedService;

            if (sqlLinkedService == null)
            {
                throw new Exception($"Unable to find data set name '{datasetName}'.");
            }

            string connectionString = sqlLinkedService.ConnectionString;

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception($"Connection string for '{linkedService.Name}' linked service is empty.");
            }

            return(connectionString);
        }
        private JObject GetARMResourceFromJson(JObject jsonObject, string resourceType, object resource)
        {
            if (jsonObject["$schema"] != null)
            {
                jsonObject["$schema"].Parent.Remove(); // remove the schema
            }
            jsonObject.Add("type", resourceType.ToLower());
            jsonObject.Add("apiVersion", ARM_API_VERSION);

            // need to escape square brackets in Values as they are a special place-holder in ADF
            // jsonObject = jsonObject.ReplaceInValues("[", "[[").ReplaceInValues("]", "]]");

            JArray dependsOn = new JArray();

            dependsOn.Add("[parameters('" + ARM_PROJECT_PARAMETER_NAME + "')]");

            switch (resourceType.ToLower())
            {
            case "datapipelines":     // for pipelines also add dependencies to all Input and Output-Datasets
                foreach (Activity act in ((Pipeline)resource).Properties.Activities)
                {
                    foreach (ActivityInput actInput in act.Inputs)
                    {
                        dependsOn.Add(actInput.Name);
                    }

                    foreach (ActivityOutput actOutput in act.Outputs)
                    {
                        dependsOn.Add(actOutput.Name);
                    }
                }
                break;

            case "datasets":     // for Datasets also add a dependency to the LinkedService
                Dataset ds = (Dataset)resource;
                dependsOn.Add(ds.Properties.LinkedServiceName);
                break;

            case "linkedservices":     // LinkedServices like Batch or HDInsight might depend on other LinkedServices
                LinkedService ls = (LinkedService)resource;

                Regex regex = new Regex(@"""linkedservicename""\s*:\s*""([^""]+)""", RegexOptions.IgnoreCase);
                Match m     = regex.Match(jsonObject.ToString());

                if (m.Success)
                {
                    dependsOn.Add(m.Groups[1].Value);
                }
                break;

            default:
                Console.WriteLine("ResourceType {0} is not supporeted!", resourceType);
                break;
            }

            jsonObject.Add("dependsOn", dependsOn);

            return(jsonObject);
        }
コード例 #8
0
        /// <summary>
        /// Validates a linked service matches the expected properties. Throws assertion exceptions if validation fails.
        /// </summary>
        /// <param name="expected">Expected linked service</param>
        /// <param name="actual">Actual linked service</param>
        internal static void ValidateLinkedService(LinkedService expected, LinkedService actual)
        {
            Assert.NotNull(actual);
            Assert.NotNull(actual.Id);
            Assert.Equal(LinkedServiceResourceType.ToLower(), actual.Type.ToLower());

            Assert.Equal(expected.ResourceId.ToLower(), actual.ResourceId.ToLower());
        }
コード例 #9
0
        public void LinkedServiceUnregisteredTypeTest(string unregisteredTypeJson)
        {
            // If a linked service type has not been locally registered,
            // typeProperties should be deserialized to a GenericLinkedServiceInstance
            LinkedService linkedService = this.ConvertToWrapper(unregisteredTypeJson);

            Assert.IsType <GenericLinkedService>(linkedService.Properties.TypeProperties);
        }
コード例 #10
0
        public PSLinkedService(LinkedService linkedService)
        {
            if (linkedService == null)
            {
                throw new ArgumentNullException("linkedService");
            }

            this.linkedService = linkedService;
        }
コード例 #11
0
 public BlobLocation(LinkedService linkedService, Dataset dataset, string sliceYear, string sliceMonth,
                     string sliceDay)
 {
     _linkedService = linkedService;
     _dataset       = dataset;
     _sliceYear     = sliceYear;
     _sliceMonth    = sliceMonth;
     _sliceDay      = sliceDay;
 }
コード例 #12
0
        internal LinkedServiceGetResponse(
            Core.Models.LinkedServiceGetResponse internalResponse,
            DataFactoryManagementClient client)
            : this()
        {
            Ensure.IsNotNull(internalResponse, "internalResponse");
            Ensure.IsNotNull(internalResponse.LinkedService, "internalResponse.LinkedService");

            DataFactoryOperationUtilities.CopyRuntimeProperties(internalResponse, this);
            this.LinkedService =
                ((LinkedServiceOperations)client.LinkedServices).Converter.ToWrapperType(internalResponse.LinkedService);
        }
コード例 #13
0
        internal LinkedServiceGetResponse(
            Core.Models.LinkedServiceGetResponse internalResponse,
            DataFactoryManagementClient client)
            : this()
        {
            Ensure.IsNotNull(internalResponse, "internalResponse");
            Ensure.IsNotNull(internalResponse.LinkedService, "internalResponse.LinkedService");

            DataFactoryOperationUtilities.CopyRuntimeProperties(internalResponse, this);
            this.LinkedService =
                ((LinkedServiceOperations)client.LinkedServices).Converter.ToWrapperType(internalResponse.LinkedService);
        }
コード例 #14
0
        public void CanCreateLinkedService()
        {
            // Arrange
            LinkedService expected = new LinkedService()
            {
                Name       = linkedServiceName,
                Properties = new HDInsightBYOCLinkedService()
                {
                    ProvisioningState = "Succeeded"
                }
            };

            dataFactoriesClientMock.Setup(c => c.ReadJsonFileContent(It.IsAny <string>()))
            .Returns(rawJsonContent)
            .Verifiable();

            dataFactoriesClientMock.Setup(
                c =>
                c.CreatePSLinkedService(
                    It.Is <CreatePSLinkedServiceParameters>(
                        parameters =>
                        parameters.Name == linkedServiceName &&
                        parameters.ResourceGroupName == ResourceGroupName &&
                        parameters.DataFactoryName == DataFactoryName)))
            .CallBase()
            .Verifiable();

            dataFactoriesClientMock.Setup(
                c =>
                c.CreateOrUpdateLinkedService(ResourceGroupName, DataFactoryName, linkedServiceName, rawJsonContent))
            .Returns(expected)
            .Verifiable();

            // Action
            cmdlet.File  = filePath;
            cmdlet.Force = true;
            cmdlet.ExecuteCmdlet();

            // Assert
            dataFactoriesClientMock.VerifyAll();

            commandRuntimeMock.Verify(
                f =>
                f.WriteObject(
                    It.Is <PSLinkedService>(
                        ls =>
                        ResourceGroupName == ls.ResourceGroupName &&
                        DataFactoryName == ls.DataFactoryName &&
                        expected.Name == ls.LinkedServiceName &&
                        expected.Properties == ls.Properties)),
                Times.Once());
        }
コード例 #15
0
 public PSLinkedService(LinkedService service)
 {
     if (service != null)
     {
         this.Id                    = service.Id;
         this.Name                  = service.Name;
         this.Type                  = service.Type;
         this.ResourceId            = service.ResourceId;
         this.WriteAccessResourceId = service.WriteAccessResourceId;
         this.ProvisioningState     = service.ProvisioningState;
         this.Tags                  = service.Tags;
     }
 }
コード例 #16
0
        public static void SetLinkedServiceProperties(LinkedService linkedService, LinkedServiceJson linkedServiceJson)
        {
            if (linkedService.LinkedServiceProperties != null)
            {
                LinkedServiceProperty linkedServiceProperty = linkedService.LinkedServiceProperties;

                LinkedServicePropertyJson linkedServicePropertyJson = new();
                linkedServicePropertyJson.Type = linkedService.Type.ToString();

                SetLinkedServiceTypeProperties(linkedServiceProperty, linkedServicePropertyJson);

                linkedServiceJson.Properties = linkedServicePropertyJson;
            }
        }
コード例 #17
0
        /// <summary>
        /// Serializes the given LinkedService into JSON, by mocking a create request to
        /// exercise the client's serialization logic.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string SerializeLinkedServiceToJson(LinkedService item)
        {
            var createParams = new LinkedServiceCreateOrUpdateParameters()
            {
                LinkedService = item
            };

            var    handler           = new MockResourceProviderDelegatingHandler();
            var    client            = DataPipelineManagementClient.GetFakeClient(handler);
            string resourceGroupName = Guid.NewGuid().ToString("D");
            string dataFactoryName   = Guid.NewGuid().ToString("D");

            client.LinkedServices.BeginCreateOrUpdate(resourceGroupName, dataFactoryName, createParams);
            return(handler.Json);
        }
コード例 #18
0
        // Get Linked Service Connection String
        private static string GetConnectionString(LinkedService asset)
        {
            if (asset == null)
            {
                return(null);
            }

            AzureStorageLinkedService storageAsset = asset.Properties as AzureStorageLinkedService;

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

            return(storageAsset.ConnectionString);
        }
コード例 #19
0
        private AdlsInfo GetAdlsInfo(LinkedService outputLinkedService)
        {
            var azureDataLakeStoreLinkedService = (AzureDataLakeStoreLinkedService)outputLinkedService.Properties.TypeProperties;

            return(new AdlsInfo()
            {
                AzureSubscriptionId = azureDataLakeStoreLinkedService.SubscriptionId,
                AadDomain = azureDataLakeStoreLinkedService.Tenant,
                AadClient = azureDataLakeStoreLinkedService.ServicePrincipalId,
                AadClientSecret = azureDataLakeStoreLinkedService.ServicePrincipalKey,
                AdlsUri = azureDataLakeStoreLinkedService.DataLakeStoreUri,
                AdlsName = azureDataLakeStoreLinkedService.AccountName,
                AdlsResourceGroupName = azureDataLakeStoreLinkedService.ResourceGroupName,
                AdlsAuthorization = azureDataLakeStoreLinkedService.Authorization,
                AdlsSessionId = azureDataLakeStoreLinkedService.SessionId
            });
        }
コード例 #20
0
 protected void SetProperties(LinkedService linkedService)
 {
     linkedService.ConnectVia  = this.ConnectVia?.ToSdkObject();
     linkedService.Description = this.Description;
     this.Annotations?.ForEach(item => linkedService.Annotations.Add(item));
     this.Parameters?.ForEach(item => linkedService.Parameters.Add(item.Key, item.Value?.ToSdkObject()));
     if (this.AdditionalProperties != null)
     {
         foreach (var item in this.AdditionalProperties)
         {
             if (item.Key != "typeProperties")
             {
                 linkedService.Add(item.Key, item.Value);
             }
         }
     }
 }
コード例 #21
0
        protected override MyDotNetActivityContext PreExecute(IEnumerable <LinkedService> linkedServices,
                                                              IEnumerable <Dataset> datasets, Activity activity, IActivityLogger logger)
        {
            WriteGreeting(logger);
            // Process ADF artifacts up front as these objects are not serializable across app domain boundaries.
            Dataset       dataset           = datasets.First(ds => ds.Name == activity.Inputs.Single().Name);
            var           blobProperties    = (AzureBlobDataset)dataset.Properties.TypeProperties;
            LinkedService linkedService     = linkedServices.First(ls => ls.Name == dataset.Properties.LinkedServiceName);
            var           storageProperties = (AzureStorageLinkedService)linkedService.Properties.TypeProperties;

            return(new MyDotNetActivityContext
            {
                ConnectionString = storageProperties.ConnectionString,
                FolderPath = blobProperties.FolderPath,
                FileName = blobProperties.FileName
            });
        }
コード例 #22
0
        public PSLinkedService(LinkedService linkedService)
        {
            this.ConnectVia  = new PSIntegrationRuntimeReference(linkedService?.ConnectVia);
            this.Description = linkedService?.Description;
            this.Parameters  = linkedService?.Parameters?
                               .Select(element => new KeyValuePair <string, PSParameterSpecification>(element.Key, new PSParameterSpecification(element.Value)))
                               .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            this.Annotations = linkedService?.Annotations;
            var propertiesEnum = linkedService?.GetEnumerator();

            if (propertiesEnum != null)
            {
                this.AdditionalProperties = new Dictionary <string, object>();
                while (propertiesEnum.MoveNext())
                {
                    this.AdditionalProperties.Add(propertiesEnum.Current);
                }
            }
        }
        public void CanCreateUpdateDeleteLinkedService()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var client = TestHelper.GetOperationalInsightsManagementClient(this, context);
                var subId  = client.SubscriptionId;

                var linkedServiceName       = "Automation";
                var accountResourceIdFromat = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Automation/automationAccounts/{2}";
                var accountResourceId       = string.Format(accountResourceIdFromat, subId, resourceGroupName, automationAccountName);

                // Create a linked service
                var createParameters = new LinkedService
                {
                    ResourceId = accountResourceId
                };
                var createResponse = client.LinkedServices.CreateOrUpdate(resourceGroupName, workspaceName, linkedServiceName, createParameters);
                TestHelper.ValidateLinkedService(createParameters, createResponse);

                // Get the linked service
                var getResponse = client.LinkedServices.Get(resourceGroupName, workspaceName, linkedServiceName);
                TestHelper.ValidateLinkedService(createParameters, getResponse);

                // List the linked services in the workspace
                var listResponse = client.LinkedServices.ListByWorkspace(resourceGroupName, workspaceName);
                Assert.Single(listResponse);
                Assert.Single(listResponse.Where(w => w.ResourceId.Equals(accountResourceId, StringComparison.OrdinalIgnoreCase)));

                var accountResourceId2 = string.Format(accountResourceIdFromat, subId, resourceGroupName, automationAccountName2);
                var updateParameters   = new LinkedService
                {
                    ResourceId = accountResourceId2
                };

                // Perform an update on one of the linked service
                var updateResponse = client.LinkedServices.CreateOrUpdate(resourceGroupName, workspaceName, linkedServiceName, updateParameters);
                TestHelper.ValidateLinkedService(updateParameters, updateResponse);

                // Delete a linked service
                client.LinkedServices.Delete(resourceGroupName, workspaceName, linkedServiceName);
            }
        }
コード例 #24
0
        protected override GeoCodeContext PreExecute(IEnumerable <LinkedService> linkedServices,
                                                     IEnumerable <Dataset> datasets, Activity activity, IActivityLogger logger)
        {
            // Process ADF artifacts up front as these objects are not serializable across app domain boundaries.
            Dataset       dataset           = datasets.First(ds => ds.Name == activity.Inputs.Single().Name);
            var           blobProperties    = (AzureBlobDataset)dataset.Properties.TypeProperties;
            LinkedService linkedService     = linkedServices.First(ls => ls.Name == dataset.Properties.LinkedServiceName);
            var           storageProperties = (AzureStorageLinkedService)linkedService.Properties.TypeProperties;

            // to get extended properties (for example: SliceStart)
            DotNetActivity dotNetActivity = (DotNetActivity)activity.TypeProperties;

            return(new GeoCodeContext
            {
                ConnectionString = storageProperties.ConnectionString,
                FolderPath = blobProperties.FolderPath,
                FileName = blobProperties.FileName,
                OutputFolder = dotNetActivity.ExtendedProperties["OutputFolder"],
                MapsAPIKey = dotNetActivity.ExtendedProperties["MapsAPIKey"]
            });
        }
コード例 #25
0
        public void CanThrowIfLinkedServiceProvisioningFailed()
        {
            // Arrange
            LinkedService expected = new LinkedService()
            {
                Name       = linkedServiceName,
                Properties = new HDInsightBYOCLinkedService()
                {
                    ProvisioningState = "Failed"
                }
            };

            dataFactoriesClientMock.Setup(c => c.ReadJsonFileContent(It.IsAny <string>()))
            .Returns(rawJsonContent)
            .Verifiable();

            dataFactoriesClientMock.Setup(
                c =>
                c.CreatePSLinkedService(
                    It.Is <CreatePSLinkedServiceParameters>(
                        parameters =>
                        parameters.Name == linkedServiceName &&
                        parameters.ResourceGroupName == ResourceGroupName &&
                        parameters.DataFactoryName == DataFactoryName)))
            .CallBase()
            .Verifiable();

            dataFactoriesClientMock.Setup(
                c =>
                c.CreateOrUpdateLinkedService(ResourceGroupName, DataFactoryName, linkedServiceName, rawJsonContent))
            .Returns(expected)
            .Verifiable();

            // Action
            cmdlet.File  = filePath;
            cmdlet.Force = true;

            // Assert
            Assert.Throws <ProvisioningFailedException>(() => cmdlet.ExecuteCmdlet());
        }
        public void LinkedServiceCreateFailsWithoutWorkspace()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var client = TestHelper.GetOperationalInsightsManagementClient(this, context);
                var subId  = client.SubscriptionId;

                string linkedServiceName = "Automation";
                string workspaceName     = TestUtilities.GenerateName("AzSDKTest");

                var accountResourceIdFromat = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Automation/automationAccounts/{2}";
                var accountResourceId       = string.Format(accountResourceIdFromat, subId, resourceGroupName, "testAccount");

                var createParameters = new LinkedService
                {
                    ResourceId = accountResourceId
                };

                // Create a linked service on a non-existent workspace
                TestHelper.VerifyCloudException(HttpStatusCode.NotFound, () => client.LinkedServices.CreateOrUpdate(resourceGroupName, workspaceName, linkedServiceName, createParameters));
            }
        }
        public LinkedService ADFLinkedServiceFromJson(JObject jsonObject)
        {
            Type       dynClass;
            MethodInfo dynMethod;

            string objectType = "LinkedService";

            MapConfigElements(ref jsonObject);
            MapSlices(ref jsonObject);

            dynClass  = new Core.DataFactoryManagementClient().GetType();
            dynMethod = dynClass.GetMethod("DeserializeInternal" + objectType + "Json", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            CoreModels.LinkedService internalObject = (CoreModels.LinkedService)dynMethod.Invoke(this, new object[] { jsonObject.ToString() });

            dynClass = Type.GetType(dynClass.AssemblyQualifiedName.Replace("Core.DataFactoryManagementClient", "Conversion." + objectType + "Converter"));
            ConstructorInfo constructor = dynClass.GetConstructor(Type.EmptyTypes);
            object          classObject = constructor.Invoke(new object[] { });

            dynMethod = dynClass.GetMethod("ToWrapperType", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            LinkedService ret = (LinkedService)dynMethod.Invoke(classObject, new object[] { internalObject });

            return(ret);
        }
コード例 #28
0
 /// <summary>
 /// Create or update a linked service.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group to get. The name is case insensitive.
 /// </param>
 /// <param name='workspaceName'>
 /// Name of the Log Analytics Workspace that will contain the linkedServices
 /// resource
 /// </param>
 /// <param name='linkedServiceName'>
 /// Name of the linkedServices resource
 /// </param>
 /// <param name='parameters'>
 /// The parameters required to create or update a linked service.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async System.Threading.Tasks.Task <LinkedService> CreateOrUpdateAsync(this ILinkedServicesOperations operations, string resourceGroupName, string workspaceName, string linkedServiceName, LinkedService parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, linkedServiceName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #29
0
 /// <summary>
 /// Create or update a linked service.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group to get. The name is case insensitive.
 /// </param>
 /// <param name='workspaceName'>
 /// Name of the Log Analytics Workspace that will contain the linkedServices
 /// resource
 /// </param>
 /// <param name='linkedServiceName'>
 /// Name of the linkedServices resource
 /// </param>
 /// <param name='parameters'>
 /// The parameters required to create or update a linked service.
 /// </param>
 public static LinkedService CreateOrUpdate(this ILinkedServicesOperations operations, string resourceGroupName, string workspaceName, string linkedServiceName, LinkedService parameters)
 {
     return(System.Threading.Tasks.Task.Factory.StartNew(s => ((ILinkedServicesOperations)s).CreateOrUpdateAsync(resourceGroupName, workspaceName, linkedServiceName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
コード例 #30
0
        /// <summary>
        /// Create or update a linked service.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group. The name is case insensitive.
        /// </param>
        /// <param name='workspaceName'>
        /// The name of the workspace.
        /// </param>
        /// <param name='linkedServiceName'>
        /// Name of the linkedServices resource
        /// </param>
        /// <param name='parameters'>
        /// The parameters required to create or update a linked service.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <LinkedService> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string linkedServiceName, LinkedService parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <LinkedService> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, linkedServiceName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
コード例 #31
0
        /// <summary>
        /// Create or update a linked service.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group. The name is case insensitive.
        /// </param>
        /// <param name='workspaceName'>
        /// The name of the workspace.
        /// </param>
        /// <param name='linkedServiceName'>
        /// Name of the linkedServices resource
        /// </param>
        /// <param name='parameters'>
        /// The parameters required to create or update a linked service.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <LinkedService> > BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string linkedServiceName, LinkedService parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (resourceGroupName.Length > 90)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
                }
                if (resourceGroupName.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
                }
            }
            if (workspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
            }
            if (workspaceName != null)
            {
                if (workspaceName.Length > 63)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "workspaceName", 63);
                }
                if (workspaceName.Length < 4)
                {
                    throw new ValidationException(ValidationRules.MinLength, "workspaceName", 4);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(workspaceName, "^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "workspaceName", "^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$");
                }
            }
            if (linkedServiceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "linkedServiceName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (Client.SubscriptionId != null)
            {
                if (Client.SubscriptionId.Length < 1)
                {
                    throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1);
                }
            }
            string apiVersion = "2020-08-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("workspaceName", workspaceName);
                tracingParameters.Add("linkedServiceName", linkedServiceName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}").ToString();

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

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

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


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

            // Serialize Request
            string _requestContent = null;

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

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

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

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

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <LinkedService>();

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

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LinkedService>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LinkedService>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
 public LinkedServiceCreateOrUpdateParameters(LinkedService linkedService)
     : this()
 {
     Ensure.IsNotNull(linkedService, "linkedService");
     this.LinkedService = linkedService;
 }