public void Template()
        {
            string action = HttpHosting.Context.Request.GetParameter("action");

            if (action == "help")
            {
                string fileName = String.Concat(Cms.PhysicPath,
                                                CmsVariables.TEMP_PATH,
                                                "tpl_lang_guid.xml");
                AutoObjectXml obj = new AutoObjectXml(fileName);
                obj.InsertFromType(typeof(CmsTemplateImpl), false);
                obj.Flush();

                var rsp = HttpHosting.Context.Response;
                rsp.WriteAsync(XmlObjectDoc.DocStyleSheet);

                int tmpInt = 0;
                foreach (XmlObject _obj in obj.GetObjects())
                {
                    rsp.WriteAsync(XmlObjectDoc.GetGrid(_obj, ++tmpInt));
                }
            }
            else
            {
                HttpHosting.Context.Response.WriteAsync(TemplateUtility.GetTemplatePagesHTML());
            }
        }
        public void GetsDynamicParametersForTemplateFile()
        {
            RuntimeDefinedParameterDictionary result = TemplateUtility.GetTemplateParametersFromFile(
                templateFile,
                null,
                null,
                new[] { "TestPS" });

            Assert.Equal(7, result.Count);

            Assert.Equal("string", result["string"].Name);
            Assert.Equal(typeof(string), result["String"].ParameterType);

            Assert.Equal("int", result["int"].Name);
            Assert.Equal(typeof(int), result["int"].ParameterType);

            Assert.Equal("securestring", result["securestring"].Name);
            Assert.Equal(typeof(SecureString), result["securestring"].ParameterType);

            Assert.Equal("bool", result["bool"].Name);
            Assert.Equal(typeof(bool), result["bool"].ParameterType);

            Assert.Equal("object", result["object"].Name);
            Assert.Equal(typeof(Hashtable), result["object"].ParameterType);

            Assert.Equal("secureObject", result["secureObject"].Name);
            Assert.Equal(typeof(Hashtable), result["secureObject"].ParameterType);

            Assert.Equal("array", result["array"].Name);
            Assert.Equal(typeof(object[]), result["array"].ParameterType);
        }
        public void ConstructsArrayTypeDynamicParameter()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "ranks";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    JArray.Parse("[\"1\", \"3\", \"5\"]"),
                    JArray.Parse("[\"A\", \"D\", \"F\"]"),
                },
                DefaultValue = JArray.Parse("[\"A\", \"D\", \"F\"]"),
                Type         = "array"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("ranks", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(object[]), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            var    url      = "http://schemas.altazion.com/sys/template.xsd";
            string savePath = DownloadSchema(url);

            TemplateUtility util = new TemplateUtility(savePath, Directory.GetCurrentDirectory());

            // on enregistre des handlers pour afficher la progreesion
            // dans la console de l'action
            util.ProcessStepStart      += Validation_stepStarted;
            util.ProcessStepCompletion += Validation_stepCompleted;
            util.ProcessStart          += Validation_ProcessStarted;
            util.ProcessCompletion     += Validation_ProcessCompleted;

            var result = util.StartTemplateValidationProcess();

            if (result.IsSuccess)
            {
                util.StartZipProcess("final.zip");
            }
            else
            {
                throw new Exception("Echec du traitement de votre template");
            }
        }
Beispiel #5
0
        public void Template()
        {
            string action = System.Web.HttpContext.Current.Request["action"];

            if (action == "help")
            {
                string fileName = String.Concat(Cms.PyhicPath,
                                                CmsVariables.TEMP_PATH,
                                                "tpl_lang_guid.xml");
                AutoObjectXml obj = new AutoObjectXml(fileName);
                obj.InsertFromType(typeof(CmsTemplateImpl), false);
                obj.Flush();

                var rsp = System.Web.HttpContext.Current.Response;
                rsp.Write(XmlObjectDoc.DocStyleSheet);

                int tmpInt = 0;
                foreach (XmlObject _obj in obj.GetObjects())
                {
                    rsp.Write(XmlObjectDoc.GetGrid(_obj, ++tmpInt));
                }
            }
            else
            {
                TemplateUtility.PrintTemplatesInfo();
            }
        }
        public void ResolvesDuplicatedDynamicParameterName()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "Name";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    "Mode1", "Mode2", "Mode3"
                },
                MaxLength = "5",
                MinLength = "1",
                Type      = "bool"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal(key + "FromTemplate", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(bool), dynamicParameter.ParameterType);
            Assert.Equal(2, dynamicParameter.Attributes.Count);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.True(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);

            ValidateLengthAttribute validateLengthAttribute = (ValidateLengthAttribute)dynamicParameter.Attributes[1];

            Assert.Equal(int.Parse(value.MinLength), validateLengthAttribute.MinLength);
            Assert.Equal(int.Parse(value.MaxLength), validateLengthAttribute.MaxLength);
        }
Beispiel #7
0
 void FillTemplateFile(
     string templateFile,
     IReadOnlyCollection <string> definitions          = null,
     IReadOnlyDictionary <string, string> replacements = null)
 {
     TemplateUtility.FillTemplateFile(templateFile, definitions, replacements);
 }
        public void ConstructsDynamicParameterWithNullAllowedValues()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "computeMode";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = null,
                DefaultValue  = "Mode1",
                Type          = "securestring"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("computeMode", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(SecureString), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
        public void ConstructsObjectTypeDynamicParameter()
        {
            string[] parameters        = { "Name", "Location", "Mode" };
            string[] parameterSetNames = { "__AllParameterSets" };
            string   key = "appSku";
            TemplateFileParameterV1 value = new TemplateFileParameterV1()
            {
                AllowedValues = new List <object>()
                {
                    JObject.Parse("{\"code\" : \"F1\", \"name\" : \"Free\"}"),
                    JObject.Parse("{\"code\" : \"F2\", \"name\" : \"Shared\"}"),
                },
                DefaultValue = JObject.Parse("{\"code\" : \"F1\", \"name\" : \"Free\"}"),
                Type         = "object"
            };
            KeyValuePair <string, TemplateFileParameterV1> parameter = new KeyValuePair <string, TemplateFileParameterV1>(key, value);

            RuntimeDefinedParameter dynamicParameter = TemplateUtility.ConstructDynamicParameter(parameters, parameter);

            Assert.Equal("appSku", dynamicParameter.Name);
            Assert.Equal(value.DefaultValue, dynamicParameter.Value);
            Assert.Equal(typeof(Hashtable), dynamicParameter.ParameterType);
            Assert.Single(dynamicParameter.Attributes);

            ParameterAttribute parameterAttribute = (ParameterAttribute)dynamicParameter.Attributes[0];

            Assert.False(parameterAttribute.Mandatory);
            Assert.True(parameterAttribute.ValueFromPipelineByPropertyName);
            Assert.Equal(parameterSetNames[0], parameterAttribute.ParameterSetName);
        }
        public void ParseTemplateParameterFileContents_DeserializeWithCorrectType()
        {
            Dictionary <string, TemplateFileParameterV1> result =
                TemplateUtility.ParseTemplateParameterFileContents(@"Resources\WebSite.param.dev.json");

            Assert.Equal(true, result["isWorker"].Value);
            Assert.Equal((System.Int64) 1, result["numberOfWorker"].Value);
        }
        protected Hashtable GetTemplateParameterObject(Hashtable templateParameterObject)
        {
            // NOTE(jogao): create a new Hashtable so that user can re-use the templateParameterObject.
            var prameterObject = new Hashtable();

            if (templateParameterObject != null)
            {
                foreach (var parameterKey in templateParameterObject.Keys)
                {
                    // Let default behavior of a value parameter if not a KeyVault reference Hashtable
                    var hashtableParameter = templateParameterObject[parameterKey] as Hashtable;
                    if (hashtableParameter != null && hashtableParameter.ContainsKey("reference"))
                    {
                        prameterObject[parameterKey] = templateParameterObject[parameterKey];
                    }
                    else
                    {
                        prameterObject[parameterKey] = new Hashtable {
                            { "value", templateParameterObject[parameterKey] }
                        };
                    }
                }
            }

            // Load parameters from the file
            string templateParameterFilePath = this.ResolvePath(TemplateParameterFile);

            if (templateParameterFilePath != null && FileUtilities.DataStore.FileExists(templateParameterFilePath))
            {
                var parametersFromFile = TemplateUtility.ParseTemplateParameterFileContents(templateParameterFilePath);
                parametersFromFile.ForEach(dp =>
                {
                    var parameter = new Hashtable();
                    if (dp.Value.Value != null)
                    {
                        parameter.Add("value", dp.Value.Value);
                    }
                    if (dp.Value.Reference != null)
                    {
                        parameter.Add("reference", dp.Value.Reference);
                    }

                    prameterObject[dp.Key] = parameter;
                });
            }

            // Load dynamic parameters
            IEnumerable <RuntimeDefinedParameter> parameters = PowerShellUtilities.GetUsedDynamicParameters(this.AsJobDynamicParameters, MyInvocation);

            if (parameters.Any())
            {
                parameters.ForEach(dp => prameterObject[((ParameterAttribute)dp.Attributes[0]).HelpMessage] = new Hashtable {
                    { "value", dp.Value }
                });
            }

            return(prameterObject);
        }
Beispiel #12
0
    void FillTemplateFile(
        string templateFile,
        IReadOnlyCollection <string> definitions          = null,
        IReadOnlyDictionary <string, string> replacements = null)
    {
        var templateContent = ReadAllText(templateFile);

        WriteAllText(templateFile, TemplateUtility.FillTemplate(templateContent, definitions, replacements));
    }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                //Set the Locale for Bot
                activity.Locale = TemplateUtility.GetLocale(activity);

                var messageActivity = StripBotAtMentions.StripAtMentionText(activity);
                try
                {
                    await Conversation.SendAsync(messageActivity, () => new Dialogs.RootDialog());
                }
                catch (Exception ex)
                {
                }
            }
            else if (activity.Type == ActivityTypes.Invoke) // Received an invoke
            {
                // Handle ComposeExtension query
                if (activity.IsComposeExtensionQuery())
                {
                    var invokeResponse = this.GetComposeExtensionResponse(activity);
                    return(Request.CreateResponse <ComposeExtensionResponse>(HttpStatusCode.OK, invokeResponse));
                }
                else if (activity.IsO365ConnectorCardActionQuery())
                {
                    return(await HandleO365ConnectorCardActionQuery(activity));
                }
                else
                {
                    var messageActivity = (IMessageActivity)null;

                    if (activity.Name == "actionableMessage/executeAction")
                    {
                        messageActivity = ParseInvokeActivityRequest.ParseO365ConnectorCardInvokeRequest(activity);
                    }
                    else
                    {
                        messageActivity = ParseInvokeActivityRequest.ParseInvokeRequest(activity);
                    }

                    await Conversation.SendAsync(messageActivity, () => new Dialogs.RootDialog());

                    // Handle other types of invoke
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }

            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
 public void ParseTemplateParameterFileContents_DeserializeWithCorrectType()
 {
     // Add up to 3 retries for flaky test
     TestExecutionHelpers.RetryAction(() =>
     {
         Dictionary <string, TemplateFileParameterV1> result =
             TemplateUtility.ParseTemplateParameterFileContents(@"Resources/WebSite.param.dev.json".AsAbsoluteLocation());
         Assert.True(result["isWorker"].Value as bool?);
         Assert.Equal((System.Int64) 1, result["numberOfWorker"].Value);
     });
 }
        public void GetTemplateParametersFromObject()
        {
            Hashtable templateParameterObject = new Hashtable();

            templateParameterObject["string"] = "myvalue";
            templateParameterObject["int"]    = 12;
            templateParameterObject["bool"]   = true;
            templateParameterObject["object"] = new Hashtable()
            {
                { "code", "F1" },
                { "name", "Free" }
            };
            templateParameterObject["array"] = new object[] {
                "A", "D", "F"
            };


            RuntimeDefinedParameterDictionary result = TemplateUtility.GetTemplateParametersFromFile(
                templateFile,
                templateParameterObject,
                null,
                new[] { "TestPS" });

            Assert.Equal(7, result.Count);

            Assert.Equal("string", result["string"].Name);
            Assert.Equal(typeof(string), result["string"].ParameterType);
            Assert.Equal("myvalue", result["string"].Value);

            Assert.Equal("int", result["int"].Name);
            Assert.Equal(typeof(int), result["int"].ParameterType);
            Assert.Equal(12, result["int"].Value);

            Assert.Equal("bool", result["bool"].Name);
            Assert.Equal(typeof(bool), result["bool"].ParameterType);
            Assert.True(result["bool"].Value as bool?);

            Assert.Equal("object", result["object"].Name);
            Assert.Equal(typeof(Hashtable), result["object"].ParameterType);
            Hashtable objectValue = result["object"].Value as Hashtable;

            Assert.Equal(2, objectValue.Count);
            Assert.Equal("F1", objectValue["code"]);
            Assert.Equal("Free", objectValue["name"]);

            Assert.Equal("array", result["array"].Name);
            Assert.Equal(typeof(object[]), result["array"].ParameterType);
            var arrayValue = result["array"].Value as object[];

            Assert.Equal(3, arrayValue.Length);
            Assert.Equal("A", arrayValue[0]);
            Assert.Equal("F", arrayValue[2]);
        }
Beispiel #16
0
        public void PrintVariables(Jiffy.Essence essence)
        {
            PushIndent(essence.indent);

            WriteLine("/// <summary>");
            WriteLine("/// Type: Monoscript");
            WriteLine("/// <summary>");
            WriteLine("protected SerializedProperty m_Script;");
            essence.Foreach((FieldInfo info) =>
            {
        #line default
        #line hidden

        #line 59 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
                this.Write("/// <summary>\r\n/// Type: ");


        #line default
        #line hidden

        #line 61 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
                this.Write(this.ToStringHelper.ToStringWithCulture(TemplateUtility.NiceTypeName(info.FieldType)));


        #line default
        #line hidden

        #line 61 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
                this.Write("\r\n/// </summary>\r\nprotected SerializedProperty ");


        #line default
        #line hidden

        #line 63 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
                this.Write(this.ToStringHelper.ToStringWithCulture(info.Name));


        #line default
        #line hidden

        #line 63 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
                this.Write(";\r\n");


        #line default
        #line hidden

        #line 64 "C:\Users\Byron\Documents\jiffy-editor\proj.cs\JiffyEditor\Jiffy\Templates\Generators\SimpleEditor.t4"
            });
            PopIndent();
        }
Beispiel #17
0
        public static VmTemplate ToVirtualTemplate(this ConvergedTemplate template, string isolationTag = "")
        {
            TemplateUtility tu = new TemplateUtility(template.Detail);

            tu.Name            = template.Name;
            tu.Networks        = template.Networks ?? "lan";
            tu.Iso             = template.Iso;
            tu.IsolationTag    = isolationTag.HasValue() ? isolationTag : template.WorkspaceGlobalId ?? Guid.Empty.ToString();
            tu.Id              = template.Id.ToString();
            tu.UseUplinkSwitch = template.WorkspaceUseUplinkSwitch;
            tu.AddGuestSettings(template.Guestinfo ?? "");
            return(tu.AsTemplate());
        }
        public void HandlesInvalidTemplateFiles()
        {
            Hashtable hashtable = new Hashtable();

            hashtable["Bool"] = true;
            hashtable["Foo"]  = "bar";
            RuntimeDefinedParameterDictionary result = TemplateUtility.GetTemplateParametersFromFile(
                invalidTemplateFile,
                null,
                templateParameterFileSchema1,
                new[] { "TestPS" });

            Assert.Empty(result);
        }
        public object GetDynamicParameters()
        {
            if (!string.IsNullOrEmpty(TemplateFile) &&
                !TemplateFile.Equals(templateFile, StringComparison.OrdinalIgnoreCase))
            {
                templateFile = TemplateFile;
                if (string.IsNullOrEmpty(TemplateParameterUri))
                {
                    dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                        this.ResolvePath(TemplateFile),
                        TemplateParameterObject,
                        this.ResolvePath(TemplateParameterFile),
                        MyInvocation.MyCommand.Parameters.Keys.ToArray());
                }
                else
                {
                    dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                        this.ResolvePath(TemplateFile),
                        TemplateParameterObject,
                        TemplateParameterUri,
                        MyInvocation.MyCommand.Parameters.Keys.ToArray());
                }
            }
            else if (!string.IsNullOrEmpty(TemplateUri) &&
                     !TemplateUri.Equals(templateUri, StringComparison.OrdinalIgnoreCase))
            {
                templateUri = TemplateUri;
                if (string.IsNullOrEmpty(TemplateParameterUri))
                {
                    dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                        TemplateUri,
                        TemplateParameterObject,
                        this.ResolvePath(TemplateParameterFile),
                        MyInvocation.MyCommand.Parameters.Keys.ToArray());
                }
                else
                {
                    dynamicParameters = TemplateUtility.GetTemplateParametersFromFile(
                        TemplateUri,
                        TemplateParameterObject,
                        TemplateParameterUri,
                        MyInvocation.MyCommand.Parameters.Keys.ToArray());
                }
            }

            RegisterDynamicParameters(dynamicParameters);

            return(dynamicParameters);
        }
        /// <summary>
        /// Handle when a message is addressed to the bot.
        /// </summary>
        /// <param name="turnContext">The turn context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>
        /// For more information on bot messaging in Teams, see the documentation
        /// https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/conversation-basics?tabs=dotnet#receive-a-message .
        /// </remarks>
        protected override async Task OnMessageActivityAsync(
            ITurnContext <IMessageActivity> turnContext,
            CancellationToken cancellationToken)
        {
            // Set the Locale for Bot
            turnContext.Activity.Locale = TemplateUtility.GetLocale(turnContext.Activity);

            // Run the Dialog with the new message Activity.
            await _dialog.Run(
                turnContext,
                _conversationState.CreateProperty <DialogState>(nameof(DialogState)),
                cancellationToken);

            await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
        public void Template_resolver_visual_studio_template_correctly(MockContainer <TemplateResolver> templateResolver, ITemplate buildTemplate)
        {
            "Given I have a template resolver"
            ._(() => templateResolver = B.AutoMock <TemplateResolver>());

            "And default configuration"
            ._(() => DefaultConfigurationUtility.PostInit(templateResolver.GetMock <IConfiguration>()));

            "And a set of templates"
            ._(() => TemplateUtility.Defaults(templateResolver.Subject));

            "When I call resolve"
            ._(() => buildTemplate = templateResolver.Subject.Resolve(TemplateType.Source));

            "Then I get a build template back"
            ._(() => buildTemplate.Should().BeOfType <Template>());
        }
Beispiel #22
0
        public static async Task <bool> DownloadExternalFile(
            string externalFile,
            int timeout,
            Action <string, string> warningSink,
            Action <string, string> errorSink)
        {
            try
            {
                var lines         = File.ReadAllLines(externalFile).Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
                var uriConversion = Uri.TryCreate(lines.FirstOrDefault(), UriKind.Absolute, out var uri);
                ControlFlow.Assert(uriConversion, $"Could not parse URI for external file from first line of '{externalFile}'.");

                var outputFile   = externalFile.Substring(0, externalFile.Length - 4);
                var previousHash = File.Exists(outputFile) ? FileSystemTasks.GetFileHash(outputFile) : null;

                var template = await HttpTasks.HttpDownloadStringAsync(uri.OriginalString);

                var replacements = lines.Skip(1)
                                   .Where(x => x.Contains('='))
                                   .Select(x => x.Split('='))
                                   .Where(x => x.Length == 2)
                                   .ToDictionary(
                    x => $"_{x.First().Trim('_').ToUpperInvariant()}_",
                    x => x.ElementAt(1));
                var definitions = lines.Skip(1)
                                  .Where(x => !x.Contains('=') && !string.IsNullOrWhiteSpace(x))
                                  .Select(x => x.ToUpperInvariant())
                                  .ToList();

                File.WriteAllText(outputFile, TemplateUtility.FillTemplate(template, definitions, replacements));
                var newHash = FileSystemTasks.GetFileHash(outputFile);

                if (newHash != previousHash)
                {
                    warningSink(externalFile, "External file has been updated.");
                }

                return(true);
            }
            catch (Exception exception)
            {
                errorSink(externalFile, exception.Message);
                return(false);
            }
        }
Beispiel #23
0
        private ComposeExtensionResponse GetComposeExtensionResponse(Activity activity)
        {
            var composeExtensionQuery = activity.GetComposeExtensionQueryData();
            var composeExtParamValue  = composeExtensionQuery.Parameters[0].Value.ToString();
            // Process data and return the response.
            ComposeExtensionResponse          composeExtensionResponse      = new ComposeExtensionResponse();
            ComposeExtensionResult            composeExtensionResult        = new ComposeExtensionResult();
            List <ComposeExtensionAttachment> lstComposeExtensionAttachment = new List <ComposeExtensionAttachment>();
            string imageUrl    = "https://luna1.co/cae4f2.png";
            string deepLinkUrl = TemplateUtility.GetDeepLink(activity, composeExtParamValue);

            lstComposeExtensionAttachment.Add(TemplateUtility.CreateComposeExtensionCardsAttachments("Deep Link", "Clicking on the button will redirect you to the configuration tab", imageUrl, "hero", deepLinkUrl));
            composeExtensionResult.Type               = "result";
            composeExtensionResult.AttachmentLayout   = "list";
            composeExtensionResult.Attachments        = lstComposeExtensionAttachment;
            composeExtensionResponse.ComposeExtension = composeExtensionResult;
            return(composeExtensionResponse);
        }
        private ComposeExtensionResponse GetComposeExtensionResponse(Activity activity)
        {
            var composeExtensionQuery = activity.GetComposeExtensionQueryData();
            var composeExtParamValue  = composeExtensionQuery.Parameters[0].Value.ToString();
            // Process data and return the response.
            ComposeExtensionResponse          composeExtensionResponse      = new ComposeExtensionResponse();
            ComposeExtensionResult            composeExtensionResult        = new ComposeExtensionResult();
            List <ComposeExtensionAttachment> lstComposeExtensionAttachment = new List <ComposeExtensionAttachment>();
            string imageUrl    = "https://luna1.co/cae4f2.png";
            string deepLinkUrl = TemplateUtility.GetDeepLink(activity, composeExtParamValue);

            lstComposeExtensionAttachment.Add(TemplateUtility.GenerateComposeExtentionAttachments(activity));
            composeExtensionResult.Type               = "result";
            composeExtensionResult.AttachmentLayout   = "list";
            composeExtensionResult.Attachments        = lstComposeExtensionAttachment;
            composeExtensionResponse.ComposeExtension = composeExtensionResult;
            return(composeExtensionResponse);
        }
Beispiel #25
0
        private async Task <DialogTurnResult> BeginUpdateCardMsgDialogAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (stepContext == null)
            {
                throw new ArgumentNullException(nameof(stepContext));
            }
            var existingState = await this._conversationState.GetAsync(stepContext.Context, () => new RootDialogState());

            if (!string.IsNullOrEmpty(stepContext.Context.Activity.ReplyToId))
            {
                IMessageActivity activity = stepContext.Context.Activity;

                updateCounter = TemplateUtility.ParseUpdateCounterJson((Activity)activity);

                var updatedMessage = CreateUpdatedMessage(stepContext);

                ConnectorClient client = new ConnectorClient(new Uri(stepContext.Context.Activity.ServiceUrl), ConfigurationManager.AppSettings["MicrosoftAppId"], ConfigurationManager.AppSettings["MicrosoftAppPassword"]);

                try
                {
                    ResourceResponse resp = await client.Conversations.UpdateActivityAsync(stepContext.Context.Activity.Conversation.Id, stepContext.Context.Activity.ReplyToId, (Activity)updatedMessage);

                    await stepContext.Context.SendActivityAsync(Strings.UpdateCardMessageConfirmation);
                }
                catch (Exception ex)
                {
                    await stepContext.Context.SendActivityAsync(Strings.ErrorUpdatingCard + ex.Message);
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(Strings.NoMsgToUpdate);
            }

            //Set the Last Dialog in Conversation Data
            var currentState = await this._conversationState.GetAsync(stepContext.Context, () => new RootDialogState());

            currentState.LastDialogKey = Strings.LastDialogSetupUpdateCard;
            await this._conversationState.SetAsync(stepContext.Context, currentState);

            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
        /*  public void sendToast(int timeAddedSec, string toastdescription, string toastTitle)
         * {
         *    Debug.WriteLine("toast");
         *    try
         *    {
         *        DateTime dueTime = DateTime.Now.AddSeconds(timeAddedSec);
         *        // Set up the notification text.
         *        var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
         *        var strings = toastXml.GetElementsByTagName("text");
         *        strings[0].AppendChild(toastXml.CreateTextNode(toastTitle));
         *        strings[1].AppendChild(toastXml.CreateTextNode(toastdescription));
         *
         *        // Create the toast notification object.
         *        var toast = new ScheduledToastNotification(toastXml, DateTime.Now);
         *        var idNumber = 5;  // Generates a unique ID number for the notification.
         *        toast.Id = "Toast" + idNumber;
         *
         *        // Add to the schedule.
         *        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
         *    }
         *    catch (Exception e)
         *    { Debug.WriteLine("toast exception = "+e.ToString()); }
         *
         *
         *
         *
         *
         * }*/
        void SendToast(string heading, string createdAt)
        {
            ToastNotifier toastNotifier   = ToastNotificationManager.CreateToastNotifier();
            XmlDocument   xmlToastContent = ToastNotificationManager.GetTemplateContent(
                ToastTemplateType.ToastImageAndText01);

            TemplateUtility.CompleteTemplate(
                xmlToastContent,
                new string[] { heading },
                new string[] { createdAt },
                "ms-winsoundevent:Notification.Mail");
            // TODO: change delivery time
            ScheduledToastNotification toastNotification = new ScheduledToastNotification(xmlToastContent,
                                                                                          (new DateTimeOffset(DateTime.Now) + TimeSpan.FromSeconds(10)));

            // TODO: change identifier
            toastNotification.Id = "AirTnT";
            toastNotifier.AddToSchedule(toastNotification);
        }
        public void GetTemplateParametersFromFileWithSchema2MergesObjects()
        {
            Hashtable hashtable = new Hashtable();

            hashtable["Bool"] = true;
            hashtable["Foo"]  = "bar";
            RuntimeDefinedParameterDictionary result = TemplateUtility.GetTemplateParametersFromFile(
                templateFile,
                null,
                templateParameterFileSchema2,
                new[] { "TestPS" });

            Assert.Equal(7, result.Count);

            Assert.Equal("string", result["string"].Name);
            Assert.Equal(typeof(string), result["string"].ParameterType);
            Assert.Equal("myvalue", result["string"].Value);

            Assert.Equal("int", result["int"].Name);
            Assert.Equal(typeof(int), result["int"].ParameterType);
            Assert.Equal("12", result["int"].Value);

            Assert.Equal("bool", result["bool"].Name);
            Assert.Equal(typeof(bool), result["bool"].ParameterType);
            Assert.Equal("True", result["bool"].Value);

            Assert.Equal("object", result["object"].Name);
            Assert.Equal(typeof(Hashtable), result["object"].ParameterType);
            JObject objectValue = result["object"].Value as JObject;

            Assert.Equal(2, objectValue.Count);
            Assert.Equal("F1", objectValue["code"].ToObject <string>());
            Assert.Equal("Free", objectValue["name"].ToObject <string>());

            Assert.Equal("array", result["array"].Name);
            Assert.Equal(typeof(object[]), result["array"].ParameterType);
            var arrayValue = result["array"].Value as JArray;

            Assert.Equal(3, arrayValue.Count);
            Assert.Equal("A", arrayValue[0].ToObject <string>());
            Assert.Equal("F", arrayValue[2].ToObject <string>());
        }
Beispiel #28
0
        public async Task StartAsync(IDialogContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            //Set the Last Dialog in Conversation Data
            context.UserData.SetValue(Strings.LastDialogKey, Strings.LastDialogThumbnailCard);

            var message    = context.MakeMessage();
            var attachment = GetThumbnailCard();

            message.Attachments.Add(attachment);
            message.Attachments.Add(TemplateUtility.GetChoiceOptionCard());

            await context.PostAsync((message));

            context.Done <object>(null);
        }
Beispiel #29
0
        private async Task <bool> DownloadExternalFile(ExternalFilesData data)
        {
            try
            {
                var previousHash = File.Exists(data.OutputPath) ? FileSystemTasks.GetFileHash(data.OutputPath) : null;

                var template = (await HttpTasks.HttpDownloadStringAsync(data.Uri.OriginalString)).SplitLineBreaks();
                TextTasks.WriteAllLines(data.OutputPath, TemplateUtility.FillTemplate(template, data.Tokens));

                var newHash = FileSystemTasks.GetFileHash(data.OutputPath);
                if (newHash != previousHash)
                {
                    LogWarning(message: $"External file '{data.OutputPath}' has been updated.", file: data.Identity);
                }

                return(true);
            }
            catch (Exception exception)
            {
                LogError(message: exception.Message, file: data.Identity);
                return(false);
            }
        }
        public async Task StartAsync(IDialogContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!string.IsNullOrEmpty(context.Activity.ReplyToId))
            {
                Activity activity = context.Activity as Activity;
                updateCounter = TemplateUtility.ParseUpdateCounterJson(activity);

                var updatedMessage = CreateUpdatedMessage(context);

                ConnectorClient client = new ConnectorClient(new Uri(context.Activity.ServiceUrl));

                try
                {
                    ResourceResponse resp = await client.Conversations.UpdateActivityAsync(context.Activity.Conversation.Id, context.Activity.ReplyToId, (Activity)updatedMessage);

                    await context.PostAsync(Strings.UpdateCardMessageConfirmation);
                }
                catch (Exception ex)
                {
                    await context.PostAsync(Strings.ErrorUpdatingCard + ex.Message);
                }
            }
            else
            {
                await context.PostAsync(Strings.NoMsgToUpdate);
            }

            context.Done <object>(null);

            //Set the Last Dialog in Conversation Data
            context.UserData.SetValue(Strings.LastDialogKey, Strings.LastDialogSetupUpdateCard);
        }