Example #1
0
        private async Task AddOperations(JObject apiTemplateResource, string apiId, DeploymentTemplate template, JObject apiInstance)
        {
            var operations = await resourceCollector.GetResource(apiId + "/operations");

            foreach (JObject operation in (operations == null ? new JArray() : operations.Value <JArray>("value")))
            {
                var opId = operation.Value <string>("id");

                Console.WriteLine();
                Console.WriteLine($"Adding operation - {opId}");

                var operationInstance = await resourceCollector.GetResource(opId);

                var operationTemplateResource = template.CreateOperation(operationInstance);
                apiTemplateResource.Value <JArray>("resources").Add(operationTemplateResource);

                var operationPolicies = await resourceCollector.GetResource(opId + "/policies");

                foreach (JObject operationPolicy in (operationPolicies == null ? new JArray() : operationPolicies.Value <JArray>("value")))
                {
                    var operationSuffix = apiInstance.Value <string>("name") + "_" + operationInstance.Value <string>("name");
                    var policy          = await AddPolicy(operationPolicy, template, apiInstance, apiTemplateResource, operationSuffix);

                    operationTemplateResource.Value <JArray>("resources").Add(policy);
                }
            }
        }
Example #2
0
        public void TestAddAPIInstance()
        {
            var document = JObject.Parse(Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.malo-apiminstance.json"));
            var template = new DeploymentTemplate();

            template.AddAPIManagementInstance(document);
            var definition = JObject.FromObject(template);

            //check parameter default values
            Assert.AreEqual("ibizmalo", definition["parameters"]["service_ibizmalo_name"]["defaultValue"]);
            Assert.AreEqual("West Europe", definition["parameters"]["service_ibizmalo_location"]["defaultValue"]);
            Assert.AreEqual("*****@*****.**", definition["parameters"]["service_ibizmalo_publisherEmail"]["defaultValue"]);
            Assert.AreEqual("ibiz", definition["parameters"]["service_ibizmalo_publisherName"]["defaultValue"]);
            Assert.AreEqual("*****@*****.**", definition["parameters"]["service_ibizmalo_notificationSenderEmail"]["defaultValue"]);
            Assert.AreEqual("Developer", definition["parameters"]["service_ibizmalo_sku_name"]["defaultValue"]);
            Assert.AreEqual("1", definition["parameters"]["service_ibizmalo_sku_capacity"]["defaultValue"]);

            //check definition
            Assert.AreEqual("Microsoft.ApiManagement/service", definition["resources"][0]["type"]);
            Assert.AreEqual("[parameters('service_ibizmalo_name')]", definition["resources"][0]["name"]);
            Assert.AreEqual("2019-01-01", definition["resources"][0]["apiVersion"]);

            Assert.AreEqual("[parameters('service_ibizmalo_sku_name')]", definition["resources"][0]["sku"]["name"]);
            Assert.AreEqual("[parameters('service_ibizmalo_sku_capacity')]", definition["resources"][0]["sku"]["capacity"]);
        }
        private GeneratedTemplate GenerateAPI(JToken api, JObject parsedTemplate, bool apiStandalone,
                                              bool separatePolicyFile, bool separateSwaggerFile)
        {
            var apiObject = JObject.FromObject(api);
            GeneratedTemplate  generatedTemplate = new GeneratedTemplate();
            DeploymentTemplate template          = new DeploymentTemplate(true, true);

            if (separatePolicyFile)
            {
                ReplaceApiOperationPolicyWithFileLink(apiObject, parsedTemplate);
                AddParametersForFileLink(parsedTemplate);
            }
            if (separateSwaggerFile)
            {
                ((JObject)apiObject["properties"]).Property("contentFormat").Remove();
                ((JObject)apiObject["properties"]).Property("contentValue").Remove();
                apiObject["resources"].Where(x => _swaggerTemplateApiResourceTypes.Any(p => p == x.Value <string>("type")))
                .ToList().ForEach(x => x.Remove());
            }
            template.parameters = GetParameters(parsedTemplate["parameters"], apiObject);
            SetFilenameAndDirectory(apiObject, parsedTemplate, generatedTemplate, false);
            template.resources.Add(apiStandalone ? RemoveServiceDependencies(apiObject) : apiObject);

            if (apiStandalone)
            {
                AddProductAPI(apiObject, parsedTemplate, template.resources);
            }
            generatedTemplate.Content = JObject.FromObject(template);
            return(generatedTemplate);
        }
        private void GenerateSwaggerTemplate(JObject parsedTemplate, bool separatePolicyFile, IEnumerable <JToken> apis, List <GeneratedTemplate> templates)
        {
            AddParametersForFileLink(parsedTemplate);
            var apisWithSwagger = apis.Where(x => x["properties"].Value <string>("contentFormat") == "swagger-json" &&
                                             x["properties"].Value <string>("contentValue") != null);

            foreach (var apiWithSwagger in apisWithSwagger)
            {
                GeneratedTemplate  generatedTemplate = new GeneratedTemplate();
                DeploymentTemplate template          = new DeploymentTemplate(true, true);
                SetFilenameAndDirectory(apiWithSwagger, parsedTemplate, generatedTemplate, true);
                if (separatePolicyFile)
                {
                    ReplaceApiOperationPolicyWithFileLink(apiWithSwagger, parsedTemplate);
                    AddParametersForFileLink(parsedTemplate);
                }

                var swaggerTemplate = CreateSwaggerTemplate(apiWithSwagger, parsedTemplate);
                template.resources.Add(JObject.FromObject(swaggerTemplate));
                template.parameters       = GetParameters(parsedTemplate["parameters"], swaggerTemplate);
                generatedTemplate.Content = JObject.FromObject(template);
                templates.Add(generatedTemplate);
                GeneratedTemplate generatedSwagger = new GeneratedTemplate();
                SetFilenameAndDirectory(apiWithSwagger, parsedTemplate, generatedSwagger, true);
                generatedSwagger.FileName = generatedSwagger.FileName.Replace("swagger.template.json", "swagger.json");
                generatedSwagger.Content  = JObject.Parse(apiWithSwagger["properties"].Value <string>("contentValue"));
                templates.Add(generatedSwagger);
            }
        }
        private GeneratedTemplate GenerateProduct(JToken product, JObject parsedTemplate, bool separatePolicyFile, bool apiStandalone, bool listApiInProduct)
        {
            var productId = GetProductId(product);
            GeneratedTemplate generatedTemplate = new GeneratedTemplate
            {
                Directory = $"product-{productId}",
                FileName  = $"product-{productId}.template.json"
            };
            DeploymentTemplate template = new DeploymentTemplate(true, true);

            if (separatePolicyFile)
            {
                ReplaceProductPolicyWithFileLink(product, productId);
                AddParametersForFileLink(parsedTemplate);
            }
            template.parameters = GetParameters(parsedTemplate["parameters"], product);
            template.resources.Add(JObject.FromObject(product));
            generatedTemplate.Content = JObject.FromObject(template);
            if (listApiInProduct)
            {
                ListApiInProduct(generatedTemplate.Content, parsedTemplate);
            }
            if (!listApiInProduct && apiStandalone)
            {
                RemoveProductAPIs(generatedTemplate.Content);
            }
            return(generatedTemplate);
        }
        private async Task AddCertificate(JObject policy, DeploymentTemplate template)
        {
            var policyPropertyName    = policy["properties"].Value <string>("policyContent") == null ? "value" : "policyContent";
            var certificateThumbprint = TemplateHelper.GetCertificateThumbPrintIdFromPolicy(policy["properties"].Value <string>(policyPropertyName));

            if (!string.IsNullOrEmpty(certificateThumbprint))
            {
                var certificates = await resourceCollector.GetResource(GetAPIMResourceIDString() + "/certificates");

                if (certificates != null)
                {
                    // If the thumbprint is a property, we must lookup the value of the property first.
                    var match = Regex.Match(certificateThumbprint, "{{(?<name>[-_.a-zA-Z0-9]*)}}");

                    if (match.Success)
                    {
                        string propertyName     = match.Groups["name"].Value;
                        var    propertyResource = await resourceCollector.GetResource(GetAPIMResourceIDString() + $"/properties/{propertyName}");

                        if (propertyResource != null)
                        {
                            certificateThumbprint = propertyResource["properties"].Value <string>("value");
                        }
                    }

                    var certificate = certificates.Value <JArray>("value").FirstOrDefault(x =>
                                                                                          x?["properties"]?.Value <string>("thumbprint") == certificateThumbprint);
                    if (certificate != null)
                    {
                        template.CreateCertificate(JObject.FromObject(certificate), true);
                    }
                }
            }
        }
Example #7
0
        private async Task AssignApisToProducts(DeploymentTemplate template)
        {
            var products = await resourceCollector.GetResource(GetAPIMResourceIDString() + "/products");

            foreach (JObject productObject in (products == null ? new JArray() : products.Value <JArray>("value")))
            {
                var id = productObject.Value <string>("id");
                var productInstance = await resourceCollector.GetResource(id);

                var productApis = await resourceCollector.GetResource(id + "/apis", (string.IsNullOrEmpty(apiFilters) ? "" : $"$filter={apiFilters}"));

                // Skip product if not related to an API in the filter.
                if (productApis != null && productApis.Value <JArray>("value").Count > 0)
                {
                    foreach (JObject productApi in (productApis == null ? new JArray() : productApis.Value <JArray>("value")))
                    {
                        var productProperties = productApi["properties"];
                        if (productProperties["apiVersionSetId"] != null)
                        {
                            var apiVersionSetId = new AzureResourceId(productProperties["apiVersionSetId"].ToString()).ValueAfter("api-version-sets");
                            productProperties["apiVersionSetId"] = $"[resourceId('Microsoft.ApiManagement/service/api-version-sets', parameters('{GetServiceName(servicename)}'), '{apiVersionSetId}')]";
                        }

                        template.resources.Add(template.AddProductApi(productApi));
                    }
                }
            }
        }
Example #8
0
        public void TestAddVersionSet()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.VersionSet.VersionSetResource.json");
            var template = new DeploymentTemplate();
            var actual   = template.AddVersionSet(JObject.Parse(document));

            Assert.IsNotNull(actual);
        }
Example #9
0
        private static ResourceTemplate GetSchema(bool parametrizePropertiesOnly = false)
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.Schema.simpleschema.json");
            var template = new DeploymentTemplate(parametrizePropertiesOnly);
            var actual   = template.CreateAPISchema(JObject.Parse(document));

            return(actual);
        }
        public void TestSchema()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.Schema.simpleschema.json");
            var template = new DeploymentTemplate();
            var actual   = template.CreateAPISchema(JObject.Parse(document));

            Assert.IsNotNull(actual);
        }
 public TemplateGenerator(string LogicApp, string SubscriptionId, string ResourceGroup, IResourceCollector resourceCollector)
 {
     this.SubscriptionId    = SubscriptionId;
     this.ResourceGroup     = ResourceGroup;
     this.LogicApp          = LogicApp;
     this.resourceCollector = resourceCollector;
     template = JsonConvert.DeserializeObject <DeploymentTemplate>(GetResourceContent("LogicAppTemplate.Templates.starterTemplate.json"));
 }
Example #12
0
        public void TestAddAPIMInstanceResource()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.StandardInstance-New.json");
            var template = DeploymentTemplate.FromString(document);
            var actual   = template.ToString();

            Assert.IsNotNull(actual);
        }
        public bool PolicyHandeAzureResources(JObject policy, string apiname, DeploymentTemplate template)
        {
            var policyPropertyName = policy["properties"].Value <string>("policyContent") == null ? "value" : "policyContent";
            var policyContent      = policy["properties"].Value <string>(policyPropertyName);

            var policyXMLDoc = XDocument.Parse(policyContent);

            var commentMatch = Regex.Match(policyContent, "<!--[ ]*(?<json>{+.*\"azureResource.*)-->");

            if (commentMatch.Success)
            {
                var json = commentMatch.Groups["json"].Value;

                JObject azureResourceObject = JObject.Parse(json).Value <JObject>("azureResource");
                if (azureResourceObject != null)
                {
                    string reourceType = azureResourceObject.Value <string>("type");
                    string id          = azureResourceObject.Value <string>("id");

                    if (reourceType == "logicapp")
                    {
                        var    logicAppNameMatch     = Regex.Match(id, @"resourceGroups/(?<resourceGroupName>[\w-_d]*)/providers/Microsoft.Logic/workflows/(?<name>[\w-_d]*)/triggers/(?<triggerName>[\w-_d]*)");
                        string logicAppName          = logicAppNameMatch.Groups["name"].Value;
                        string logicApptriggerName   = logicAppNameMatch.Groups["triggerName"].Value;
                        string logicAppResourceGroup = logicAppNameMatch.Groups["resourceGroupName"].Value;

                        string listCallbackUrl = $"listCallbackUrl(resourceId(parameters('{template.AddParameter($"logicApp_{logicAppName}_resourcegroup", "string", logicAppResourceGroup)}'),'Microsoft.Logic/workflows/triggers', parameters('{template.AddParameter($"logicApp_{logicAppName}_name", "string", logicAppName)}'),parameters('{template.AddParameter($"logicApp_{logicAppName}_trigger", "string", logicApptriggerName)}')), providers('Microsoft.Logic', 'workflows').apiVersions[0])";

                        //Set the Base URL
                        var backendService = policyXMLDoc.Descendants().Where(dd => dd.Name == "set-backend-service" && dd.Attribute("id").Value == "apim-generated-policy").FirstOrDefault();
                        policy["properties"][policyPropertyName] = CreatePolicyContentReplaceBaseUrl(backendService, policyContent, $"{listCallbackUrl}.basePath");

                        //Handle the sig property
                        var rewriteElement  = policyXMLDoc.Descendants().Where(dd => dd.Name == "rewrite-uri").LastOrDefault();
                        var rewritetemplate = rewriteElement.Attribute("template");
                        if (rewritetemplate != null)
                        {
                            var match = Regex.Match(rewritetemplate.Value, "{{(?<name>[-_.a-zA-Z0-9]*)}}");

                            if (match.Success)
                            {
                                string propname = match.Groups["name"].Value;
                                this.identifiedProperties.Add(new Property()
                                {
                                    type      = Property.PropertyType.LogicApp,
                                    name      = propname,
                                    extraInfo = listCallbackUrl,
                                    apis      = new List <string>(new string[] { apiname })
                                });
                            }
                        }
                    }
                }
            }
            return(commentMatch.Success);
        }
Example #14
0
        public void RemoveBuiltInGroups()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.StandardInstance-New.json");
            var template = DeploymentTemplate.FromString(document);

            template.RemoveResources_BuiltInGroups();

            Assert.AreEqual(0, template.resources.Where(rr => rr.Value <string>("type") == "Microsoft.ApiManagement/service/groups" && rr["properties"].Value <string>("type") == "system").Count());
            Assert.IsNull(template.parameters["groups_guests_name_1"]);
        }
Example #15
0
        public async Task <JObject> GenerateTemplate()
        {
            DeploymentTemplate template = new DeploymentTemplate(this.parametrizePropertiesOnly, this.fixedServiceNameParameter, this.createApplicationInsightsInstance, this.parameterizeBackendFunctionKey);

            await AddApis(template);
            await AssignApisToProducts(template);
            await AddProperties(template);

            return(JObject.FromObject(template));
        }
Example #16
0
        public void ParameterizeBackends()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.MaloInstance-Preview-Export.json");
            var template = DeploymentTemplate.FromString(document);

            template.ParameterizeBackends();

            Assert.AreEqual("http://www.webservicex.net", template.parameters["backends_soap2rest_stock_url"].Value <string>("defaultValue"));
            Assert.AreEqual("[parameters('backends_soap2rest_stock_url')]", template.resources.Where(rr => rr.Value <string>("type") == "Microsoft.ApiManagement/service/backends" && rr.Value <string>("name") == "[parameters('backends_soap2rest_stock_name')]").First()["properties"].Value <string>("url"));
        }
Example #17
0
        private async Task AddSchemas(string apiId, DeploymentTemplate template, JObject apiTemplateResource)
        {
            var apiSchemas = await resourceCollector.GetResource(apiId + "/schemas");

            foreach (JObject schema in (apiSchemas == null ? new JArray() : apiSchemas.Value <JArray>("value")))
            {
                var schemaTemplate = template.CreateAPISchema(schema);
                apiTemplateResource.Value <JArray>("resources").Add(JObject.FromObject(schemaTemplate));
            }
        }
        private async Task <BackendObject> HandleBackend(DeploymentTemplate template, string startname, string backendid)
        {
            var backendInstance = await resourceCollector.GetResource(GetAPIMResourceIDString() + "/backends/" + backendid);

            JObject azureResource = null;

            if (backendInstance["properties"]["resourceId"] != null)
            {
                string version = "2018-02-01";
                if (backendInstance["properties"].Value <string>("resourceId").Contains("Microsoft.Logic"))
                {
                    version = "2017-07-01";
                }

                azureResource = await resourceCollector.GetResource(backendInstance["properties"].Value <string>("resourceId"), "", version);
            }

            //sometime old endpoint are not cleaned-up, this will result in null. So skip these resources
            if (azureResource == null)
            {
                return(null);
            }

            var property = template.AddBackend(backendInstance, azureResource);

            if (property != null)
            {
                if (property.type == Property.PropertyType.LogicApp)
                {
                    var idp = this.identifiedProperties.Where(pp => pp.name.StartsWith(startname) && pp.name.Contains("-invoke")).FirstOrDefault();
                    if (idp != null)
                    {
                        idp.extraInfo = property.extraInfo;
                        idp.type      = Property.PropertyType.LogicAppRevisionGa;
                    }
                }
                else if (property.type == Property.PropertyType.Function)
                {
                    // old way of handling, removed 2019-11-03
                    //property.operationName = GetOperationName(startname);
                    property.operationName = startname;
                    identifiedProperties.Add(property);
                    foreach (var idp in this.identifiedProperties.Where(pp => pp.name.ToLower().StartsWith(property.name) && !pp.name.Contains("-invoke")))
                    {
                        idp.extraInfo = property.extraInfo;
                        idp.type      = Property.PropertyType.Function;
                    }
                }
            }

            return(new BackendObject()
            {
                backendInstance = backendInstance, backendProperty = property
            });
        }
        public TemplateGenerator()
        {
            var assembly     = System.Reflection.Assembly.GetExecutingAssembly();
            var resourceName = "LogicAppTemplate.Templates.starterTemplate.json";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    template = JsonConvert.DeserializeObject <DeploymentTemplate>(reader.ReadToEnd());
                }
        }
Example #20
0
        public void TestFromString()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.StandardInstance-New.json");

            Assert.IsNotNull(document);

            var template = DeploymentTemplate.FromString(document);

            Assert.IsNotNull(template);
            Assert.IsInstanceOfType(template, typeof(DeploymentTemplate));
        }
Example #21
0
        private GeneratedTemplate GenerateAPI(JToken api, JObject parsedTemplate, bool apiStandalone)
        {
            GeneratedTemplate  generatedTemplate = new GeneratedTemplate();
            DeploymentTemplate template          = new DeploymentTemplate(true);

            template.parameters = GetParameters(parsedTemplate["parameters"], api);

            SetFilenameAndDirectory(api, parsedTemplate, generatedTemplate);
            template.resources.Add(apiStandalone ? RemoveServiceDependencies(api) : JObject.FromObject(api));
            generatedTemplate.Content = JObject.FromObject(template);
            return(generatedTemplate);
        }
        private IEnumerable <GeneratedTemplate> GenerateService(JObject parsedTemplate, bool separatePolicyFile, bool alwaysAddPropertiesAndBackend)
        {
            List <GeneratedTemplate> templates       = new List <GeneratedTemplate>();
            List <string>            wantedResources = new List <string> {
                ServiceResourceType, OperationalInsightsWorkspaceResourceType, AppInsightsResourceType, StorageAccountResourceType
            };

            if (alwaysAddPropertiesAndBackend)
            {
                wantedResources.AddRange(new[] { PropertyResourceType, BackendResourceType });
            }

            var generatedTemplate = new GeneratedTemplate {
                FileName = "service.template.json", Directory = String.Empty
            };
            DeploymentTemplate template = new DeploymentTemplate(true, true);
            var resources = parsedTemplate.SelectTokens("$.resources[*]")
                            .Where(r => wantedResources.Any(w => w == r.Value <string>("type")));

            foreach (JToken resource in resources)
            {
                if (resource.Value <string>("type") == ServiceResourceType)
                {
                    AddServiceResources(parsedTemplate, resource, PropertyResourceType);
                    AddServiceResources(parsedTemplate, resource, BackendResourceType);
                    AddServiceResources(parsedTemplate, resource, OpenIdConnectProviderResourceType);
                    AddServiceResources(parsedTemplate, resource, CertificateResourceType);
                    if (separatePolicyFile)
                    {
                        var policy = resource.SelectToken($"$..resources[?(@.type==\'{ServicePolicyResourceType}\')]");
                        if (policy != null)
                        {
                            templates.Add(GenerateServicePolicyFile(parsedTemplate, policy));
                            ReplacePolicyWithFileLink(policy, new FileInfo(ServicePolicyFileName, String.Empty));
                        }
                    }
                }
                template.parameters.Merge(GetParameters(parsedTemplate["parameters"], resource));
                template.variables.Merge(GetParameters(parsedTemplate["variables"], resource, "variables"));
                var variableParameters = GetParameters(parsedTemplate["parameters"], parsedTemplate["variables"]);
                foreach (var parameter in variableParameters)
                {
                    if (template.parameters[parameter.Key] == null)
                    {
                        template.parameters[parameter.Key] = parameter.Value;
                    }
                }
                template.resources.Add(JObject.FromObject(resource));
            }
            generatedTemplate.Content = JObject.FromObject(template);
            templates.Add(generatedTemplate);
            return(templates);
        }
Example #23
0
        public void ParameterizeAPIs()
        {
            var document = Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.StandardInstance-New.json");
            var template = DeploymentTemplate.FromString(document);

            template.ParameterizeAPIs();

            Assert.AreEqual("http://echoapi.cloudapp.net/api", template.parameters["apis_echo_api_serviceUrl"].Value <string>("defaultValue"));
            Assert.AreEqual("[parameters('apis_echo_api_serviceUrl')]", template.resources.Where(rr => rr.Value <string>("type") == "Microsoft.ApiManagement/service/apis" && rr.Value <string>("name") == "[parameters('apis_echo_api_name')]").First()["properties"].Value <string>("serviceUrl"));
            Assert.AreEqual("1", template.parameters["apis_echo_api_apiRevision"].Value <string>("defaultValue"));
            Assert.AreEqual("[parameters('apis_echo_api_apiRevision')]", template.resources.Where(rr => rr.Value <string>("type") == "Microsoft.ApiManagement/service/apis" && rr.Value <string>("name") == "[parameters('apis_echo_api_name')]").First()["properties"].Value <string>("apiRevision"));
        }
Example #24
0
        private async Task AddApiPolicies(string apiId, string apiName, DeploymentTemplate template, JObject apiInstance, JObject apiTemplateResource)
        {
            var apiPolicies = await resourceCollector.GetResource(apiId + "/policies");

            foreach (JObject policy in (apiPolicies == null ? new JArray() : apiPolicies.Value <JArray>("value")))
            {
                await AddCertificate(policy, template);

                var apiPolicy = await AddPolicy(policy, template, apiInstance, apiTemplateResource, apiName);

                apiTemplateResource.Value <JArray>("resources").Add(apiPolicy);
            }
        }
        public TemplateGenerator(string LogicApp, string SubscriptionId, string ResourceGroup, IResourceCollector resourceCollector)
        {
            this.SubscriptionId    = SubscriptionId;
            this.ResourceGroup     = ResourceGroup;
            this.LogicApp          = LogicApp;
            this.resourceCollector = resourceCollector;
            var assembly     = System.Reflection.Assembly.GetExecutingAssembly();
            var resourceName = "LogicAppTemplate.Templates.starterTemplate.json";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    template = JsonConvert.DeserializeObject <DeploymentTemplate>(reader.ReadToEnd());
                }
        }
Example #26
0
        private GeneratedTemplate GeneratedMasterTemplate2(JObject parsedTemplate, bool separatePolicyFile, string fileName, string directory, IEnumerable <GeneratedTemplate> filteredTemplates, List <GeneratedTemplate> generatedTemplates)
        {
            var generatedTemplate = new GeneratedTemplate {
                Directory = directory, FileName = fileName
            };
            DeploymentTemplate template = new DeploymentTemplate(true, true);

            foreach (GeneratedTemplate template2 in filteredTemplates)
            {
                template.resources.Add(GenerateDeployment(template2, generatedTemplates));
            }
            template.parameters       = GetParameters(parsedTemplate["parameters"], template.resources, separatePolicyFile);
            generatedTemplate.Content = JObject.FromObject(template);
            return(generatedTemplate);
        }
Example #27
0
        public void ScenarioTestLogicAppUpdatedBackend()
        {
            var collector = new MockResourceCollector("UpdatedeLogicApp");
            var dtemplate = new DeploymentTemplate();

            var document = JObject.Parse(Utils.GetEmbededFileContent("APIManagementTemplate.Test.Samples.UpdatedeLogicApp.service-cramoapidev-backends-LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV.json"));

            dtemplate.AddBackend(document, JObject.Parse("{\"properties\":{\"definition\": {\"triggers\": {\"manual\": {\"type\": \"Request\",\"kind\": \"Http\"}}}}}"));

            Assert.AreEqual("[substring(listCallbackUrl(resourceId(parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_resourceGroup'), 'Microsoft.Logic/workflows/triggers', parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_logicAppName'), 'manual'), '2017-07-01').basePath,0,add(10,indexOf(listCallbackUrl(resourceId(parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_resourceGroup'), 'Microsoft.Logic/workflows/triggers', parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_logicAppName'), 'manual'), '2017-07-01').basePath,'/triggers/')))]", dtemplate.resources[0]["properties"].Value <string>("url"));
            Assert.AreEqual("[concat('https://management.azure.com/','subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_resourceGroup'),'/providers/Microsoft.Logic/workflows/',parameters('LogicApp_INT3502-PricelistErrorFileToSharePoint-DEV_logicAppName'))]", dtemplate.resources[0]["properties"].Value <string>("resourceId"));
            var result = dtemplate.ToString();

            //Assert.AreEqual("other", oparation["properties"]["templateParameters"][1].Value<string>("name"));
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TaskExecutor"/> class.
        /// </summary>
        /// <param name="template">The deployment template.</param>
        /// <param name="tasks">The tasks to execute.</param>
        /// <param name="context">The task execution context.</param>
        public TaskExecutor(DeploymentTemplate template, IList <ITask> tasks, TaskContext context)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException(nameof(tasks));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Template = template;
            Tasks    = tasks;
            Context  = context;
        }
        public void PolicyHandeBackendUrl(JObject policy, string apiname, DeploymentTemplate template)
        {
            var policyPropertyName = policy["properties"].Value <string>("policyContent") == null ? "value" : "policyContent";
            var policyContent      = policy["properties"].Value <string>(policyPropertyName);

            var policyXMLDoc = XDocument.Parse(policyContent);
            //find the last backend service and add as parameter
            var backendService = policyXMLDoc.Descendants().Where(dd => dd.Name == "set-backend-service").LastOrDefault();

            if (backendService != null)
            {
                // This does not work in all cases. If you want to be sure, use a property as placeholder.
                if (backendService.Attribute("base-url") != null && !backendService.Attribute("base-url").Value.Contains("{{") && !parametrizePropertiesOnly)
                {
                    string baseUrl   = backendService.Attribute("base-url").Value;
                    var    paramname = template.AddParameter($"api_{apiname}_backendurl", "string", baseUrl);
                    if (replaceSetBackendServiceBaseUrlAsProperty)
                    {
                        policy["properties"][policyPropertyName] = CreatePolicyContentReplaceBaseUrlWithProperty(backendService, policyContent, paramname);

                        string          id         = GetIdFromPolicy(policy);
                        AzureResourceId resourceId = new AzureResourceId(id);
                        var             lookFor    = $"/service/{resourceId.ValueAfter("service")}";
                        var             index      = id.IndexOf(lookFor);
                        var             serviceId  = id.Substring(0, index + lookFor.Length);
                        var             property   = new
                        {
                            id         = $"{serviceId}/properties/{paramname}",
                            type       = "Microsoft.ApiManagement/service/namedValues",
                            name       = paramname,
                            properties = new
                            {
                                displayName = paramname,
                                value       = $"[parameters('{paramname}')]",
                                secret      = false
                            }
                        };
                        template.AddNamedValues(JObject.FromObject(property));
                    }
                    else
                    {
                        policy["properties"][policyPropertyName] = CreatePolicyContentReplaceBaseUrl(backendService, policyContent, $"parameters('{paramname}')");
                    }
                }
            }
        }
        public void PolicyHandeBackendUrl(JObject policy, string apiname, DeploymentTemplate template)
        {
            var policyContent = policy["properties"].Value <string>("policyContent");
            var policyXMLDoc  = XDocument.Parse(policyContent);
            //find the last backend service and add as parameter
            var backendService = policyXMLDoc.Descendants().Where(dd => dd.Name == "set-backend-service").LastOrDefault();

            if (backendService != null)
            {
                if (backendService.Attribute("base-url") != null)
                {
                    var baseUrl   = backendService.Attribute("base-url");
                    var paramname = template.AddParameter($"api_{apiname}_backendurl", "string", backendService.Attribute("base-url").Value);
                    policy["properties"]["policyContent"] = CreatePolicyContentReplaceBaseUrl(backendService, policyContent, $"parameters('{paramname}')");
                }
            }
        }