public void PopulateMetadata_ValidJsonAsInput_ReturnMetadataDictionary()
        {
            string metadata = @"{
                ""subscription"": {
                    ""id"": ""/subscriptions/00000000-0000-0000-0000-000000000000"",
                    ""subscriptionId"": ""/subscriptions/00000000-0000-0000-0000-000000000000"",
                    ""tenantId"": ""00000000-0000-0000-0000-000000000000""
                },
                ""resourceGroup"": {
                    ""id"": ""/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/metadataTestresourcegroupname"",
                    ""location"": ""westus2"",
                    ""name"": ""metadataTestresourcegroupname""
                },
                ""deployment"": {
                    ""name"": ""deploymentname"",
                    ""type"": ""deploymenttype"",
                    ""location"": ""westus2"",
                    ""id"": ""/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/metadataTestresourcegroupname"",
                    ""properties"": {
                        ""templateLink"": {
                            ""uri"": ""https://deploymenturi"",
                            ""contentVersion"": ""0.0"",
                            ""metadata"": {
                                ""metadata"": ""deploymentmetadata""
                            }
                        }
                    }
                },
                ""tenantId"": ""00000000-0000-0000-0000-000000000000""
            }";

            InsensitiveDictionary <JToken> metadataObj = _armTemplateProcessor.PopulateDeploymentMetadata(metadata);

            Assert.AreEqual("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/metadataTestresourcegroupname", metadataObj["resourceGroup"]["id"].Value <string>());
        }
        public void ParseAndValidateTemplate_ValidTemplateWithCopyIndex_ProcessResourceCopies()
        {
            string templateJson = @"{
                ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#"",
                ""contentVersion"": ""1.0.0.0"",
                ""parameters"": { },
                ""variables"": { },
                ""resources"": [
                    {
                        ""apiVersion"": ""2016-03-30"",
                        ""copy"": {
                            ""count"": 2,
                            ""name"": ""masterLbLoopNode""
                        },
                        ""location"": ""westus2"",
                        ""name"": ""[concat('name', '/', 'SSH-', 'VMNamePrefix-', copyIndex())]"",
                        ""properties"": {
                            ""backendPort"": 22,
                            ""enableFloatingIP"": false,
                            ""frontendIPConfiguration"": {
                                ""id"": ""Microsoft.Network/loadBalancers/loadBalancer/frontendIPConfigurations/config""
                            },
                            ""frontendPort"": ""[copyIndex(2200)]"",
                            ""protocol"": ""Tcp""
                        },
                        ""type"": ""Microsoft.Network/loadBalancers/inboundNatRules""
                    }
                ],
                ""outputs"": {}
            }";

            ArmTemplateProcessor armTemplateProcessor = new ArmTemplateProcessor(templateJson);

            var parameters = new InsensitiveDictionary <JToken>();

            var metadata = new InsensitiveDictionary <JToken>
            {
                { "subscription", new JObject(
                      new JProperty("id", "/subscriptions/00000000-0000-0000-0000-000000000000"),
                      new JProperty("subscriptionId", "00000000-0000-0000-0000-000000000000"),
                      new JProperty("tenantId", "00000000-0000-0000-0000-000000000000")) },
                { "resourceGroup", new JObject(
                      new JProperty("id", "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceGroupName"),
                      new JProperty("location", "westus2"),
                      new JProperty("name", "resource-group")) },
                { "tenantId", "00000000-0000-0000-0000-000000000000" }
            };

            Template template = armTemplateProcessor.ParseAndValidateTemplate(parameters, metadata);

            Assert.AreEqual(2, template.Resources.Length);

            Assert.AreEqual("name/SSH-VMNamePrefix-0", template.Resources.First().Name.Value);
            Assert.AreEqual("[concat('name', '/', 'SSH-', 'VMNamePrefix-', copyIndex())]", template.Resources.First().OriginalName);
            Assert.AreEqual(2200, template.Resources.First().Properties.Value.InsensitiveToken("frontendPort").Value <int>());

            Assert.AreEqual("name/SSH-VMNamePrefix-1", template.Resources.Last().Name.Value);
            Assert.AreEqual("[concat('name', '/', 'SSH-', 'VMNamePrefix-', copyIndex())]", template.Resources.Last().OriginalName);
            Assert.AreEqual(2201, template.Resources.Last().Properties.Value.InsensitiveToken("frontendPort").Value <int>());
        }
Example #3
0
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static List <Hashtable> GetTagsHashtables(InsensitiveDictionary <string> tags)
 {
     return(tags == null
         ? null
         : tags.Select(kvp => new Hashtable {
         { "Name", kvp.Key }, { "Value", kvp.Value }
     }).ToList());
 }
Example #4
0
        /// <summary>
        /// Processes the ARM template with provided parameters and deployment metadata.
        /// </summary>
        /// <param name="parameters">The template parameters and their values <c>JSON</c>. Must follow this schema: https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#</param>
        /// <param name="metadata">The deployment metadata <c>JSON</c>.</param>
        /// <returns>The processed template as a <c>JSON</c> object.</returns>
        public JToken ProcessTemplate(string parameters, string metadata)
        {
            InsensitiveDictionary <JToken> parametersDictionary = PopulateParameters(string.IsNullOrEmpty(parameters) ? PlaceholderInputGenerator.GeneratePlaceholderParameters(armTemplate) : parameters);
            InsensitiveDictionary <JToken> metadataDictionary   = string.IsNullOrEmpty(metadata) ? PlaceholderInputGenerator.GeneratePlaceholderDeploymentMetadata() : PopulateDeploymentMetadata(metadata);

            var template = ParseAndValidateTemplate(parametersDictionary, metadataDictionary);

            return(template.ToJToken());
        }
        public void PopulateParameters_ParametersPropertyIsEmpty_ReturnEmptyParametersDictionary()
        {
            string parameters = @"{
                ""parameters"": { }
            }";

            InsensitiveDictionary <JToken> parametersObj = _armTemplateProcessor.PopulateParameters(parameters);

            Assert.IsFalse(parametersObj.Any());
        }
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static Hashtable[] GetTagsHashtables(InsensitiveDictionary <string> tags)
 {
     return(tags == null
         ? null
         : tags.SelectArray(kvp => new Hashtable
     {
         { "Name", kvp.Key },
         { "Value", kvp.Value },
     }));
 }
Example #7
0
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static Hashtable[] GetTagsHashtables(InsensitiveDictionary<string> tags)
 {
     return tags == null
         ? null
         : tags.SelectArray(kvp => new Hashtable
         {
             {"Name", kvp.Key},
             {"Value", kvp.Value},
         });
 }
Example #8
0
 public string GetBindingConnectionInformation(string operationId, InsensitiveDictionary <JToken> connectionParameters)
 {
     return(ServiceOperationsProviderUtilities
            .GetRequiredParameterValue(
                serviceId: ServiceId,
                operationId: operationId,
                parameterName: "connectionString",
                parameters: connectionParameters)?
            .ToValue <string>());
 }
        /// <summary>
        /// Creates an insensitive dictionary from an enumerable.
        /// </summary>
        /// <param name="source">The enumerable.</param>
        /// <param name="keySelector">The key selector.</param>
        /// <param name="valueSelector">The value selector.</param>
        public static InsensitiveDictionary <TValue> ToInsensitiveDictionary <TSource, TValue>(this IEnumerable <TSource> source, Func <TSource, string> keySelector, Func <TSource, TValue> valueSelector)
        {
            var dictionary = new InsensitiveDictionary <TValue>();

            foreach (var value in source)
            {
                dictionary[keySelector(value)] = valueSelector(value);
            }

            return(dictionary);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ActiveMQTriggerParameters"/> class.
        /// </summary>
        /// <param name="connectionParameters"></param>
        /// <param name="serviceOperationRequest"></param>
        public ActiveMQTriggerParameters(InsensitiveDictionary <JToken> connectionParameters, ServiceOperationRequest serviceOperationRequest)
        {
            this.connectionParameters    = connectionParameters;
            this.serviceOperationRequest = serviceOperationRequest;

            BrokerUri = ServiceOperationsProviderUtilities.GetParameterValue("BrokerUri", connectionParameters).ToValue <string>();
            ClientId  = ServiceOperationsProviderUtilities.GetParameterValue("ClientId", connectionParameters).ToValue <string>();
            UserName  = ServiceOperationsProviderUtilities.GetParameterValue("UserName", connectionParameters).ToValue <string>();
            Password  = ServiceOperationsProviderUtilities.GetParameterValue("Password", connectionParameters).ToValue <string>();

            MaximumNumber = serviceOperationRequest.Parameters["MaximumNumber"].ToValue <int>();
            QueueName     = serviceOperationRequest.Parameters["queue"].ToValue <string>();
        }
Example #11
0
        public triggerPramsDto(InsensitiveDictionary <JToken> connectionParameters, ServiceOperationRequest serviceOperationRequest)
        {
            this.connectionParameters    = connectionParameters;
            this.serviceOperationRequest = serviceOperationRequest;

            this.BrokerUri = ServiceOperationsProviderUtilities.GetParameterValue("BrokerUri", connectionParameters).ToValue <string>();
            this.ClientId  = ServiceOperationsProviderUtilities.GetParameterValue("ClientId", connectionParameters).ToValue <string>();
            this.UserName  = ServiceOperationsProviderUtilities.GetParameterValue("UserName", connectionParameters).ToValue <string>();
            this.Password  = ServiceOperationsProviderUtilities.GetParameterValue("Password", connectionParameters).ToValue <string>();

            this.MaximumNo = serviceOperationRequest.Parameters["MaximumNo"].ToValue <int>();
            this.QueueName = serviceOperationRequest.Parameters["queue"].ToValue <string>();
        }
        public void PopulateParameters_ValidJsonAsInput_ReturnParametersDictionary()
        {
            string parameters = @"{
                ""parameters"": {
                    ""parameter0"": {
                        ""value"": ""parameter0Value""
                    }
                }
            }";

            InsensitiveDictionary <JToken> parametersObj = _armTemplateProcessor.PopulateParameters(parameters);

            Assert.AreEqual("parameter0Value", parametersObj["parameter0"].Value <string>());
        }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CosmosDBServiceOperationProvider"/> class.
        /// </summary>
        public CosmosDBServiceOperationProvider()
        {
            this.serviceOperationsList = new List <ServiceOperation>();
            this.apiOperationsList     = new InsensitiveDictionary <ServiceOperation>();

            this.apiOperationsList.AddRange(new InsensitiveDictionary <ServiceOperation>
            {
                { "receiveDocument", this.GetReceiveDocumentServiceOperation() },
            });

            this.serviceOperationsList.AddRange(new List <ServiceOperation>
            {
                { this.GetReceiveDocumentServiceOperation().CloneWithManifest(this.GetServiceOperationManifest()) },
            });
        }
        public void PopulateParameters_ParameterWithReference_ValueStartsWithPrefix()
        {
            string parameters = @"{
                ""parameters"": {
                    ""parameter0"": {
                        ""reference"": {
                            ""keyVault"": {
                                ""id"": ""keyVaultID""
                            },
                            ""secretName"": ""testSecretName""
                        }
                    }
                }
            }";

            InsensitiveDictionary <JToken> parametersObj = _armTemplateProcessor.PopulateParameters(parameters);

            Assert.AreEqual("REF_NOT_AVAIL_parameter0", parametersObj["parameter0"].Value <string>());
        }
Example #15
0
        /// <summary>
        /// Patches tags on a resource.
        /// </summary>
        /// <param name="resourceId">The resource identifier.</param>
        /// <param name="apiVersion">The API version.</param>
        /// <param name="tags">The tags to use for patching.</param>
        /// <param name="operation">The patch operation.</param>
        public TagsResource PatchTags(string resourceId, string apiVersion, InsensitiveDictionary <string> tags, PatchOperation operation)
        {
            var patchTagsRequestBody = new PatchTagsResource
            {
                Operation  = operation,
                Properties = new TagsResource {
                    Tags = tags
                }
            };

            return(this.ResourceManagerRestClient
                   .PatchResource(
                       resourceId: this.GetTagsResourceId(resourceId),
                       apiVersion: apiVersion,
                       resource: patchTagsRequestBody.ToJToken(),
                       cancellationToken: CancellationToken.None)
                   .Result
                   .Value
                   .FromJson <TagsResource>());
        }
        public void ParseAndValidateTemplate_ValidTemplateWithExpressionInResourceProperties_ProcessResourceProperyLanguageExpressions()
        {
            var parameters = new InsensitiveDictionary <JToken>();

            var metadata = new InsensitiveDictionary <JToken>
            {
                { "subscription", new JObject(
                      new JProperty("id", "/subscriptions/00000000-0000-0000-0000-000000000000"),
                      new JProperty("subscriptionId", "00000000-0000-0000-0000-000000000000"),
                      new JProperty("tenantId", "00000000-0000-0000-0000-000000000000")) },
                { "resourceGroup", new JObject(
                      new JProperty("id", "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceGroupName"),
                      new JProperty("location", "westus2"),
                      new JProperty("name", "resource-group")) },
                { "tenantId", "00000000-0000-0000-0000-000000000000" }
            };

            Template template = _armTemplateProcessor.ParseAndValidateTemplate(parameters, metadata);

            Assert.IsTrue(template.Resources.First().Properties.Value.InsensitiveToken("dnsSettings.domainNameLabel").Value <string>().StartsWith("linux-vm-"));
        }
Example #17
0
        /// <summary>
        /// Constructor for Service operation provider.
        /// </summary>

        public FTPServiceOperationProvider()
        {
            this.serviceOperationsList = new List <ServiceOperation>();
            this.apiOperationsList     = new InsensitiveDictionary <ServiceOperation>();

            this.apiOperationsList.AddRange(new InsensitiveDictionary <ServiceOperation>
            {
                { ServiceOperationListFile, FTPListOperation() },
                { ServiceOperationGetFile, FTPGetFile() },
                { ServiceOperationUploadFile, FTPUploadFile() },
                { ServiceOperationDeleteFile, FTPDeleteFile() },
                { ServiceOperationCopyFileToBlob, FTPCopyFileToBlob() },
            });

            this.serviceOperationsList.AddRange(new List <ServiceOperation>
            {
                { FTPListOperation().CloneWithManifest(FTPListOperationServiceOperationManifest()) },
                { FTPGetFile().CloneWithManifest(FTPGetOperationServiceOperationManifest()) },
                { FTPUploadFile().CloneWithManifest(FTPUploadOperationServiceOperationManifest()) },
                { FTPDeleteFile().CloneWithManifest(FTPDeleteOperationServiceOperationManifest()) },
                { FTPCopyFileToBlob().CloneWithManifest(FTPCopyFileToBlobOperationServiceOperationManifest()) }
            });
        }
Example #18
0
        Task <ServiceOperationResponse> IServiceOperationsProvider.InvokeOperation(string operationId, InsensitiveDictionary <JToken> connectionParameters, ServiceOperationRequest serviceOperationRequest)
        {
            string path              = string.Empty;
            string outputParam       = string.Empty;
            string serverName        = string.Empty;
            string userName          = string.Empty;
            string password          = string.Empty;
            bool   useSSL            = false;
            bool   implicitMode      = false;
            bool   activeMode        = false;
            bool   useSelfSignedCert = false;
            bool   useBinaryMode     = false;

            ServiceOperationResponse resp = null;
            var opResp = Task.Run(() =>
            {
                try
                {
                    //serverName = GetBindingConnectionInformation(operationId, connectionParameters);
                    var folderToken = serviceOperationRequest.Parameters.GetValueOrDefault("inputParam");

                    if (folderToken != null)
                    {
                        path = folderToken.ToString();
                    }

                    if (folderToken == null || string.IsNullOrEmpty(path))
                    {
                        throw new ApplicationException("Unable to obtain path");
                    }
                    serverName        = GetBindingConnectionParameter(operationId, connectionParameters, "servername");
                    userName          = GetBindingConnectionParameter(operationId, connectionParameters, "username");
                    password          = GetBindingConnectionParameter(operationId, connectionParameters, "password");
                    useSSL            = System.Convert.ToBoolean(GetBindingConnectionParameter(operationId, connectionParameters, "usessl"));
                    implicitMode      = System.Convert.ToBoolean(GetBindingConnectionParameter(operationId, connectionParameters, "implicitmode"));
                    activeMode        = System.Convert.ToBoolean(GetBindingConnectionParameter(operationId, connectionParameters, "activemode"));
                    useSelfSignedCert = System.Convert.ToBoolean(GetBindingConnectionParameter(operationId, connectionParameters, "useSelfsignedcert"));
                    useBinaryMode     = System.Convert.ToBoolean(GetBindingConnectionParameter(operationId, connectionParameters, "usebinarymode"));

                    FTPConfig ftpConfig        = new FTPConfig(serverName, userName, password, useSSL, implicitMode, useSelfSignedCert, activeMode, useBinaryMode);
                    Connectors.FTPCore.FTP FTP = new Connectors.FTPCore.FTP(ftpConfig);
                    switch (operationId)
                    {
                    case ServiceOperationGetFile:
                        var file           = FTP.FluentGetFile(path);
                        JProperty fileProp = new JProperty("body", file.Result);
                        resp = new ServiceOperationResponse(fileProp.Value, System.Net.HttpStatusCode.OK);

                        break;

                    case ServiceOperationUploadFile:
                        string content;
                        var con = serviceOperationRequest.Parameters.GetValueOrDefault("content");

                        if (con == null)
                        {
                            throw new ApplicationException("Unable to read content");
                        }

                        content = con.ToString();

                        var output        = FTP.FluentUploadFile(path, content);
                        JProperty outProp = new JProperty("body", output.Result);
                        resp = new ServiceOperationResponse(outProp.Value, System.Net.HttpStatusCode.OK);

                        break;

                    case ServiceOperationDeleteFile:
                        var deleteOutput     = FTP.FluentDeleteFile(path);
                        JProperty deleteProp = new JProperty("body", deleteOutput.Result);
                        resp = new ServiceOperationResponse(deleteProp.Value, System.Net.HttpStatusCode.OK);

                        break;


                    case ServiceOperationCopyFileToBlob:
                        string storageConnectionString;
                        var storageConn = serviceOperationRequest.Parameters.GetValueOrDefault("storageconnectionstring");

                        if (storageConn == null)
                        {
                            throw new ApplicationException("Unable to read Storage Connection String");
                        }
                        storageConnectionString = storageConn.ToString();

                        string targetContainer;
                        var targetContainerParam = serviceOperationRequest.Parameters.GetValueOrDefault("targetcontainer");

                        if (targetContainerParam == null)
                        {
                            throw new ApplicationException("Unable to read Target Container");
                        }

                        targetContainer = targetContainerParam.ToString();

                        var copyFileOutput = FTP.FluentCopyFileToBlob(path, storageConnectionString, targetContainer);

                        JProperty copyProp = new JProperty("body", copyFileOutput.Result);
                        resp = new ServiceOperationResponse(copyProp.Value, System.Net.HttpStatusCode.OK);

                        break;

                    case ServiceOperationListFile:
                        var fileList = FTP.FluentListFiles(path);
                        var obj      = fileList.Result;

                        List <JObject> jobjects = new List <JObject>();
                        foreach (var doc in fileList.Result)
                        {
                            jobjects.Add((JObject)doc.ToJToken());
                        }
                        JProperty prop = new JProperty("body", jobjects);

                        resp = new ServiceOperationResponse(prop.Value, System.Net.HttpStatusCode.OK);

                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
                catch (FtpCommandException ex)
                {
                    HttpStatusCode code = GetStatusCode(ex.CompletionCode);
                    throw new ServiceOperationsProviderException(
                        httpStatus: code,
                        errorCode: ServiceOperationsErrorResponseCode.ServiceOperationFailed,
                        errorMessage: ex.Message + ", completion code: " + ex.CompletionCode,
                        null);
                }
                catch (Exception ex)
                {
                    throw new ServiceOperationsProviderException(
                        httpStatus: HttpStatusCode.InternalServerError,
                        errorCode: ServiceOperationsErrorResponseCode.ServiceOperationFailed,
                        errorMessage: ex.Message,
                        innerException: ex.InnerException
                        );
                }

                return(resp);
            });

            return(opResp);
        }
Example #19
0
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static List<Hashtable> GetTagsHashtables(InsensitiveDictionary<string> tags)
 {
     return tags == null
         ? null
         : tags.Select(kvp => new Hashtable { { "Name", kvp.Key }, { "Value", kvp.Value } }).ToList();
 }
 /// <summary>
 /// Gets the connection.
 /// </summary>
 /// <param name="operationId">The operation id.</param>
 /// <param name="connectionParameters">The connection parameters.</param>
 public string GetBindingConnectionInformation(string operationId, InsensitiveDictionary <JToken> connectionParameters)
 {
     throw new NotImplementedException();
 }
Example #21
0
        public static Dictionary<string, string> ParseKeywords(string str, Tokens tokens)
        {
            PARSE state = PARSE.Initial;
            int index = 0;
            int keyStart = 0;
            InsensitiveDictionary keywords = new InsensitiveDictionary(5);
            string key = null;

            if (str != null)
            {
                StringBuilder builder = new StringBuilder(str.Length);
                for (; index < str.Length; index++)
                {
                    char ch = str[index];
                    switch (state)
                    {
                        case PARSE.Initial:
                            if (Char.IsLetterOrDigit(ch))
                            {
                                keyStart = index;
                                state = PARSE.Keyword;
                            }
                            break;

                        case PARSE.Keyword:
                            if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                state = PARSE.Initial;
                            }
                            else if (tokens.Equal.IndexOf(ch) >= 0)
                            {
                                //Note: We have a case-insentive hashtable so we don't have to lowercase
                                key = str.Substring(keyStart, index - keyStart).Trim();
                                state = PARSE.Equal;
                            }
                            break;

                        case PARSE.Equal:
                            if (Char.IsWhiteSpace(ch))
                                break;
                            builder.Length = 0;

                            //Note: Since we allow you to alter the tokens, these are not 
                            //constant values, so we cannot use a switch statement...
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.SingleBegin;
                            }
                            else if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.DoubleBegin;
                            }
                            else if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                keywords.Update(key, String.Empty);
                                state = PARSE.Initial;
                            }
                            else
                            {
                                state = PARSE.Value;
                                builder.Append(ch);
                            }
                            break;

                        case PARSE.Value:
                            if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                keywords.Update(key, (builder.ToString()).Trim());
                                state = PARSE.Initial;
                            }
                            else
                            {
                                builder.Append(ch);
                            }
                            break;

                        case PARSE.SingleBegin:
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                                state = PARSE.SingleEnd;
                            else
                                builder.Append(ch);
                            break;

                        case PARSE.DoubleBegin:
                            if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                                state = PARSE.DoubleEnd;
                            else
                                builder.Append(ch);
                            break;

                        case PARSE.SingleEnd:
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.SingleBegin;
                                builder.Append(ch);
                            }
                            else
                            {
                                keywords.Update(key, builder.ToString());
                                state = PARSE.End;
                                goto case PARSE.End;
                            }
                            break;

                        case PARSE.DoubleEnd:
                            if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.DoubleBegin;
                                builder.Append(ch);
                            }
                            else
                            {
                                keywords.Update(key, builder.ToString());
                                state = PARSE.End;
                                goto case PARSE.End;
                            }
                            break;

                        case PARSE.End:
                            if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                state = PARSE.Initial;
                            }
                            break;

                        default:
                            throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
                    }
                }

                switch (state)
                {
                    case PARSE.Initial:
                    case PARSE.Keyword:
                    case PARSE.End:
                        break;

                    case PARSE.Equal:
                        keywords.Update(key, String.Empty);
                        break;

                    case PARSE.Value:
                        keywords.Update(key, (builder.ToString()).Trim());
                        break;

                    case PARSE.SingleBegin:
                    case PARSE.DoubleBegin:
                    case PARSE.SingleEnd:
                    case PARSE.DoubleEnd:
                        keywords.Update(key, builder.ToString());
                        break;

                    default:
                        throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
                }
            }
            return keywords;
        }
Example #22
0
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static Hashtable GetTagsHashtable(InsensitiveDictionary<string> tags)
 {
     return tags == null
         ? null
         : TagsConversionHelper.CreateTagHashtable(tags);
 }
Example #23
0
 /// <summary>
 /// Parses and validates the template.
 /// </summary>
 /// <param name="parameters">The template parameters</param>
 /// <param name="metadata">The deployment metadata</param>
 /// <returns>The processed template as a Template object.</returns>
 internal Template ParseAndValidateTemplate(InsensitiveDictionary <JToken> parameters, InsensitiveDictionary <JToken> metadata)
Example #24
0
 /// <summary>
 /// Gets a tags hash table from a tags dictionary.
 /// </summary>
 /// <param name="tags">The tags dictionary.</param>
 internal static Hashtable GetTagsHashtable(InsensitiveDictionary <string> tags)
 {
     return(tags == null
         ? null
         : TagsConversionHelper.CreateTagHashtable(tags));
 }
        public CosmosDbTriggerServiceOperationProvider()
        {
            this.serviceOperationsList = new List <ServiceOperation>();
            this.apiOperationsList     = new InsensitiveDictionary <ServiceOperation>();

            this.apiOperationsList.AddRange(new InsensitiveDictionary <ServiceOperation>
            {
                { "receiveDocument", ReceiveDocument },
            });

            this.serviceOperationsList.AddRange(new List <ServiceOperation>
            {
                { ReceiveDocument.CloneWithManifest(new ServiceOperationManifest
                    {
                        ConnectionReference = new ConnectionReferenceFormat
                        {
                            ReferenceKeyFormat = ConnectionReferenceKeyFormat.ServiceProvider,
                        },
                        Settings = new OperationManifestSettings
                        {
                            SecureData        = new OperationManifestSettingWithOptions <SecureDataOptions>(),
                            TrackedProperties = new OperationManifestSetting
                            {
                                Scopes = new OperationScope[] { OperationScope.Trigger },
                            },
                        },
                        InputsLocation = new InputsLocation[]
                        {
                            InputsLocation.Inputs,
                            InputsLocation.Parameters,
                        },
                        Outputs = new SwaggerSchema
                        {
                            Type       = SwaggerSchemaType.Object,
                            Properties = new OrdinalDictionary <SwaggerSchema>
                            {
                                {
                                    "body", new SwaggerSchema
                                    {
                                        Type        = SwaggerSchemaType.Array,
                                        Title       = "Receive document",
                                        Description = "Receive document description",
                                        Items       = new SwaggerSchema
                                        {
                                            Type       = SwaggerSchemaType.Object,
                                            Properties = new OrdinalDictionary <SwaggerSchema>
                                            {
                                                {
                                                    "contentData", new SwaggerSchema
                                                    {
                                                        Type        = SwaggerSchemaType.String,
                                                        Title       = "Content",
                                                        Format      = "byte",
                                                        Description = "content",
                                                    }
                                                },
                                                {
                                                    "Properties", new SwaggerSchema
                                                    {
                                                        Type  = SwaggerSchemaType.Object,
                                                        Title = "documentProperties",
                                                        AdditionalProperties = new JObject
                                                        {
                                                            { "type", "object" },
                                                            { "properties", new JObject {
                                                              } },
                                                            { "required", new JObject {
                                                              } },
                                                        },
                                                        Description = "document data properties",
                                                    }
                                                },
                                            },
                                        },
                                    }
                                },
                            },
                        },
                        Inputs = new SwaggerSchema
                        {
                            Type       = SwaggerSchemaType.Object,
                            Properties = new OrdinalDictionary <SwaggerSchema>
                            {
                                {
                                    "databaseName", new SwaggerSchema
                                    {
                                        Type        = SwaggerSchemaType.String,
                                        Title       = "database name",
                                        Description = "database name",
                                    }
                                },
                                {
                                    "collectionName", new SwaggerSchema
                                    {
                                        Type        = SwaggerSchemaType.String,
                                        Title       = "collection name",
                                        Description = "collection name",
                                    }
                                },
                            },
                            Required = new string[]
                            {
                                "databaseName",
                            },
                        },
                        Connector  = CosmosDbOperationApi,
                        Trigger    = TriggerType.Batch,
                        Recurrence = new RecurrenceSetting
                        {
                            Type = RecurrenceType.None,
                        },
                    }) },
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ActiveMQTriggerServiceOperationProvider"/> class.
        /// </summary>
        public ActiveMQTriggerServiceOperationProvider()
        {
            serviceOperationsList = new List <ServiceOperation>();
            apiOperationsList     = new InsensitiveDictionary <ServiceOperation>();

            apiOperationsList.AddRange(new InsensitiveDictionary <ServiceOperation>
            {
                { "ReceiveMessagesrigger", ReceiveMessagesTrigger },
            });

            serviceOperationsList.AddRange(new List <ServiceOperation>
            {
                {
                    ReceiveMessagesTrigger.CloneWithManifest(new ServiceOperationManifest
                    {
                        ConnectionReference = new ConnectionReferenceFormat
                        {
                            ReferenceKeyFormat = ConnectionReferenceKeyFormat.ServiceProvider,
                        },
                        Settings = new OperationManifestSettings
                        {
                            SecureData        = new OperationManifestSettingWithOptions <SecureDataOptions>(),
                            TrackedProperties = new OperationManifestSetting
                            {
                                Scopes = new OperationScope[] { OperationScope.Trigger },
                            },
                        },
                        InputsLocation = new InputsLocation[]
                        {
                            InputsLocation.Inputs,
                            InputsLocation.Parameters,
                        },
                        Outputs = new SwaggerSchema
                        {
                            Type       = SwaggerSchemaType.Object,
                            Properties = new OrdinalDictionary <SwaggerSchema>
                            {
                                {
                                    "body", new SwaggerSchema
                                    {
                                        Type        = SwaggerSchemaType.Array,
                                        Title       = "Messages",
                                        Description = "Receive ActiveMQ messages as array ",
                                        Items       = new SwaggerSchema
                                        {
                                            Type       = SwaggerSchemaType.Object,
                                            Properties = new OrdinalDictionary <SwaggerSchema>
                                            {
                                                {
                                                    "contentData", new SwaggerSchema
                                                    {
                                                        Type        = SwaggerSchemaType.String,
                                                        Title       = "Content",
                                                        Format      = "byte",
                                                        Description = "content",
                                                    }
                                                },
                                                {
                                                    "Properties", new SwaggerSchema
                                                    {
                                                        Type        = SwaggerSchemaType.Object,
                                                        Title       = "Properties",
                                                        Description = "ActiveMQ messages properties",
                                                        Properties  = new OrdinalDictionary <SwaggerSchema>
                                                        {
                                                            {
                                                                "NMSMessageId", new SwaggerSchema
                                                                {
                                                                    Type        = SwaggerSchemaType.String,
                                                                    Title       = "NMSMessageId",
                                                                    Format      = "byte",
                                                                    Description = "NMSMessageId",
                                                                }
                                                            },
                                                        },
                                                    }
                                                },
                                            },
                                        },
                                    }
                                },
                            },
                        },
                        Inputs = new SwaggerSchema
                        {
                            Type       = SwaggerSchemaType.Object,
                            Properties = new OrdinalDictionary <SwaggerSchema>
                            {
                                {
                                    "queue", new SwaggerSchema
                                    {
                                        Type        = SwaggerSchemaType.String,
                                        Title       = "Queue name",
                                        Description = "Queue name",
                                    }
                                },
                                {
                                    "MaximumNumber", new SwaggerSchema
                                    {
                                        Type  = SwaggerSchemaType.Number,
                                        Title = "Maximum number of messages",
                                    }
                                },
                            },
                            Required = new string[]
                            {
                                "queue",
                                "MaximumNumber"
                            },
                        },
                        Connector  = ActiveMQTriggerApi,
                        Trigger    = TriggerType.Batch,
                        Recurrence = new RecurrenceSetting
                        {
                            Type = RecurrenceType.Basic,
                        },
                    })
                },
            });
        }
        public Task <ServiceOperationResponse> InvokeOperation(string operationId, InsensitiveDictionary <JToken> connectionParameters,
                                                               ServiceOperationRequest serviceOperationRequest)
        {
            //System.IO.File.AppendAllText("c:\\temp\\lalogdll2.txt", $"\r\n({DateTime.Now}) start InvokeOperation ");

            string Error = "";

            try
            {
                ServiceOpertionsProviderValidation.OperationId(operationId);

                triggerPramsDto _triggerPramsDto = new triggerPramsDto(connectionParameters, serviceOperationRequest);

                var connectionFactory = new NmsConnectionFactory(_triggerPramsDto.UserName, _triggerPramsDto.Password, _triggerPramsDto.BrokerUri);
                using (var connection = connectionFactory.CreateConnection())
                {
                    connection.ClientId = _triggerPramsDto.ClientId;

                    using (var session = connection.CreateSession(AcknowledgementMode.Transactional))
                    {
                        using (var queue = session.GetQueue(_triggerPramsDto.QueueName))
                        {
                            using (var consumer = session.CreateConsumer(queue))
                            {
                                connection.Start();

                                List <JObject> receiveMessages = new List <JObject>();

                                for (int i = 0; i < _triggerPramsDto.MaximumNo; i++)
                                {
                                    var message = consumer.Receive(new TimeSpan(0, 0, 0, 1)) as ITextMessage;
                                    //System.IO.File.AppendAllText("c:\\temp\\lalogdll2.txt", $"\r\n({DateTime.Now}) message != null {(message != null).ToString()} ");
                                    if (message != null)
                                    {
                                        receiveMessages.Add(new JObject
                                        {
                                            { "contentData", message.Text },
                                            { "Properties", new JObject {
                                                  { "NMSMessageId", message.NMSMessageId }
                                              } },
                                        });
                                    }
                                    else
                                    {
                                        //the we will exit the loop if there are no message
                                        break;
                                    }
                                }
                                session.Commit();
                                session.Close();
                                connection.Close();

                                if (receiveMessages.Count == 0)
                                {
                                    //System.IO.File.AppendAllText("c:\\temp\\lalogdll2.txt", $"\r\n({DateTime.Now}) Skip  { JObject.FromObject(new { message = "No messages"} ) }");
                                    return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JObject.FromObject(new { message = "No messages" }), System.Net.HttpStatusCode.Accepted)));
                                }
                                else
                                {
                                    //System.IO.File.AppendAllText("c:\\temp\\lalogdll2.txt", $"\r\n({DateTime.Now}) Ok  {JArray.FromObject(receiveMessages)}");

                                    return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JArray.FromObject(receiveMessages), System.Net.HttpStatusCode.OK)));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Error = e.Message;
                //System.IO.File.AppendAllText("c:\\temp\\lalogdll2.txt", $"\r\n({DateTime.Now}) error {e.Message}");
            }

            return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JObject.FromObject(new { message = Error }), System.Net.HttpStatusCode.InternalServerError)));
        }
        /// <summary>
        /// the InvokeOperation will be executed periodical to fetch the new ActiveMQ messages
        /// </summary>
        /// <param name="operationId"></param>
        /// <param name="connectionParameters"></param>
        /// <param name="serviceOperationRequest"></param>
        /// <returns></returns>
        public Task <ServiceOperationResponse> InvokeOperation(string operationId, InsensitiveDictionary <JToken> connectionParameters,
                                                               ServiceOperationRequest serviceOperationRequest)
        {
            try
            {
                ServiceOpertionsProviderValidation.OperationId(operationId);

                ActiveMQTriggerParameters activeMQTriggerParameters = new ActiveMQTriggerParameters(connectionParameters, serviceOperationRequest);

                var connectionFactory = new NmsConnectionFactory(activeMQTriggerParameters.UserName, activeMQTriggerParameters.Password, activeMQTriggerParameters.BrokerUri);
                using (var connection = connectionFactory.CreateConnection())
                {
                    connection.ClientId = activeMQTriggerParameters.ClientId;

                    using (var session = connection.CreateSession(AcknowledgementMode.Transactional))
                    {
                        using (var queue = session.GetQueue(activeMQTriggerParameters.QueueName))
                        {
                            using (var consumer = session.CreateConsumer(queue))
                            {
                                connection.Start();

                                List <JObject> receiveMessages = new List <JObject>();

                                for (int i = 0; i < activeMQTriggerParameters.MaximumNumber; i++)
                                {
                                    var message = consumer.Receive(messageReceiveTimeout) as ITextMessage;
                                    if (message != null)
                                    {
                                        receiveMessages.Add(new JObject
                                        {
                                            { "contentData", message.Text },
                                            { "Properties", new JObject {
                                                  { "NMSMessageId", message.NMSMessageId }
                                              } },
                                        });
                                    }
                                    else
                                    {
                                        //Will exit the loop if there are no message
                                        break;
                                    }
                                }
                                session.Commit();
                                session.Close();
                                connection.Close();

                                if (receiveMessages.Count == 0)
                                {
                                    return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JObject.FromObject(new { message = "No messages" }), System.Net.HttpStatusCode.Accepted)));
                                }
                                else
                                {
                                    return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JArray.FromObject(receiveMessages), System.Net.HttpStatusCode.OK)));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                return(Task.FromResult((ServiceOperationResponse) new ActiveMQTriggerResponse(JObject.FromObject(new { message = error }), System.Net.HttpStatusCode.InternalServerError)));
            }
        }
 public Task <ServiceOperationResponse> InvokeActionOperation(string operationId, InsensitiveDictionary <JToken> connectionParameters, ServiceOperationRequest serviceOperationRequest)
 {
     throw new NotImplementedException();
 }