private AzureResourceId apiIdTemplate(string apiId)
        {
            var rid = new AzureResourceId(apiId);

            rid.SubscriptionId = "',subscription().subscriptionId,'";
            if (apiId.Contains("/managedApis/"))
            {
                rid.ReplaceValueAfter("locations", "',parameters('logicAppLocation'),'");
            }
            else
            {
                string resourcegroupValue         = LogicAppResourceGroup == rid.ResourceGroupName ? "[resourceGroup().name]" : rid.ResourceGroupName;
                string resourcegroupParameterName = AddTemplateParameter(apiId.Split('/').Last() + "-ResourceGroup", "string", resourcegroupValue);
                rid.ResourceGroupName = $"',parameters('{resourcegroupParameterName}'),'";
            }
            return(rid);
        }
        public JObject generateConnectionTemplate(JObject connectionResource, JObject connectionInstance, string connectionName, string concatedId, string connectionNameParam)
        {
            //create template
            var connectionTemplate = new Models.ConnectionTemplate(connectionNameParam, concatedId);

            //displayName
            connectionTemplate.properties.displayName = $"[parameters('{AddTemplateParameter(connectionName+ "_displayName", "string", (string)connectionInstance["properties"]["displayName"])}')]";
            JObject connectionParameters = new JObject();

            bool useGateway = connectionInstance["properties"]["nonSecretParameterValues"]["gateway"] != null;


            //add all parameters
            if (connectionResource["properties"]["connectionParameters"] != null)
            {
                foreach (JProperty parameter in connectionResource["properties"]["connectionParameters"])
                {
                    if ((string)(parameter.Value)["type"] != "oauthSetting")
                    {
                        //we are not handling parameter gatewaySetting
                        if ((string)parameter.Value["type"] == "gatewaySetting")
                        {
                            continue;
                        }
                        if (parameter.Value["uiDefinition"]["constraints"]["capability"] != null)
                        {
                            var match = parameter.Value["uiDefinition"]["constraints"]["capability"].FirstOrDefault(cc => (string)cc == "gateway" && useGateway || (string)cc == "cloud" && !useGateway);
                            if (match == null)
                            {
                                continue;
                            }
                        }


                        if (parameter.Name == "accessKey" && concatedId.EndsWith("/azureblob')]"))
                        {
                            connectionParameters.Add(parameter.Name, $"[listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('{connectionName}_accountName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value]");
                        }
                        else
                        {
                            //todo check this!
                            var addedparam = AddTemplateParameter($"{connectionName}_{parameter.Name}", (string)(parameter.Value)["type"], connectionInstance["properties"]["nonSecretParameterValues"][parameter.Name]);
                            connectionParameters.Add(parameter.Name, $"[parameters('{addedparam}')]");

                            //If has an enum
                            if (parameter.Value["allowedValues"] != null)
                            {
                                var array = new JArray();
                                foreach (var allowedValue in parameter.Value["allowedValues"])
                                {
                                    array.Add(allowedValue["value"]);
                                }
                                template.parameters[addedparam]["allowedValues"] = array;
                                if (parameter.Value["allowedValues"].Count() == 1)
                                {
                                    template.parameters[addedparam]["defaultValue"] = parameter.Value["allowedValues"][0]["value"];
                                }
                            }

                            if (parameter.Value["uiDefinition"]["description"] != null)
                            {
                                //add meta data
                                template.parameters[addedparam]["metadata"] = new JObject();
                                template.parameters[addedparam]["metadata"]["description"] = parameter.Value["uiDefinition"]["description"];
                            }
                        }
                    }
                }
            }

            if (useGateway)
            {
                var currentvalue  = (string)connectionInstance["properties"]["nonSecretParameterValues"]["gateway"]["id"];
                var rid           = new AzureResourceId(currentvalue);
                var gatewayname   = AddTemplateParameter($"{connectionName}_gatewayname", "string", rid.ResourceName);
                var resourcegroup = AddTemplateParameter($"{connectionName}_gatewayresourcegroup", "string", rid.ResourceGroupName);

                var gatewayobject = new JObject();
                gatewayobject["id"] = $"[concat('subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroup}'),'/providers/Microsoft.Web/connectionGateways/',parameters('{gatewayname}'))]";
                connectionParameters.Add("gateway", gatewayobject);
                useGateway = true;
            }

            connectionTemplate.properties.parameterValues = connectionParameters;
            return(JObject.FromObject(connectionTemplate));
        }
        public async Task <JObject> generateDefinition(JObject definition, bool generateConnection = true)
        {
            var rid = new AzureResourceId(definition.Value <string>("id"));

            LogicAppResourceGroup = rid.ResourceGroupName;

            template.parameters["logicAppName"]["defaultValue"] = definition.Value <string>("name");

            workflowTemplateReference = template.resources.Where(t => ((string)t["type"]) == "Microsoft.Logic/workflows").FirstOrDefault();

            // WriteVerbose("Upgrading connectionId paramters...");
            var modifiedDefinition = definition["properties"]["definition"].ToString().Replace(@"['connectionId']", @"['connectionId']");

            // WriteVerbose("Removing API Host references...");

            workflowTemplateReference["properties"]["definition"] = handleActions(JObject.Parse(modifiedDefinition), (JObject)definition["properties"]["parameters"]);

            // Diagnostic Settings
            if (DiagnosticSettings)
            {
                JToken resources = await handleDiagnosticSettings(definition);

                ((JArray)workflowTemplateReference["resources"]).Merge(resources);
            }

            // Remove resources if empty
            if (((JArray)workflowTemplateReference["resources"]).Count == 0)
            {
                workflowTemplateReference.Remove("resources");
            }

            if (definition["properties"]["integrationAccount"] == null)
            {
                ((JObject)template.resources[0]["properties"]).Remove("integrationAccount");
                template.parameters.Remove("IntegrationAccountName");
                template.parameters.Remove("IntegrationAccountResourceGroupName");
            }
            else
            {
                template.parameters["IntegrationAccountName"]["defaultValue"] = definition["properties"]["integrationAccount"]["name"];
            }



            JObject connections = (JObject)definition["properties"]["parameters"]["$connections"];

            foreach (JProperty parameter in workflowTemplateReference["properties"]["definition"]["parameters"])
            {
                if (!parameter.Name.StartsWith("$"))
                {
                    var name = "param" + parameter.Name;
                    template.parameters.Add(name, JObject.FromObject(new { type = parameter.Value["type"], defaultValue = parameter.Value["defaultValue"] }));
                    parameter.Value["defaultValue"] = "[parameters('" + name + "')]";
                }
            }



            // WriteVerbose("Checking connections...");
            if (connections == null)
            {
                return(JObject.FromObject(template));
            }

            workflowTemplateReference["properties"]["parameters"]["$connections"] = new JObject(new JProperty("value", new JObject()));
            foreach (JProperty connectionProperty in connections["value"])
            {
                /*
                 * "Billogram": {
                 * "connectionId": "/subscriptions/89d02439-770d-43f3-9e4a-8b910457a10c/resourceGroups/INT001.Invoice/providers/Microsoft.Web/connections/Billogram",
                 * "connectionName": "Billogram",
                 * "id": "/subscriptions/89d02439-770d-43f3-9e4a-8b910457a10c/resourceGroups/Messaging/providers/Microsoft.Web/customApis/Billogram"
                 * }
                 */

                string name           = connectionProperty.Name;
                string connectionId   = connectionProperty.First.Value <string>("connectionId");
                string id             = connectionProperty.First.Value <string>("id");
                string connectionName = connectionProperty.First["connectionName"] != null?connectionProperty.First.Value <string>("connectionName") : connectionId.Split('/').Last();

                var    cid        = apiIdTemplate(id);
                string concatedId = $"[concat('{cid.ToString()}')]";
                //fixes old templates where name sometimes is missing

                var connectionNameParam = AddTemplateParameter($"{connectionName}_name", "string", connectionName);
                workflowTemplateReference["properties"]["parameters"]["$connections"]["value"][connectionName] = JObject.FromObject(new
                {
                    id             = concatedId,
                    connectionId   = $"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]",
                    connectionName = $"[parameters('{connectionNameParam}')]"
                });

                /*
                 * "connections_Billogram_id": {
                 *  "defaultValue": "/subscriptions/cb693348-19cf-42ee-9a63-1969d567f333/resourceGroups/Shared/providers/Microsoft.Web/customApis/Billogram",
                 *  "type": "String"
                 * }
                 * "workflows_INT001.Invoice_id": {
                 *  "defaultValue": "/subscriptions/cb693348-19cf-42ee-9a63-1969d567f333/resourceGroups/Shared/providers/Microsoft.Web/customApis/Billogram",
                 *  "type": "String"
                 * }
                 *      "connections_Billogram_name": {
                 *  "defaultValue": "Billogram",
                 *  "type": "String"
                 * },
                 * {
                 *  "comments": "Generalized from resource: '/subscriptions/cb693348-19cf-42ee-9a63-1969d567f333/resourceGroups/INT001.Invoice/providers/Microsoft.Web/connections/Billogram'.",
                 *  "type": "Microsoft.Web/connections",
                 *  "name": "[parameters('connections_Billogram_name')]",
                 *  "apiVersion": "2016-06-01",
                 *  "location": "westeurope",
                 *  "scale": null,
                 *  "properties": {
                 *      "displayName": "[parameters('connections_Billogram_name')]",
                 *      "customParameterValues": {},
                 *      "api": {
                 *          "id": "[parameters('connections_Billogram_id')]"
                 *      }
                 *  },
                 *  "dependsOn": []
                 * }
                 * "parameters": {
                 *  "$connections": {
                 *      "value": {
                 *          "Billogram": {
                 *              "connectionId": "[resourceId('Microsoft.Web/connections', parameters('connections_Billogram_name'))]",
                 *              "connectionName": "Billogram",
                 *              "id": "[parameters('workflows_INT001.Invoice_id')]"
                 *          }
                 *      }
                 *  }
                 * }
                 */
                if (generateConnection)
                {
                    //get api definition
                    JObject apiResource = await resourceCollector.GetResource("https://management.azure.com" + id, "2016-06-01");

                    //get api instance data, sub,group,provider,name
                    JObject apiResourceInstance = await resourceCollector.GetResource("https://management.azure.com" + connectionId, "2016-06-01");

                    //add depends on to make sure that the api connection is created before the Logic App
                    ((JArray)workflowTemplateReference["dependsOn"]).Add($"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]");

                    // WriteVerbose($"Generating connection resource for {connectionName}....");
                    var connectionTemplate = generateConnectionTemplate(apiResource, apiResourceInstance, connectionName, concatedId, connectionNameParam);

                    template.resources.Insert(1, connectionTemplate);
                }
            }


            // WriteVerbose("Finalizing Template...");
            return(JObject.FromObject(template));
        }
        private JToken handleActions(JObject definition, JObject parameters)
        {
            foreach (JProperty action in definition["actions"])
            {
                var type = action.Value.SelectToken("type").Value <string>().ToLower();
                //if workflow fix so links are dynamic.
                if (type == "workflow")
                {
                    var curr = ((JObject)definition["actions"][action.Name]["inputs"]["host"]["workflow"]).Value <string>("id");
                    ///subscriptions/fakeecb73-15f5-4c85-bb3e-fakeecb73/resourceGroups/myresourcegrp/providers/Microsoft.Logic/workflows/INT0020-All-Users-Batch2
                    var    wid = new AzureResourceId(curr);
                    string resourcegroupValue         = LogicAppResourceGroup == wid.ResourceGroupName ? "[resourceGroup().name]" : wid.ResourceGroupName;
                    string resourcegroupParameterName = AddTemplateParameter(action.Name + "-ResourceGroup", "string", resourcegroupValue);
                    string wokflowParameterName       = AddTemplateParameter(action.Name + "-LogicAppName", "string", wid.ResourceName);
                    string workflowid = $"[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroupParameterName}'),'/providers/Microsoft.Logic/workflows/',parameters('{wokflowParameterName}'))]";
                    definition["actions"][action.Name]["inputs"]["host"]["workflow"]["id"] = workflowid;
                    //string result = "[concat('" + rgx.Replace(matches.Groups[1].Value, "',subscription().subscriptionId,'") + + "']";
                }
                else if (type == "apimanagement")
                {
                    var apiId = ((JObject)definition["actions"][action.Name]["inputs"]["api"]).Value <string>("id");
                    var aaid  = new AzureResourceId(apiId);


                    aaid.SubscriptionId    = "',subscription().subscriptionId,'";
                    aaid.ResourceGroupName = "', parameters('" + AddTemplateParameter("apimResourceGroup", "string", aaid.ResourceGroupName) + "'),'";
                    aaid.ReplaceValueAfter("service", "', parameters('" + AddTemplateParameter("apimInstanceName", "string", aaid.ValueAfter("service")) + "'),'");
                    aaid.ReplaceValueAfter("apis", "', parameters('" + AddTemplateParameter("apimApiId", "string", aaid.ValueAfter("apis")) + "'),'");
                    apiId = "[concat('" + aaid.ToString() + "')]";

                    definition["actions"][action.Name]["inputs"]["api"]["id"] = apiId;

                    //handle subscriptionkey
                    var subkey = ((JObject)definition["actions"][action.Name]["inputs"]).Value <string>("subscriptionKey");
                    definition["actions"][action.Name]["inputs"]["subscriptionKey"] = "[parameters('" + AddTemplateParameter("apimSubscriptionKey", "string", subkey) + "')]";
                }
                else if (type == "if")
                {
                    definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject <JObject>(), parameters);
                    //else

                    if (definition["actions"][action.Name]["else"] != null && definition["actions"][action.Name]["else"]["actions"] != null)
                    {
                        definition["actions"][action.Name]["else"] = handleActions(definition["actions"][action.Name]["else"].ToObject <JObject>(), parameters);
                    }
                }
                else if (type == "scope" || type == "foreach" || type == "until")
                {
                    definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject <JObject>(), parameters);
                }
                else if (type == "switch")
                {
                    //handle default if exists
                    if (definition["actions"][action.Name]["default"] != null && definition["actions"][action.Name]["default"]["actions"] != null)
                    {
                        definition["actions"][action.Name]["default"] = handleActions(definition["actions"][action.Name]["default"].ToObject <JObject>(), parameters);
                    }

                    foreach (var switchcase in definition["actions"][action.Name]["cases"].Children <JProperty>())
                    {
                        definition["actions"][action.Name]["cases"][switchcase.Name] = handleActions(definition["actions"][action.Name]["cases"][switchcase.Name].ToObject <JObject>(), parameters);
                    }
                }
                else if (type == "flatfiledecoding" || type == "flatfileencoding")
                {
                    definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]["name"] = "[parameters('" + AddTemplateParameter(action.Name + "-SchemaName", "string", ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]).Value <string>("name")) + "')]";
                }
                else if (type == "xslt")
                {
                    definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]["name"] = "[parameters('" + AddTemplateParameter(action.Name + "-MapName", "string", ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]).Value <string>("name")) + "')]";
                }
                else if (type == "http")
                {
                    definition["actions"][action.Name]["inputs"]["uri"] = "[parameters('" + AddTemplateParameter(action.Name + "-URI", "string", ((JObject)definition["actions"][action.Name]["inputs"]).Value <string>("uri")) + "')]";

                    var authenticationObj = (JObject)definition["actions"][action.Name]["inputs"]["authentication"];
                    if (authenticationObj != null)
                    {
                        var authType = authenticationObj.Value <string>("type");
                        if ("Basic".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "******" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("password")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["username"] = "******" + AddTemplateParameter(action.Name + "-Username", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("username")) + "')]";
                        }
                        else if ("ClientCertificate".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "******" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("password")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["pfx"]      = "[parameters('" + AddTemplateParameter(action.Name + "-Pfx", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("pfx")) + "')]";
                        }
                        else if ("ActiveDirectoryOAuth".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["audience"]  = "[parameters('" + AddTemplateParameter(action.Name + "-Audience", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("audience")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["authority"] = "[parameters('" + AddTemplateParameter(action.Name + "-Authority", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("authority")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["clientId"]  = "[parameters('" + AddTemplateParameter(action.Name + "-ClientId", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("clientId")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["secret"]    = "[parameters('" + AddTemplateParameter(action.Name + "-Secret", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("secret")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["tenant"]    = "[parameters('" + AddTemplateParameter(action.Name + "-Tenant", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("tenant")) + "')]";
                        }
                        else if ("Raw".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Raw", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("value")) + "')]";
                        }
                    }
                }
                else if (type == "function")
                {
                    var curr = ((JObject)definition["actions"][action.Name]["inputs"]["function"]).Value <string>("id");
                    var faid = new AzureResourceId(curr);

                    faid.SubscriptionId    = "',subscription().subscriptionId,'";
                    faid.ResourceGroupName = "',parameters('" + AddTemplateParameter(action.Name + "-ResourceGroup", "string", faid.ResourceGroupName) + "'),'";
                    faid.ReplaceValueAfter("sites", "',parameters('" + AddTemplateParameter(action.Name + "-FunctionApp", "string", faid.ValueAfter("sites")) + "'),'");
                    faid.ReplaceValueAfter("functions", "',parameters('" + AddTemplateParameter(action.Name + "-FunctionName", "string", faid.ValueAfter("functions")) + "')");

                    definition["actions"][action.Name]["inputs"]["function"]["id"] = "[concat('" + faid.ToString() + ")]";
                }
                else
                {
                    var api = action.Value.SelectToken("inputs.host.api");
                    if (api != null)
                    {
                        ((JObject)definition["actions"][action.Name]["inputs"]["host"]).Remove("api");
                    }

                    //get the type:
                    //handle connection
                    var connection = action.Value.SelectToken("inputs.host.connection");
                    if (connection != null)
                    {
                        var getConnectionNameType = this.GetConnectionTypeName(connection, parameters);

                        switch (getConnectionNameType)
                        {
                        case "filesystem":
                        {
                            //var metadata = action.Value.SelectToken("metadata");
                            var meta = ((JObject)definition["actions"][action.Name]["metadata"]);
                            if (meta != null)
                            {
                                var base64string = ((JProperty)meta.First).Name;
                                var param        = AddParameterForMetadataBase64(meta, action.Name + "-folderPath");
                                meta.Parent.Parent["inputs"]["path"] = "[concat('" + action.Value.SelectToken("inputs.path").ToString().Replace($"'{base64string}'", "',base64(parameters('" + param + "')),'") + "')]";
                            }
                            break;
                        }

                        case "azureblob":
                        {
                            var meta = ((JObject)definition["actions"][action.Name]["metadata"]);
                            if (meta != null)
                            {
                                var base64string = ((JProperty)meta.First).Name;
                                var param        = AddParameterForMetadataBase64(meta, action.Name + "-path");

                                var token = action.Value.SelectToken("inputs.path");

                                var replaced = token.Value <string>().Replace($"'{base64string}'", $"', parameters('__apostrophe'), base64(parameters('{param}')), parameters('__apostrophe'), '");
                                var newValue = $"[concat('{replaced}')]";

                                meta.Parent.Parent["inputs"]["path"] = newValue;

                                AddTemplateParameter("__apostrophe", "string", "'");
                            }
                            break;
                        }
                        }
                    }
                }
            }

            //when in if statements triggers is not there
            if (definition["triggers"] != null)
            {
                foreach (JProperty trigger in definition["triggers"])
                {
                    //handle api
                    var api = trigger.Value.SelectToken("inputs.host.api");
                    if (api != null)
                    {
                        ((JObject)definition["triggers"][trigger.Name]["inputs"]["host"]).Remove("api");
                    }

                    //handle connection
                    var connection = trigger.Value.SelectToken("inputs.host.connection");
                    if (connection != null)
                    {
                        var getConnectionNameType = this.GetConnectionTypeName(connection, parameters);

                        switch (getConnectionNameType)
                        {
                        case "filesystem":
                        {
                            var meta = ((JObject)trigger.Value["metadata"]);
                            if (meta != null)
                            {
                                try
                                {
                                    var base64string = ((JProperty)meta.First).Name;
                                    var param        = AddParameterForMetadataBase64(meta, trigger.Name + "-folderPath");
                                    meta.Parent.Parent["inputs"]["queries"]["folderId"] = "[base64(parameters('" + param + "'))]";
                                }
                                catch (FormatException ex)
                                {
                                    //folderid is not a valid base64 so we are skipping it for now

                                    /*var path = ((JProperty)meta.First).Value.ToString();
                                     * var param = AddTemplateParameter(trigger.Name + "-folderPath","string",path);
                                     * meta[((JProperty)meta.First).Name] = $"[parameters('{param}')]";*/
                                }
                            }
                            break;
                        }
                        }
                    }

                    //promote parameters for reccurence settings
                    var recurrence = trigger.Value.SelectToken("recurrence");
                    if (recurrence != null)
                    {
                        definition["triggers"][trigger.Name]["recurrence"]["frequency"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Frequency", "string", recurrence.Value <string>("frequency")) + "')]";
                        definition["triggers"][trigger.Name]["recurrence"]["interval"]  = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Interval", "int", new JProperty("defaultValue", recurrence.Value <int>("interval"))) + "')]";
                        if (recurrence["startTime"] != null)
                        {
                            string   value = recurrence.Value <string>("startTime");
                            DateTime date;
                            if (DateTime.TryParse(value, out date))
                            {
                                value = date.ToString("O");
                            }
                            definition["triggers"][trigger.Name]["recurrence"]["startTime"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "StartTime", "string", value) + "')]";
                        }
                        if (recurrence["timeZone"] != null)
                        {
                            definition["triggers"][trigger.Name]["recurrence"]["timeZone"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "TimeZone", "string", recurrence.Value <string>("timeZone")) + "')]";
                        }
                        if (recurrence["schedule"] != null)
                        {
                            definition["triggers"][trigger.Name]["recurrence"]["schedule"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Schedule", "Object", new JProperty("defaultValue", recurrence["schedule"])) + "')]";
                        }
                    }
                }
            }

            return(definition);
        }
Пример #5
0
        public JObject generateConnectionTemplate(JObject connectionResource, JObject connectionInstance, string connectionName, string concatedId, string connectionNameParam)
        {
            //create template
            var connectionTemplate = new Models.ConnectionTemplate(connectionNameParam, concatedId);

            //displayName
            connectionTemplate.properties.displayName = $"[parameters('{AddTemplateParameter(connectionName + "_displayName", "string", (string)connectionInstance["properties"]["displayName"])}')]";
            JObject connectionParameters = new JObject();

            bool useGateway = connectionInstance["properties"]["nonSecretParameterValues"]["gateway"] != null;


            //add all parameters
            if (connectionResource["properties"]["connectionParameters"] != null)
            {
                foreach (JProperty parameter in connectionResource["properties"]["connectionParameters"])
                {
                    if ((string)(parameter.Value)["type"] != "oauthSetting")
                    {
                        //we are not handling parameter gatewaySetting
                        if ((string)parameter.Value["type"] == "gatewaySetting")
                        {
                            continue;
                        }
                        if (parameter.Value["uiDefinition"]["constraints"]["capability"] != null)
                        {
                            var match = parameter.Value["uiDefinition"]["constraints"]["capability"].FirstOrDefault(cc => (string)cc == "gateway" && useGateway || (string)cc == "cloud" && !useGateway);
                            if (match == null)
                            {
                                continue;
                            }
                        }


                        if ((parameter.Name == "accessKey" && concatedId.EndsWith("/azureblob')]")) || parameter.Name == "sharedkey" && concatedId.EndsWith("/azuretables')]"))
                        {
                            connectionParameters.Add(parameter.Name, $"[listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('{connectionName}_accountName')), '2018-02-01').keys[0].value]");
                        }
                        else if (parameter.Name == "sharedkey" && concatedId.EndsWith("/azurequeues')]"))
                        {
                            connectionParameters.Add(parameter.Name, $"[listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('{connectionName}_storageaccount')), '2018-02-01').keys[0].value]");
                        }
                        else if (concatedId.EndsWith("/azureeventgridpublish')]"))
                        {
                            var url      = connectionInstance["properties"]["nonSecretParameterValues"].Value <string>("endpoint");
                            var location = connectionInstance.Value <string>("location");
                            url = url.Replace("https://", "");
                            var site = url.Substring(0, url.LastIndexOf("." + location));

                            var param = AddTemplateParameter($"{connectionInstance.Value<string>("name")}_instancename", "string", site);

                            if (parameter.Name == "endpoint")
                            {
                                connectionParameters.Add(parameter.Name, $"[reference(concat('Microsoft.EventGrid/topics/',parameters('{param}')),'2018-01-01').endpoint]");
                            }
                            else if (parameter.Name == "api_key")
                            {
                                connectionParameters.Add(parameter.Name, $"[listKeys(resourceId('Microsoft.EventGrid/topics',parameters('{param}')),'2018-01-01').key1]");
                            }
                        }
                        else
                        {
                            //todo check this!
                            var addedparam = AddTemplateParameter($"{connectionName}_{parameter.Name}", (string)(parameter.Value)["type"], connectionInstance["properties"]["nonSecretParameterValues"][parameter.Name]);
                            connectionParameters.Add(parameter.Name, $"[parameters('{addedparam}')]");

                            //If has an enum
                            if (parameter.Value["allowedValues"] != null)
                            {
                                var array = new JArray();
                                foreach (var allowedValue in parameter.Value["allowedValues"])
                                {
                                    array.Add(allowedValue["value"].Value <string>().Replace("none", "anonymous"));
                                }
                                template.parameters[addedparam]["allowedValues"] = array;
                                if (parameter.Value["allowedValues"].Count() == 1)
                                {
                                    template.parameters[addedparam]["defaultValue"] = parameter.Value["allowedValues"][0]["value"].Value <string>().Replace("none", "anonymous");
                                }
                            }

                            if (parameter.Value["uiDefinition"]["description"] != null)
                            {
                                //add meta data
                                template.parameters[addedparam]["metadata"] = new JObject();
                                template.parameters[addedparam]["metadata"]["description"] = parameter.Value["uiDefinition"]["description"];
                            }
                        }
                    }
                }
            }

            if (useGateway)
            {
                var currentvalue  = (string)connectionInstance["properties"]["nonSecretParameterValues"]["gateway"]["id"];
                var rid           = new AzureResourceId(currentvalue);
                var gatewayname   = AddTemplateParameter($"{connectionName}_gatewayname", "string", rid.ResourceName);
                var resourcegroup = AddTemplateParameter($"{connectionName}_gatewayresourcegroup", "string", rid.ResourceGroupName);

                var gatewayobject = new JObject();
                gatewayobject["id"] = $"[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroup}'),'/providers/Microsoft.Web/connectionGateways/',parameters('{gatewayname}'))]";
                connectionParameters.Add("gateway", gatewayobject);
                useGateway = true;
            }
            //only fill connectionParameters when source not empty, otherwise saved credentials will be lost.
            if (connectionParameters.HasValues)
            {
                connectionTemplate.properties.parameterValues = connectionParameters;
            }

            return(JObject.FromObject(connectionTemplate));
        }
Пример #6
0
        public async Task <JObject> generateDefinition(JObject definition, bool generateConnection = true)
        {
            var rid = new AzureResourceId(definition.Value <string>("id"));

            LogicAppResourceGroup = rid.ResourceGroupName;
            //Manage Integration account
            if (definition["properties"]["integrationAccount"] == null)
            {
                ((JObject)template.resources[0]["properties"]).Remove("integrationAccount");
                template.parameters.Remove("IntegrationAccountName");
                template.parameters.Remove("IntegrationAccountResourceGroupName");
            }
            else
            {
                template.parameters["IntegrationAccountName"]["defaultValue"] = definition["properties"]["integrationAccount"]["name"];
                IntegrationAccountId = definition["properties"]["integrationAccount"].Value <string>("id");
            }

            //ISE
            if (definition["properties"]["integrationServiceEnvironment"] == null)
            {
                ((JObject)template.resources[0]["properties"]).Remove("integrationServiceEnvironment");
                template.parameters.Remove("integrationServiceEnvironmentName");
                template.parameters.Remove("integrationServiceEnvironmentResourceGroupName");
            }
            else
            {
                template.parameters["integrationServiceEnvironmentName"]["defaultValue"] = definition["properties"]["integrationServiceEnvironment"]["name"];
                AzureResourceId iseId = new AzureResourceId(definition["properties"]["integrationServiceEnvironment"].Value <string>("id"));
                template.parameters["integrationServiceEnvironmentResourceGroupName"]["defaultValue"] = iseId.ResourceGroupName;
            }

            if (disabledState)
            {
                ((JObject)template.resources[0]["properties"]).Add("state", "Disabled");
            }

            template.parameters["logicAppName"]["defaultValue"] = definition.Value <string>("name");

            workflowTemplateReference = template.resources.Where(t => ((string)t["type"]) == "Microsoft.Logic/workflows").FirstOrDefault();

            // WriteVerbose("Upgrading connectionId paramters...");
            var modifiedDefinition = definition["properties"]["definition"].ToString().Replace(@"['connectionId']", @"['connectionId']");
            // WriteVerbose("Removing API Host references...");

            var def = JObject.Parse(modifiedDefinition);
            //try fixing all properties that start with before handling connections etc[
            var ll = def.Value <JObject>("actions").Descendants().Where(dd => dd.Type == JTokenType.String && dd.Value <string>().StartsWith("[") && dd.Value <string>().EndsWith("]")).ToList();

            for (int i = 0; i < ll.Count(); i++)
            {
                var tofix    = ll[i];
                var newValue = "[" + tofix.Value <string>();
                if (tofix.Parent.Type == JTokenType.Property)
                {
                    (tofix.Parent as JProperty).Value = newValue;
                }
                else
                {
                    var parent = tofix.Parent;
                    tofix.Remove();
                    parent.Add(newValue);
                }
            }

            workflowTemplateReference["properties"]["definition"] = handleActions(def, (JObject)definition["properties"]["parameters"]);

            if (definition.ContainsKey("tags"))
            {
                JToken tags = await HandleTags(definition);

                if (tags.HasValues)
                {
                    workflowTemplateReference.Add("tags", tags);
                }
            }

            // Diagnostic Settings
            if (DiagnosticSettings)
            {
                JToken resources = await handleDiagnosticSettings(definition);

                ((JArray)workflowTemplateReference["resources"]).Merge(resources);
            }

            // Remove resources if empty
            if (((JArray)workflowTemplateReference["resources"]).Count == 0)
            {
                workflowTemplateReference.Remove("resources");
            }


            JObject connections = (JObject)definition["properties"]["parameters"]["$connections"];

            foreach (JProperty parameter in workflowTemplateReference["properties"]["definition"]["parameters"])
            {
                if (!parameter.Name.StartsWith("$"))
                {
                    var name = "param" + parameter.Name;

                    template.parameters.Add(name, JObject.FromObject(new { type = parameter.Value["type"].Value <string>().ToLower(), defaultValue = (parameter.Value["type"].Value <string>().ToLower() == "securestring") ? string.Empty : parameter.Value["defaultValue"] }));
                    parameter.Value["defaultValue"] = "[parameters('" + name + "')]";
                }
            }



            // WriteVerbose("Checking connections...");
            if (connections == null)
            {
                return(JObject.FromObject(template));
            }

            workflowTemplateReference["properties"]["parameters"]["$connections"] = new JObject(new JProperty("value", new JObject()));
            foreach (JProperty connectionProperty in connections["value"])
            {
                string name           = connectionProperty.Name;
                string connectionId   = connectionProperty.First.Value <string>("connectionId");
                string id             = connectionProperty.First.Value <string>("id");
                string connectionName = connectionProperty.First["connectionName"] != null?connectionProperty.First.Value <string>("connectionName") : connectionId.Split('/').Last();


                //fixes old templates where name sometimes is missing

                var connectionNameParam = AddTemplateParameter($"{connectionName}_name", "string", connectionName);

                var    cid        = apiIdTemplate(id, connectionNameParam);
                string concatedId = $"[concat('{cid.ToString()}')]";


                workflowTemplateReference["properties"]["parameters"]["$connections"]["value"][name] = JObject.FromObject(new
                {
                    id             = concatedId,
                    connectionId   = $"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]",
                    connectionName = $"[parameters('{connectionNameParam}')]"
                });

                if (generateConnection)
                {
                    //get api definition
                    JObject apiResource = await resourceCollector.GetResource("https://management.azure.com" + id, "2016-06-01");

                    //get api instance data, sub,group,provider,name
                    JObject apiResourceInstance = await resourceCollector.GetResource("https://management.azure.com" + connectionId, "2016-06-01");

                    //add depends on to make sure that the api connection is created before the Logic App
                    ((JArray)workflowTemplateReference["dependsOn"]).Add($"[resourceId('Microsoft.Web/connections', parameters('{connectionNameParam}'))]");

                    // WriteVerbose($"Generating connection resource for {connectionName}....");
                    var connectionTemplate = generateConnectionTemplate(apiResource, apiResourceInstance, connectionName, concatedId, connectionNameParam);

                    template.resources.Insert(1, connectionTemplate);
                }
            }

            // WriteVerbose("Finalizing Template...");
            return(JObject.FromObject(template));
        }
Пример #7
0
        private JToken handleActions(JObject definition, JObject parameters)
        {
            foreach (JProperty action in definition["actions"])
            {
                var type = action.Value.SelectToken("type").Value <string>().ToLower();
                //if workflow fix so links are dynamic.
                if (type == "workflow")
                {
                    var curr = ((JObject)definition["actions"][action.Name]["inputs"]["host"]["workflow"]).Value <string>("id");

                    var    wid = new AzureResourceId(curr);
                    string resourcegroupValue         = LogicAppResourceGroup == wid.ResourceGroupName ? "[resourceGroup().name]" : wid.ResourceGroupName;
                    string resourcegroupParameterName = AddTemplateParameter(action.Name + "-ResourceGroup", "string", resourcegroupValue);
                    string wokflowParameterName       = AddTemplateParameter(action.Name + "-LogicAppName", "string", wid.ResourceName);
                    string workflowid = $"[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('{resourcegroupParameterName}'),'/providers/Microsoft.Logic/workflows/',parameters('{wokflowParameterName}'))]";
                    definition["actions"][action.Name]["inputs"]["host"]["workflow"]["id"] = workflowid;
                }
                else if (type == "initializevariable" && IncludeInitializeVariable && definition["actions"][action.Name]["inputs"]["variables"][0]["value"] != null)
                {
                    var    variableType = definition["actions"][action.Name]["inputs"]["variables"][0]["type"];
                    string paramType    = string.Empty;

                    //missing securestring & secureObject
                    switch (variableType.Value <string>())
                    {
                    case "Array":
                    case "Object":
                    case "String":
                        paramType = variableType.Value <string>().ToLower();
                        break;

                    case "Boolean":
                        paramType = "bool";
                        break;

                    case "Float":
                        paramType = "string";
                        break;

                    case "Integer":
                        paramType = "int";
                        break;

                    default:
                        paramType = "string";
                        break;
                    }

                    //Arrays and Objects can't be expressions
                    if (definition["actions"][action.Name]["inputs"]["variables"][0]["value"].Type != JTokenType.Array &&
                        definition["actions"][action.Name]["inputs"]["variables"][0]["value"].Type != JTokenType.Object)
                    {
                        //If variable is an expression OR float, we need to change the type of the parameter to string
                        if (definition["actions"][action.Name]["inputs"]["variables"][0].Value <string>("value").StartsWith("@") ||
                            variableType.Value <string>() == "Float")
                        {
                            definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", "string", ((JObject)definition["actions"][action.Name]["inputs"]["variables"][0]).Value <string>("value")) + "')]";
                        }
                        else
                        {
                            //Same as the one from in the outer if sentence
                            definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", paramType, definition["actions"][action.Name]["inputs"]["variables"][0]["value"]) + "')]";
                        }
                    }
                    else
                    {
                        definition["actions"][action.Name]["inputs"]["variables"][0]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Value", paramType, definition["actions"][action.Name]["inputs"]["variables"][0]["value"]) + "')]";
                    }
                }
                else if (type == "apimanagement")
                {
                    var apiId = ((JObject)definition["actions"][action.Name]["inputs"]["api"]).Value <string>("id");
                    var aaid  = new AzureResourceId(apiId);


                    aaid.SubscriptionId    = "',subscription().subscriptionId,'";
                    aaid.ResourceGroupName = "', parameters('" + AddTemplateParameter("apimResourceGroup", "string", aaid.ResourceGroupName) + "'),'";
                    aaid.ReplaceValueAfter("service", "', parameters('" + AddTemplateParameter("apimInstanceName", "string", aaid.ValueAfter("service")) + "'),'");
                    aaid.ReplaceValueAfter("apis", "', parameters('" + AddTemplateParameter("apimApiId", "string", aaid.ValueAfter("apis")) + "'),'");
                    apiId = "[concat('" + aaid.ToString() + "')]";

                    definition["actions"][action.Name]["inputs"]["api"]["id"] = apiId;

                    //handle subscriptionkey if not parematrized
                    var subkey = ((JObject)definition["actions"][action.Name]["inputs"]).Value <string>("subscriptionKey");
                    if (!Regex.Match(subkey, @"parameters\('(.*)'\)").Success)
                    {
                        definition["actions"][action.Name]["inputs"]["subscriptionKey"] = "[parameters('" + AddTemplateParameter("apimSubscriptionKey", "string", subkey) + "')]";
                    }
                }
                else if (type == "if")
                {
                    definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject <JObject>(), parameters);
                    //else

                    if (definition["actions"][action.Name]["else"] != null && definition["actions"][action.Name]["else"]["actions"] != null)
                    {
                        definition["actions"][action.Name]["else"] = handleActions(definition["actions"][action.Name]["else"].ToObject <JObject>(), parameters);
                    }
                }
                else if (type == "scope" || type == "foreach" || type == "until")
                {
                    definition["actions"][action.Name] = handleActions(definition["actions"][action.Name].ToObject <JObject>(), parameters);
                }
                else if (type == "switch")
                {
                    //handle default if exists
                    if (definition["actions"][action.Name]["default"] != null && definition["actions"][action.Name]["default"]["actions"] != null)
                    {
                        definition["actions"][action.Name]["default"] = handleActions(definition["actions"][action.Name]["default"].ToObject <JObject>(), parameters);
                    }

                    foreach (var switchcase in definition["actions"][action.Name]["cases"].Children <JProperty>())
                    {
                        definition["actions"][action.Name]["cases"][switchcase.Name] = handleActions(definition["actions"][action.Name]["cases"][switchcase.Name].ToObject <JObject>(), parameters);
                    }
                }
                else if (type == "flatfiledecoding" || type == "flatfileencoding")
                {
                    definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]["name"] = "[parameters('" + AddTemplateParameter(action.Name + "-SchemaName", "string", ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["schema"]).Value <string>("name")) + "')]";
                }
                else if (type == "xslt" || type == "liquid")
                {
                    var mapname          = ((JObject)definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]).Value <string>("name");
                    var mapParameterName = AddTemplateParameter(action.Name + "-MapName", "string", mapname);
                    definition["actions"][action.Name]["inputs"]["integrationAccount"]["map"]["name"] = "[parameters('" + mapParameterName + "')]";
                }
                else if (type == "http")
                {
                    definition["actions"][action.Name]["inputs"]["uri"] = "[parameters('" + AddTemplateParameter(action.Name + "-URI", "string", ((JObject)definition["actions"][action.Name]["inputs"]).Value <string>("uri")) + "')]";

                    var authenticationObj = (JObject)definition["actions"][action.Name]["inputs"]["authentication"];
                    if (authenticationObj != null)
                    {
                        var authType = authenticationObj.Value <string>("type");
                        if ("Basic".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "******" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("password")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["username"] = "******" + AddTemplateParameter(action.Name + "-Username", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("username")) + "')]";
                        }
                        else if ("ClientCertificate".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["password"] = "******" + AddTemplateParameter(action.Name + "-Password", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("password")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["pfx"]      = "[parameters('" + AddTemplateParameter(action.Name + "-Pfx", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("pfx")) + "')]";
                        }
                        else if ("ActiveDirectoryOAuth".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["audience"]  = "[parameters('" + AddTemplateParameter(action.Name + "-Audience", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("audience")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["authority"] = "[parameters('" + AddTemplateParameter(action.Name + "-Authority", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("authority")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["clientId"]  = "[parameters('" + AddTemplateParameter(action.Name + "-ClientId", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("clientId")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["secret"]    = "[parameters('" + AddTemplateParameter(action.Name + "-Secret", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("secret")) + "')]";
                            definition["actions"][action.Name]["inputs"]["authentication"]["tenant"]    = "[parameters('" + AddTemplateParameter(action.Name + "-Tenant", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("tenant")) + "')]";
                        }
                        else if ("Raw".Equals(authType, StringComparison.CurrentCultureIgnoreCase))
                        {
                            definition["actions"][action.Name]["inputs"]["authentication"]["value"] = "[parameters('" + AddTemplateParameter(action.Name + "-Raw", "string", ((JObject)definition["actions"][action.Name]["inputs"]["authentication"]).Value <string>("value")) + "')]";
                        }
                    }
                }
                else if (type == "function")
                {
                    var curr = ((JObject)definition["actions"][action.Name]["inputs"]["function"]).Value <string>("id");
                    var faid = new AzureResourceId(curr);

                    var resourcegroupValue = LogicAppResourceGroup == faid.ResourceGroupName ? "[resourceGroup().name]" : faid.ResourceGroupName;


                    faid.SubscriptionId    = "',subscription().subscriptionId,'";
                    faid.ResourceGroupName = "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "FunctionApp-" : action.Name + "-") + "ResourceGroup", "string", resourcegroupValue) + "'),'";
                    faid.ReplaceValueAfter("sites", "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "" : action.Name + "-") + "FunctionApp", "string", faid.ValueAfter("sites")) + "'),'");
                    faid.ReplaceValueAfter("functions", "',parameters('" + AddTemplateParameter((FixedFunctionAppName ? "" : action.Name + "-") + "FunctionName", "string", faid.ValueAfter("functions")) + "')");

                    definition["actions"][action.Name]["inputs"]["function"]["id"] = "[concat('" + faid.ToString() + ")]";
                }
                else
                {
                    var api = action.Value.SelectToken("inputs.host.api");
                    if (api != null)
                    {
                        ((JObject)definition["actions"][action.Name]["inputs"]["host"]).Remove("api");
                    }

                    //get the type:
                    //handle connection
                    var connection = action.Value.SelectToken("inputs.host.connection");
                    if (connection != null)
                    {
                        var connectioname = definition["actions"][action.Name]["inputs"]["host"]["connection"].Value <string>("name");

                        var getConnectionNameType = this.GetConnectionTypeName(connection, parameters);

                        switch (getConnectionNameType)
                        {
                        case "filesystem":
                        {
                            var newValue = AddParameterForMetadataBase64((JObject)action.Value, action.Name + "-folderPath", action.Value["inputs"].Value <string>("path"));
                            action.Value["inputs"]["path"] = newValue;

                            break;
                        }

                        case "azuretables":
                        {
                            var inputs = action.Value.Value <JObject>("inputs");
                            var path   = inputs.Value <string>("path");
                            var m      = Regex.Match(path, @"/Tables/@{encodeURIComponent\('(.*)'\)");
                            if (m.Groups.Count > 1)
                            {
                                var tablename = m.Groups[1].Value;
                                var param     = AddTemplateParameter(action.Name + "-tablename", "string", tablename);
                                inputs["path"] = "[concat('" + path.Replace($"'{tablename}'", $"', parameters('__apostrophe'), parameters('{param}'), parameters('__apostrophe'), '") + "')]";
                                AddTemplateParameter("__apostrophe", "string", "'");
                            }

                            break;
                        }

                        case "azureblob":
                        {
                            var newValue = AddParameterForMetadataBase64((JObject)action.Value, action.Name + "-path", action.Value["inputs"].Value <string>("path"));
                            action.Value["inputs"]["path"] = newValue;
                            break;
                        }

                        case "azurequeues":
                        {
                            var inputs = action.Value.Value <JObject>("inputs");
                            var path   = inputs.Value <string>("path");
                            var m      = Regex.Match(path, @"/@{encodeURIComponent\('(.*)'\)");
                            if (m.Groups.Count > 1)
                            {
                                var queuename = m.Groups[1].Value;
                                var param     = AddTemplateParameter(action.Name + "-queuename", "string", queuename);
                                inputs["path"] = "[concat('" + path.Replace("'", "''").Replace($"'{queuename}'", $"'', parameters('{param}'), ''") + "')]";
                            }
                            break;
                        }
                        }
                    }
                }
            }

            //when in if statements triggers is not there
            if (definition["triggers"] != null)
            {
                foreach (JProperty trigger in definition["triggers"])
                {
                    //handle api
                    var api = trigger.Value.SelectToken("inputs.host.api");
                    if (api != null)
                    {
                        ((JObject)definition["triggers"][trigger.Name]["inputs"]["host"]).Remove("api");
                    }

                    //handle connection
                    var connection = trigger.Value.SelectToken("inputs.host.connection");
                    if (connection != null)
                    {
                        var getConnectionNameType = this.GetConnectionTypeName(connection, parameters);

                        switch (getConnectionNameType)
                        {
                        case "filesystem":
                        {
                            try
                            {
                                var newValue = AddParameterForMetadataBase64((JObject)trigger.Value, trigger.Name + "-folderPath", trigger.Value["inputs"]["queries"].Value <string>("folderId"));
                                trigger.Value["inputs"]["queries"]["folderId"] = newValue;
                            }
                            catch (FormatException ex)
                            {
                                //folderid is not a valid base64 so we are skipping it for now

                                /*var path = ((JProperty)meta.First).Value.ToString();
                                 * var param = AddTemplateParameter(trigger.Name + "-folderPath","string",path);
                                 * meta[((JProperty)meta.First).Name] = $"[parameters('{param}')]";*/
                            }

                            break;
                        }
                        }
                    }

                    //promote parameters for reccurence settings
                    var recurrence = trigger.Value.SelectToken("recurrence");
                    if (recurrence != null)
                    {
                        definition["triggers"][trigger.Name]["recurrence"]["frequency"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Frequency", "string", recurrence.Value <string>("frequency")) + "')]";
                        definition["triggers"][trigger.Name]["recurrence"]["interval"]  = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Interval", "int", new JProperty("defaultValue", recurrence.Value <int>("interval"))) + "')]";
                        if (recurrence["startTime"] != null)
                        {
                            string   value = recurrence.Value <string>("startTime");
                            DateTime date;
                            if (DateTime.TryParse(value, out date))
                            {
                                value = date.ToString("O");
                            }
                            definition["triggers"][trigger.Name]["recurrence"]["startTime"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "StartTime", "string", value) + "')]";
                        }
                        if (recurrence["timeZone"] != null)
                        {
                            definition["triggers"][trigger.Name]["recurrence"]["timeZone"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "TimeZone", "string", recurrence.Value <string>("timeZone")) + "')]";
                        }
                        if (recurrence["schedule"] != null)
                        {
                            definition["triggers"][trigger.Name]["recurrence"]["schedule"] = "[parameters('" + this.AddTemplateParameter(trigger.Name + "Schedule", "Object", new JProperty("defaultValue", recurrence["schedule"])) + "')]";
                        }
                    }

                    // http trigger
                    if (trigger.Value.Value <string>("type") == "Request" && trigger.Value.Value <string>("kind") == "Http")
                    {
                        if (this.GenerateHttpTriggerUrlOutput)
                        {
                            JObject outputValue = JObject.FromObject(new
                            {
                                type  = "string",
                                value = "[listCallbackURL(concat(resourceId('Microsoft.Logic/workflows/', parameters('logicAppName')), '/triggers/manual'), '2016-06-01').value]"
                            });

                            this.template.outputs.Add("httpTriggerUrl", outputValue);
                        }
                    }
                }
            }



            return(definition);
        }
Пример #8
0
        // the apiDefinition parameter allows dependency injection for unit testing
        public async Task <JObject> generateDefinition(JObject resource, string apiDefinition = null)
        {
            ARMTemplateClass template = new ARMTemplateClass();

            template.AddParameter("customConnectorApiVersion", "string", "1.0.0.0");
            var name     = template.AddParameter("customConnectorName", "string", resource.Value <string>("name"));
            var location = template.AddParameter("customConnectorLocation", "string", "[resourceGroup().location]");

            var uri = resource["properties"]["apiDefinitions"].Value <string>("modifiedSwaggerUrl");

            string swaggerRawDefinition = apiDefinition ?? GetCustomConnectorSwagger(uri);

            JObject preParsedswaggerDefinition = JObject.Parse(swaggerRawDefinition);
            var     host = preParsedswaggerDefinition.Value <string>("host");

            //replace the host with a parameter to allow the scenarios where the host could be different between environments
            var serviceHost = template.AddParameter("serviceHost", "string", host);
            var scheme      = "http";

            if (preParsedswaggerDefinition.ContainsKey("schemes"))
            {
                scheme = preParsedswaggerDefinition["schemes"].Children().First().Value <string>();
            }
            var backendService = template.AddParameter("backendService", "string", scheme + "://" + host + preParsedswaggerDefinition.Value <string>("basePath"));

            swaggerRawDefinition = swaggerRawDefinition.Replace(host, template.WrapParameterName(serviceHost));

            // handle connectionID
            swaggerRawDefinition = swaggerRawDefinition.Replace(@"/{connectionId}", string.Empty);
            JObject swaggerDefinition = JObject.Parse(swaggerRawDefinition);

            // remove all connectionID parameters
            if (swaggerDefinition.ToString().Contains("connectionId"))
            {
                // note: only Json.Net 12.0.1 supports XPath like below, hence guarding with a try/catch just in case of older version of the libray
                try
                {
                    foreach (var token in swaggerDefinition["paths"].SelectTokens(@"$..[?(@.name === 'connectionId')]").ToList())
                    {
                        token.Remove();
                    }
                }
                catch (JsonException) { }
            }


            JObject resourceObject   = new JObject();
            JObject propertiesObject = new JObject();


            // handle ISE

            JToken origIseToken = resource["properties"].SelectToken("integrationServiceEnvironment");

            if (origIseToken != null)
            {
                var iseEnvName = template.AddParameter("ISEEnvironmentName", "string", origIseToken.Value <string>("name"));


                JObject         iseObject = new JObject();
                AzureResourceId iseId     = new AzureResourceId(origIseToken.Value <string>("id"));
                //iseObject.Add("id", origIseToken.Value<string>("id"));
                var iseEnvResouceGroup = template.AddParameter("ISEEnvironmentResourceGroup", "string", iseId.ResourceGroupName);
                iseId.SubscriptionId    = "subscription().subscriptionId";
                iseId.ResourceGroupName = template.WrapParameterName(iseEnvResouceGroup);
                iseId.ResourceName      = template.WrapParameterName(iseEnvName);

                iseObject.Add("id", $"[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/',parameters('{iseEnvResouceGroup}'), '/providers/Microsoft.Logic/integrationServiceEnvironments/', parameters('{iseEnvName}'))]");

                iseObject.Add("name", template.WrapParameterName(iseEnvName));
                iseObject.Add("type", origIseToken.Value <string>("type"));

                propertiesObject.Add("integrationServiceEnvironment", iseObject);
            }

            if (resource["properties"].SelectToken("connectionParameters") != null)
            {
                propertiesObject.Add("connectionParameters", resource["properties"]["connectionParameters"]);
            }

            JObject backendObject = new JObject();

            backendObject.Add("serviceUrl", template.WrapParameterName(backendService));   // $"[parameters('{serviceHost}')]");
            propertiesObject.Add("backendService", backendObject);

            propertiesObject.Add("swagger", swaggerDefinition);
            propertiesObject.Add("description", resource["properties"].Value <string>("description"));
            propertiesObject.Add("displayname", template.WrapParameterName(name));
            propertiesObject.Add("iconUri", resource["properties"].Value <string>("iconUri"));

            resourceObject.Add("apiVersion", "2019-05-01");
            resourceObject.Add("location", template.WrapParameterName(location));
            resourceObject.Add("name", template.WrapParameterName(name));
            resourceObject.Add("type", resource.Value <string>("type"));
            resourceObject.Add("properties", propertiesObject);

            template.resources.Add(resourceObject);

            return(JObject.FromObject(template));
        }