Exemple #1
0
        public void ImageBackgroundColor()
        {
            var json = @"{
    ""type"": ""AdaptiveCard"",
    ""version"": ""1.0"",
    ""body"": [
    {
        ""type"": ""Image"",
        ""url"": ""http://adaptivecards.io/content/cats/2.png"",
        ""backgroundColor"" : ""Blue""
    },
    {
        ""type"": ""Image"",
        ""url"": ""http://adaptivecards.io/content/cats/2.png"",
        ""backgroundColor"" : ""#FF00FF""
    },
    {
        ""type"": ""Image"",
        ""url"": ""http://adaptivecards.io/content/cats/2.png"",
        ""backgroundColor"" : ""#FF00FFAA""
    },
    {
        ""type"": ""Image"",
        ""url"": ""http://adaptivecards.io/content/cats/2.png"",
        ""backgroundColor"" : ""#FREEBACE""
    },
    {
        ""type"": ""Image"",
        ""url"": ""http://adaptivecards.io/content/cats/2.png"",
        ""backgroundColor"" : ""#GREENS""
    }
    ]
}";

            // There should be 3 invalid colors in this card
            var parseResult = AdaptiveCard.FromJson(json);

            Assert.AreEqual(3, parseResult.Warnings.Count);
        }
Exemple #2
0
        public void EmptyRichTextBlock()
        {
            var json = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""body"": [
    {
      ""type"": ""RichTextBlock"",
      ""inlines"": []
    }
  ]
}";

            var card = AdaptiveCard.FromJson(json).Card;

            // Validate RTB
            var richTB1 = card.Body[0] as AdaptiveRichTextBlock;

            Assert.IsTrue(richTB1.Inlines.Count == 0);

            Assert.AreEqual(json, card.ToJson());
        }
Exemple #3
0
        public void TestStyleNullDeserialization()
        {
            var json = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""ColumnSet"",
      ""columns"": [
           {
              ""type"": ""Column"",
              ""style"": null
           }
       ]
    }
  ]
}";

            var result = AdaptiveCard.FromJson(json);

            Assert.IsNotNull(result.Card);
        }
Exemple #4
0
        public void TestElementStretch()
        {
            var payload =
                @"{
                      ""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"",
                      ""type"": ""AdaptiveCard"",
                      ""version"": ""1.0"",
                      ""body"": [
                          {
                              ""type"": ""TextBlock"",
                              ""text"": ""This is a textblock"",
                              ""height"": ""stretch""
                          }
                      ]
                  }";

            var result = AdaptiveCard.FromJson(payload);
            var card   = result?.Card;

            Assert.AreEqual(card.Body.Count, 1);
            Assert.AreEqual(card.Body[0].Height, AdaptiveHeight.Stretch);
        }
        /// <summary>
        /// Creates the edit team settings card
        /// </summary>
        /// <param name="teamId">Team id</param>
        /// <param name="teamName">User discipline</param>
        /// <param name="adminUser">Admin user. Can be null if bot installed by Graph or changed to no admin</param>
        /// <param name="teamNotifyMode">How pairings will be notified</param>
        /// <param name="subteamNames">Sub team names hints for Edit Profile page</param>
        /// <returns>user profile card</returns>
        public static AdaptiveCard GetCard(string teamId, string teamName, User adminUser, string teamNotifyMode, string subteamNames)
        {
            var variablesToValues = new Dictionary <string, string>()
            {
                { "teamId", teamId },
                { "teamName", teamName },
                { "noApprovalValue", TeamInstallInfo.NotifyModeNoApproval },
                { "needApprovalValue", TeamInstallInfo.NotifyModeNeedApproval },
                { "defaultNotifyMode", teamNotifyMode },
                { "subteamNames", subteamNames },
                { "adminUserName", adminUser == null ? string.Empty : adminUser.Name },
                { "originalAdminUserId", adminUser == null ? string.Empty : adminUser.AadId },
                { "originalAdminUserName", adminUser == null ? string.Empty : adminUser.Name }
            };

            var cardJson = AdaptiveCardHelper.ReplaceTemplateKeys(CardTemplate, variablesToValues);

            // There is an AdaptiveCard template library but it's only for .NET core.
            var card = AdaptiveCard.FromJson(cardJson).Card;

            return(card);
        }
Exemple #6
0
        private AdaptiveCard CreateRefreshCard(List <Models.Comment> comments)
        {
            Assembly     _assembly;
            StreamReader _textStreamReader;

            _assembly         = Assembly.GetExecutingAssembly();
            _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("CardRefresh.refreshCard.json"));

            AdaptiveCard refreshCard = AdaptiveCard.FromJson(_textStreamReader.ReadToEnd()).Card;

            AdaptiveContainer commentContainer = (AdaptiveContainer)refreshCard.Body.FirstOrDefault(e => e.Id != null && e.Id.Equals("comments"));

            if (commentContainer != null)
            {
                foreach (var comment in comments)
                {
                    commentContainer.Items.Add(new AdaptiveTextBlock
                    {
                        Separator = true,
                        Wrap      = true,
                        Text      = comment.CommentText
                    });

                    commentContainer.Items.Add(new AdaptiveTextBlock
                    {
                        IsSubtle            = true,
                        Size                = AdaptiveTextSize.Small,
                        HorizontalAlignment = AdaptiveHorizontalAlignment.Right,
                        Text                = $"Entered by {comment.ActionPerformer} on {comment.CommentDate}"
                    });
                }
                return(refreshCard);
            }
            else
            {
                return(null);
            }
        }
        public void ExplicitImageSerializationTest()
        {
            var expected =
                @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.2"",
  ""id"": ""myCard"",
  ""body"": [
    {
      ""type"": ""Image"",
      ""url"": ""http://adaptivecards.io/content/cats/1.png"",
      ""width"": ""20px"",
      ""height"": ""50px""
    }
  ]
}";

            var card = new AdaptiveCard("1.2")
            {
                Id   = "myCard",
                Body =
                {
                    new AdaptiveImage("http://adaptivecards.io/content/cats/1.png")
                    {
                        PixelWidth  = 20,
                        PixelHeight = 50
                    },
                }
            };

            var actual = card.ToJson();

            Assert.AreEqual(expected: expected, actual: actual);
            var deserializedCard   = AdaptiveCard.FromJson(expected).Card;
            var deserializedActual = deserializedCard.ToJson();

            Assert.AreEqual(expected: expected, actual: deserializedActual);
        }
        private async Task CreateAdapteiveCardFromJson(IDialogContext context, string text)
        {
            try
            {
                //This is the path to our card in the solution. if you had it in another folder you would map to that path ie ~\\Dialogs\\Cards\\SampleCard.json
                var path = HostingEnvironment.MapPath($"~\\Dialogs\\SampleCard.json");

                //verify the card exists
                if (!File.Exists(path))
                {
                    await context.PostAsync("I'm sorry, a card at this path does not exist.");
                }

                //open the file
                using (var file = File.OpenText(path))
                {
                    //convert the json to an adaptive card
                    var results = AdaptiveCard.FromJson(await file.ReadToEndAsync());
                    var card    = results.Card;

                    //create a message to respond with and attach the adaptive card as an attachment
                    var message = context.MakeMessage();
                    message.Attachments.Add(new Attachment()
                    {
                        Content     = card,
                        ContentType = AdaptiveCard.ContentType,
                        Name        = "Card"
                    });

                    //post card
                    await context.PostAsync(message);
                }
            }
            catch (Exception error)
            {
                await context.PostAsync(error.ToString());
            }
        }
        private void  DynamicCardDemo()
        {
            //https://blog.botframework.com/2017/06/07/adaptive-card-dotnet/  (M Imp)

            //https://stackoverflow.com/questions/56173267/ms-chat-bot-how-to-access-custom-adaptive-card-properties-from-my-c-sharp-code/56192868#56192868
            //https://stackoverflow.com/questions/61230518/how-to-map-json-array-with-adaptive-card-row-using-designer-to-create-template

            //_cards[0]
            //var adaptiveCardJson = File.ReadAllText(_cards[0]);
            //var adaptiveCardAttachment = new Attachment()
            //{
            //    ContentType = "application/vnd.microsoft.card.adaptive",
            //    Content = JsonConvert.DeserializeObject(adaptiveCardJson),
            //};
            //return adaptiveCardAttachment;

            string[] paths          = { ".", "FlightItineraryCard.json" };
            var      cardJson       = File.ReadAllText(Path.Combine(paths));
            var      card           = AdaptiveCard.FromJson(cardJson).Card;
            var      columnSet      = (card.Body[0] as AdaptiveColumnSet);
            var      column         = (columnSet.Columns[0] as AdaptiveColumn);
            var      knowledgeBlock = (column.Items[1] as AdaptiveTextBlock);

            knowledgeBlock.Text = "Whatever You Want";

            var attachment = new Attachment()
            {
                Content     = card,
                ContentType = "application/vnd.microsoft.card.adaptive"
            };

            //var reply = stepContext.Context.Activity.CreateReply();
            //reply.Attachments = new List<Attachment>();

            //reply.Attachments.Add(attachment);

            //await stepContext.Context.SendActivityAsync(reply);
        }
Exemple #10
0
        // genera l'activity contenente la card per l'acquisizione dati del nuovo servizio
        public Activity generateWorkInProgressActivity()
        {
            Activity quickResponsesMessage = MessageFactory.Text("New feature: Work in progress");

            quickResponsesMessage.Attachments = new List <Attachment>();

            string cardTitle      = "Aiutaci a migliorare il servizio";
            string cardSubtitle   = "Sfortunatamente non siamo riusciti a risolvere il problema da lei richiesto ma stiamo lavorando allo sviluppo di un nuovo servizio di risoluzione dei problemi più comuni. Troverà di seguito una lista di soluzioni comuni per problemi di dominio generale, se eventualmente una delle soluzioni risolvesse il suo problema sarebe gradito un suo feedback per aiutare lo sviluppo del nuovo servizio, grazie";
            var    quickResponses = QuickResponseCategoryHandler.GetQuickResponsesList();
            string cardJSON       = generateAdaptiveCardWithOptions(cardTitle, cardSubtitle, quickResponses);

            var results = AdaptiveCard.FromJson(cardJSON);
            var card    = results.Card;

            quickResponsesMessage.Attachments.Add(new Attachment()
            {
                Content     = card,
                ContentType = AdaptiveCard.ContentType,
                Name        = "Card"
            });

            return(quickResponsesMessage);
        }
Exemple #11
0
        public async static Task <MessagingExtensionActionResponse> ShowResponseCard(ITurnContext <IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken, string Data)
        {
            string card = "{\r\n    \"type\": \"AdaptiveCard\",\r\n    \"version\": \"1.0\",\r\n    \"body\": [\r\n        {\r\n            \"type\": \"Image\",\r\n            \"altText\": \"\",\r\n            \"url\": \"https://1f0bd229.ngrok.io/images/Firstresponsecolor.png\",\r\n            \"width\": \"\"\r\n        },\r\n        {\r\n            \"type\": \"ColumnSet\",\r\n            \"columns\": [\r\n                {\r\n                    \"type\": \"Column\",\r\n                    \"items\": [\r\n                        {\r\n                            \"type\": \"Image\",\r\n                            \"altText\": \"\",\r\n                            \"url\": \"https://1f0bd229.ngrok.io/images/ref1.png\"\r\n                        },\r\n                        {\r\n                            \"type\": \"TextBlock\",\r\n                            \"text\": \"1\"\r\n                        }\r\n                    ],\r\n                    \"width\": \"stretch\"\r\n                },\r\n                {\r\n                    \"type\": \"Column\",\r\n                    \"items\": [\r\n                        {\r\n                            \"type\": \"Image\",\r\n                            \"altText\": \"\",\r\n                            \"url\": \"https://1f0bd229.ngrok.io/images/ref2.png\"\r\n                        },\r\n                        {\r\n                            \"type\": \"TextBlock\",\r\n                            \"text\": \"1\"\r\n                        }\r\n                    ],\r\n                    \"width\": \"stretch\"\r\n                },\r\n                {\r\n                    \"type\": \"Column\",\r\n                    \"items\": [\r\n                        {\r\n                            \"type\": \"Image\",\r\n                            \"altText\": \"1\",\r\n                            \"url\": \"https://1f0bd229.ngrok.io/images/ref3.png\"\r\n                        },\r\n                        {\r\n                            \"type\": \"TextBlock\",\r\n                            \"text\": \"1\"\r\n                        }\r\n                    ],\r\n                    \"width\": \"stretch\"\r\n                },\r\n                {\r\n                    \"type\": \"Column\",\r\n                    \"items\": [\r\n                        {\r\n                            \"type\": \"Image\",\r\n                            \"altText\": \"\",\r\n                            \"url\": \"https://1f0bd229.ngrok.io/images/ref4.png\"\r\n                        },\r\n                        {\r\n                            \"type\": \"TextBlock\",\r\n                            \"text\": \"1\"\r\n                        }\r\n                    ],\r\n                    \"width\": \"stretch\"\r\n                },\r\n                {\r\n                    \"type\": \"Column\",\r\n                    \"items\": [\r\n                        {\r\n                            \"type\": \"Image\",\r\n                            \"altText\": \"\",\r\n                            \"url\": \"https://1f0bd229.ngrok.io/images/ref5.png\"\r\n                        },\r\n                        {\r\n                            \"type\": \"TextBlock\",\r\n                            \"text\": \"1\"\r\n                        }\r\n                    ],\r\n                    \"width\": \"stretch\"\r\n                }\r\n            ]\r\n        }\r\n    ],\r\n    \"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\"\r\n}";

            AdaptiveCardParseResult result = AdaptiveCard.FromJson(card);
            var attachment = new MessagingExtensionAttachment
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = result.Card,
            };

            return(await Task.FromResult(new MessagingExtensionActionResponse
            {
                ComposeExtension = new MessagingExtensionResult
                {
                    Type = "result",
                    AttachmentLayout = "list",
                    Attachments = new List <MessagingExtensionAttachment> {
                        attachment
                    }
                }
            }));
        }
Exemple #12
0
        public void TestImageStretch()
        {
            var payload =
                @"{
                      ""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"",
                      ""type"": ""AdaptiveCard"",
                      ""version"": ""1.0"",
                      ""body"": [
                          {
                              ""type"": ""Image"",
                              ""url"": ""http://adaptivecards.io/content/cats/1.png"",
                              ""height"": ""stretch"",
                              ""size"": ""small""
                          }
                      ]
                  }";

            var result = AdaptiveCard.FromJson(payload);
            var card   = result?.Card;

            Assert.AreEqual(card.Body.Count, 1);
            Assert.AreEqual(card.Body[0].Height, AdaptiveHeight.Stretch);
        }
        public void TestSerializingTextBlock()
        {
            var card = new AdaptiveCard()
            {
                Body =
                {
                    new TextBlock()
                    {
                        Text = "Hello world"
                    }
                }
            };

            string json = card.ToJson();

            // Re-parse the card
            card = AdaptiveCard.FromJson(json).Card;

            // Ensure there's a text element
            Assert.AreEqual(1, card.Body.Count);
            Assert.IsInstanceOfType(card.Body[0], typeof(TextBlock));
            Assert.AreEqual("Hello world", (card.Body[0] as TextBlock).Text);
        }
        public void CardLevelSelectAction()
        {
            var json = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""selectAction"": {
      ""type"": ""Action.OpenUrl"",
      ""title"": ""Open URL"",
      ""url"": ""http://adaptivecards.io""
  }
}";
            var card = AdaptiveCard.FromJson(json).Card;
            var actualSelectAction = card.SelectAction as AdaptiveOpenUrlAction;

            var expectedSelectAction = new AdaptiveOpenUrlAction
            {
                Title     = "Open URL",
                UrlString = "http://adaptivecards.io"
            };

            Assert.AreEqual(expectedSelectAction.Title, actualSelectAction.Title);
            Assert.AreEqual(expectedSelectAction.UrlString, actualSelectAction.UrlString);
        }
        public void TestSpacingAndSeparatorDefaults()
        {
            AdaptiveCard card = AdaptiveCard.FromJson(@"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Adaptive Card design session""
    }
  ]
}").Card;

            AdaptiveTextBlock tb = card.Body[0] as AdaptiveTextBlock;

            Assert.AreEqual(AdaptiveSpacing.Default, tb.Spacing);
            Assert.AreEqual(false, tb.Separator);

            string json = card.ToJson();

            Assert.IsFalse(json.Contains("spacing"));
            Assert.IsFalse(json.Contains("separator"));
        }
Exemple #16
0
        private static async Task RenderCard(string file, AdaptiveCardRenderer renderer, string outPath)
        {
            try
            {
                var watch = new Stopwatch();
                watch.Start();

                AdaptiveCardParseResult parseResult = AdaptiveCard.FromJson(File.ReadAllText(file, Encoding.UTF8));
                AdaptiveCard            card        = parseResult.Card;

                // Timeout after 30 seconds
                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

                // Render the card to an image
                RenderedAdaptiveCardImage renderedCard = await renderer.RenderCardToImageAsync(card, true, 400, cts.Token);

                // Report any warnings
                foreach (var warning in parseResult.Warnings.Union(renderedCard.Warnings))
                {
                    Console.WriteLine($"[{Path.GetFileName(file)}] WARNING: {warning.Message}");
                }

                // Write to a png file with the same name as the json file
                var outputFile = Path.Combine(outPath,
                                              Path.ChangeExtension(Path.GetFileName(file), ".png"));

                using (var fileStream = new FileStream(outputFile, FileMode.Create))
                {
                    renderedCard.ImageStream.CopyTo(fileStream);
                    Console.WriteLine($"[{watch.ElapsedMilliseconds}ms T{Thread.CurrentThread.ManagedThreadId}]\t{Path.GetFileName(file)} => {Path.GetFileName(outputFile)}");
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"[FAILED]\t{Path.GetFileName(file)} => {ex.Message}");
            }
        }
        /// <summary>
        /// Show DeductFrom selection card once 'Back' is clicked either from time selection or confirmation card depending upon duration value.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <param name="data">Advanced time off object.</param>
        /// <param name="paycodes">List of paycodes from azure storage.</param>
        /// <returns>Deduct from card.</returns>
        public AdaptiveCard OnBackGetDeductFromCard(IDialogContext context, AdvancedTimeOff data, List <string> paycodes)
        {
            string fullPath = HttpContext.Current.Server.MapPath("/Cards/AdaptiveCards/TimeOff/AdvanceTimeOff3.json");
            var    json     = File.ReadAllText(fullPath);

            if (paycodes.Count > 0)
            {
                var           row = "{\"title\": \"{Text}\",\"value\": \"{Value}\"}";
                StringBuilder sb  = new StringBuilder();
                for (int i = 0; i < paycodes.Count; i++)
                {
                    var paycode = row.Replace("{Text}", paycodes[i]).Replace("{Value}", paycodes[i]);
                    if (i == 0)
                    {
                        sb.Append(paycode);
                        json = json.Replace("{DeductFrom}", data.DeductFrom ?? paycodes[i]);
                    }
                    else
                    {
                        sb.Append(", " + paycode);
                    }
                }

                json = json.Replace("{Paycodes}", sb.ToString());
            }
            else
            {
                json = json.Replace("{Paycodes}", string.Empty).Replace("{DeductFrom}", data.DeductFrom ?? string.Empty);
            }

            json = json.Replace("{Title}", KronosResourceText.TimeOffRequstText).Replace("{TimeOffType}", KronosResourceText.TypeOfTimeoff);
            json = json.Replace("{Back}", KronosResourceText.Back).Replace("{Cancel}", KronosResourceText.Cancel).Replace("{Next}", KronosResourceText.NextButton);
            json = data.duration.ToLowerInvariant() == Constants.Hours.ToLowerInvariant() ? json.Replace(Constants.AdvancedBack2, Constants.AdvancedBack3ToHours) : json.Replace(Constants.AdvancedBack2, Constants.AdvancedBack2);
            var card = AdaptiveCard.FromJson(json).Card;

            return(card);
        }
        public void ColumnTypeNotRequired()
        {
            var json = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""ColumnSet"",
      ""columns"": [
        {
          ""items"": [
            {
              ""type"": ""Image"",
              ""url"": ""http://3.bp.blogspot.com/-Xo0EuTNYNQg/UEI1zqGDUTI/AAAAAAAAAYE/PLYx5H4J4-k/s1600/smiley+face+super+happy.jpg"",
              ""size"": ""stretch""
            }
          ]
        },
        {
          ""width"": ""stretch"",
          ""items"": [
            {
              ""type"": ""TextBlock"",
              ""text"": ""This card has two ColumnSets on top of each other. In each, the left column is explicitly sized to be 50 pixels wide."",
              ""wrap"": true
            }
          ]
        }
       ]
    }
  ]
}";

            var result = AdaptiveCard.FromJson(json);

            Assert.IsNotNull(result.Card);
        }
        /// <summary>
        /// TimeOff Success Card.
        /// </summary>
        /// <param name="context">Dialog context.</param>
        /// <param name="response">Time off response data.</param>
        /// <param name="obj">Advanced time off object.</param>
        /// <returns>Time off success card.</returns>
        public AdaptiveCard ShowTimeOffSuccessCard(IDialogContext context, Models.ResponseEntities.TimeOff.AddResponse.Response response, AdvancedTimeOff obj)
        {
            var repoMessage = context.MakeMessage();

            string fullPath     = HttpContext.Current.Server.MapPath("/Cards/AdaptiveCards/TimeOff/TimeOffSuccessCard.json");
            var    adaptiveCard = File.ReadAllText(fullPath);
            var    period       = response.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault();

            DateTime.TryParse(response.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().CreationDateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime creationdate);
            DateTime.TryParse(period.StartDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime sdt);
            DateTime.TryParse(period.EndDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime edt);
            edt = edt.AddHours(23);
            edt = edt.AddMinutes(59);
            var days = (int)Math.Round(edt.Subtract(sdt).TotalDays, MidpointRounding.AwayFromZero);

            adaptiveCard = adaptiveCard.Replace("{Title}", KronosResourceText.TimeOffRequstText).Replace("{Info}", KronosResourceText.TimeOffRequestSuccessInfoText);
            adaptiveCard = adaptiveCard.Replace("{Paycode}", period.PayCodeName).Replace("{Paycode_Info}", period.PayCodeName.ToLowerInvariant()).Replace("{StartDate}", sdt.ToString("MMM d, yyyy")).Replace("{EndDate}", edt.ToString("MMM d, yyyy"));
            adaptiveCard = adaptiveCard.Replace("{Type}", KronosResourceText.Type).Replace("{StartDate_Txt}", KronosResourceText.StartDate).Replace("{EndDate_Txt}", KronosResourceText.EndDate).Replace("{Duration_Txt}", KronosResourceText.Duration);
            adaptiveCard = adaptiveCard.Replace("{PendingImg}", Constants.PendingImg);
            var duration = period.Duration == Constants.full_day ? Constants.FullDay : period.Duration == Constants.half_day ? Constants.HalfDay : period.Duration == Constants.first_half_day ? Constants.FirstHalfDay : Constants.Hours;

            if (period.Duration.ToLowerInvariant() == Constants.Hours.ToLowerInvariant())
            {
                var shr   = Convert.ToInt32(obj.StartTime.Split(' ')[0].Split(':')[0]);
                var smin  = Convert.ToInt32(obj.StartTime.Split(' ')[0].Split(':')[1]);
                var ehr   = Convert.ToInt32(obj.EndTime.Split(' ')[0].Split(':')[0]);
                var emin  = Convert.ToInt32(obj.EndTime.Split(' ')[0].Split(':')[1]);
                var stime = new DateTime(2000, 1, 1, shr, smin, 0);
                var etime = new DateTime(2000, 1, 1, ehr, emin, 0);
                duration += $" ({stime.ToString("h:mm tt", CultureInfo.InvariantCulture) + " - " + etime.ToString("h:mm tt", CultureInfo.InvariantCulture)})";
            }

            adaptiveCard = adaptiveCard.Replace("{Duration}", duration).Replace("{AdditionalRequest}", KronosResourceText.AdditionalRequest);
            var card = AdaptiveCard.FromJson(adaptiveCard).Card;

            return(card);
        }
        private void TestPayloadsInDirectory(string path)
        {
            var exceptions = new List <Exception>();
            var files      = Directory.GetFiles(path, "*.json").ToList();

            Assert.IsTrue(files.Count > 1);
            foreach (var file in files)
            {
                // TODO: bring these tests back when bug #940 is closed
                if (file.Contains("Container.Style") || file.Contains("ShowCard.Style"))
                {
                    continue;
                }

                try
                {
                    var json        = File.ReadAllText(file, Encoding.UTF8);
                    var parseResult = AdaptiveCard.FromJson(json);
                    Assert.IsNotNull(parseResult.Card);
                    Assert.AreEqual(0, parseResult.Warnings.Count);

                    // Make sure JsonConvert works also
                    var card = JsonConvert.DeserializeObject <AdaptiveCard>(json);
                    Assert.AreEqual(parseResult.Card.Body.Count, card.Body.Count);
                    Assert.AreEqual(parseResult.Card.Actions.Count, card.Actions.Count);
                }
                catch (Exception ex)
                {
                    exceptions.Add(new Exception($"Payload file failed: {Path.GetFileName(file)}", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
        private async Task <Stream> ConvertAsync(Attachment attachment, CancellationToken cancellationToken)
        {
            if (attachment.ContentType == AdaptiveCard.ContentType)
            {
                // https://docs.microsoft.com/en-us/adaptive-cards/sdk/rendering-cards/net-image/render-a-card
                AdaptiveCard card = null;
                if (attachment.Content is AdaptiveCard adaptiveCard)
                {
                    card = adaptiveCard;
                }
                else if (attachment.Content is JToken jtoken)
                {
                    AdaptiveCardParseResult parseResult = AdaptiveCard.FromJson(jtoken.ToString());
                    card = parseResult.Card;
                }
                else
                {
                    throw new NotImplementedException($"{attachment.Content.GetType().Name} is not supported yet!");
                }

                // TODO don't know if it is thread safe or not
                var adaptiveRenderer = new AdaptiveCardRenderer(_adaptiveHostConfig);

                // Set any XAML resource Dictionary if you have one
                //renderer.ResourcesPath = <path-to-your-resourcedictionary.xaml>;

                // Render the card to png
                // Set createStaThread to true if running from a server
                var renderedCard = await adaptiveRenderer.RenderCardToImageAsync(card, createStaThread : true, cancellationToken : cancellationToken);

                return(renderedCard.ImageStream);
            }
            else
            {
                throw new NotSupportedException($"{attachment.ContentType} is not supported yet!");
            }
        }
        public void ContainerStyle()
        {
            var json = @"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""Container"",
      ""style"": ""default"",
      ""items"": []
    },
    {
      ""type"": ""Container"",
      ""style"": ""emphasis"",
      ""items"": []
    },
    {
      ""type"": ""Container"",
      ""items"": []
    }
  ]
}";
            var card = AdaptiveCard.FromJson(json).Card;
            var actualSelectAction = card.SelectAction as AdaptiveOpenUrlAction;

            var containerDefaultStyle = card.Body[0] as AdaptiveContainer;

            Assert.AreEqual(AdaptiveContainerStyle.Default, containerDefaultStyle.Style);

            var containerEmphasisStyle = card.Body[1] as AdaptiveContainer;

            Assert.AreEqual(AdaptiveContainerStyle.Emphasis, containerEmphasisStyle.Style);

            var containerNoneStyle = card.Body[2] as AdaptiveContainer;

            Assert.IsNull(containerNoneStyle.Style);
        }
        public void TestSpacingAndSeparator()
        {
            AdaptiveCard card = AdaptiveCard.FromJson(@"{
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""body"": [
    {
      ""type"": ""TextBlock"",
      ""text"": ""Adaptive Card design session"",
      ""spacing"": ""large"",
      ""separator"": true
    }
  ]
}").Card;

            AdaptiveTextBlock tb = card.Body[0] as AdaptiveTextBlock;

            Assert.AreEqual(AdaptiveSpacing.Large, tb.Spacing);
            Assert.AreEqual(true, tb.Separator);

            string json = card.ToJson();

            Assert.IsTrue(json.Contains(@"""separator"": true"));
        }
Exemple #24
0
        public void ParseIconUrl()
        {
            var json   = @"{
  ""$schema"": ""http://adaptivecards.io/schemas/adaptive-card.json"",
  ""type"": ""AdaptiveCard"",
  ""version"": ""1.0"",
  ""actions"": [
    {
      ""type"": ""Action.OpenUrl"",
      ""iconUrl"": ""http://adaptivecards.io/content/cats/1.png"",
      ""url"": ""http://adaptivecards.io"",
      ""title"": ""Open URL""
    }
  ]
}";
            var result = AdaptiveCard.FromJson(json);

            Assert.IsNotNull(result.Card);

            var expectedIconUrl = "http://adaptivecards.io/content/cats/1.png";
            var actualIconUrl   = result.Card.Actions[0].IconUrl;

            Assert.AreEqual(expectedIconUrl, actualIconUrl);
        }
Exemple #25
0
        public PromptOptions GenerateTVDetailsAttachment(TVDetails tvDetails)
        {
            var paths            = new[] { ".", "Cards", "movieDetails.json" };
            var adaptiveCardJson = File.ReadAllText(Path.Combine(paths));

            AdaptiveCardParseResult result = AdaptiveCard.FromJson(adaptiveCardJson);
            AdaptiveCard            card   = result.Card;

            ((AdaptiveTextBlock)card.Body.First()).Text = "Movie details";
            ((AdaptiveImage)((AdaptiveColumnSet)card.Body[1]).Columns.First().Items.First()).Url = new Uri($"https://image.tmdb.org/t/p/w500/{tvDetails.PosterPath}");

            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items.First()).Text = tvDetails.Name;
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[1]).Text      = $"Released: {tvDetails.FirstAirDate}";
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[2]).Text      = $"Genres: {string.Join(", ", tvDetails.Genres.Select(x => x.Name))}";
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[3]).Text      = $"Status: {tvDetails.Status}";
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[4]).Text      = $"Rating: {tvDetails.VoteAverage}";
            ((AdaptiveTextBlock)card.Body[2]).Text = tvDetails.Overview;

            card.Actions = null;

            ((AdaptiveFactSet)card.Body[3]).Facts
            .AddRange(tvDetails.Seasons.OrderBy(x => x.SeasonNumber).Select(x => new AdaptiveFact
            {
                Title = x.Name,
                Value = $"- ({x.AirDate?.Split("-")[0]}) - {x.EpisodeCount} episodes"
            }));

            return(new PromptOptions
            {
                Prompt = (Activity)MessageFactory.Attachment(new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content = JObject.FromObject(card)
                })
            });
        }
Exemple #26
0
        public PromptOptions GeneratePersonDetailsAttachment(PersonDetails personDetails, PersonKnownFor[] knownFor)
        {
            var paths            = new[] { ".", "Cards", "personDetails.json" };
            var adaptiveCardJson = File.ReadAllText(Path.Combine(paths));

            AdaptiveCardParseResult result = AdaptiveCard.FromJson(adaptiveCardJson);
            AdaptiveCard            card   = result.Card;

            ((AdaptiveTextBlock)card.Body.First()).Text = "Person details";
            ((AdaptiveImage)((AdaptiveColumnSet)card.Body[1]).Columns.First().Items.First()).Url = new Uri($"https://image.tmdb.org/t/p/w500/{personDetails.profile_path}");

            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items.First()).Text = personDetails.name;
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[1]).Text      = $"Born: {personDetails.birthday}";
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[2]).Text      = $"Role: {personDetails.known_for_department}";
            ((AdaptiveTextBlock)((AdaptiveColumnSet)card.Body[1]).Columns[1].Items[1]).Text      = $"Born: {personDetails.birthday}";
            ((AdaptiveTextBlock)card.Body[2]).Text = personDetails.biography;

            ((AdaptiveFactSet)card.Body[4]).Facts
            .AddRange(knownFor.Select(x => new AdaptiveFact
            {
                Title = x.Title,
                Value = $"({x.ReleaseDate.Split("-")[0]}) - {TMDBGenres.MovieGenres.Where(y => y.Value == x.GenreIds[0]).FirstOrDefault().Key}"
            }));

            ((AdaptiveOpenUrlAction)card.Actions.First()).Url = new Uri($"https://www.imdb.com/name/{personDetails.imdb_id}");


            return(new PromptOptions
            {
                Prompt = (Activity)MessageFactory.Attachment(new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content = JObject.FromObject(card)
                })
            });
        }
Exemple #27
0
        /// <summary>
        /// Get welcome card attachment to be sent in personal scope.
        /// </summary>
        /// <returns>User welcome card attachment.</returns>
        public Attachment GetWelcomeCardForPersonalScope()
        {
            var cardPayload        = this.GetCardPayload(WelcomeCardCacheKey, "\\WelcomeCard\\welcome-card.json");
            var welcomeCardOptions = new WelcomeCard
            {
                AppImage        = $"{this.botOptions.Value.AppBaseUri}/images/logo.png",
                TimesheetTabUrl = $"https://teams.microsoft.com/l/entity/{this.botOptions.Value.ManifestId}/fill-timesheet",
                WelcomeCardFillTimesheetButton = this.localizer.GetString("FillTimesheetButton"),
                WelcomeCardIntro    = this.localizer.GetString("WelcomeCardIntro"),
                WelcomeCardSubtitle = this.localizer.GetString("WelcomeCardSubtitle"),
                WelcomeCardTitle    = this.localizer.GetString("WelcomeCardTitle"),
            };
            var          template = new AdaptiveCardTemplate(cardPayload);
            var          cardJson = template.Expand(welcomeCardOptions);
            AdaptiveCard card     = AdaptiveCard.FromJson(cardJson).Card;

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card,
            };

            return(adaptiveCardAttachment);
        }
        private static async Task GetMainOptions(IMessageActivity reply)
        {
            HttpClient          client = new HttpClient();
            HttpResponseMessage response;
            AdaptiveCard        card = new AdaptiveCard();

            response = await client.GetAsync(String.Format("https://surastorage.blob.core.windows.net/cardstemplates/servicios.json"));

            var json = await response.Content.ReadAsStringAsync();

            AdaptiveCardParseResult resultString = AdaptiveCard.FromJson(json);

            card = resultString.Card;
            IList <AdaptiveWarning> warnings = resultString.Warnings;


            Attachment attachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card
            };

            reply.Attachments.Add(attachment);
        }
        public static IMessageActivity BuildNewUserGreetingCard(ITurnContext turnContext, dynamic data)
        {
            var introCard  = File.ReadAllText(MainStrings.INTRO_PATH);
            var card       = AdaptiveCard.FromJson(introCard).Card;
            var attachment = new Attachment(AdaptiveCard.ContentType, content: card);



            var response = MessageFactory.Attachment(attachment, ssml: card.Speak, inputHint: InputHints.IgnoringInput);



            response.SuggestedActions = new SuggestedActions
            {
                Actions = new List <CardAction>()
                {
                    new CardAction(type: ActionTypes.ImBack, title: MainStrings.HELP_BTN_TEXT_1, value: MainStrings.HELP_BTN_VALUE_1),
                    new CardAction(type: ActionTypes.ImBack, title: MainStrings.HELP_BTN_TEXT_2, value: MainStrings.HELP_BTN_VALUE_2),
                    new CardAction(type: ActionTypes.ImBack, title: MainStrings.HELP_BTN_TEXT_3, value: MainStrings.HELP_BTN_VALUE_3),
                },
            };

            return(response);
        }
Exemple #30
0
        /// <summary>
        /// Get pending requests reminder card for manager approval.
        /// </summary>
        /// <param name="requestsCount">Pending requests count.</param>
        /// <returns>Pending requests reminder card attachment.</returns>
        public Attachment GetRequestReminderCard(string requestsCount)
        {
            var cardPayload        = this.GetCardPayload(RequestReminderCardCacheKey, "\\ManagerRequestsReminder\\request-reminder-card.json");
            var welcomeCardOptions = new RequestsReminderCard
            {
                AppImage          = $"{this.botOptions.Value.AppBaseUri}/images/logo.png",
                DashboardTabUrl   = $"https://teams.microsoft.com/l/entity/{this.botOptions.Value.ManifestId}/manager-dashboard",
                ViewRequestButton = this.localizer.GetString("ViewRequestButton"),
                CardText          = this.localizer.GetString("RequestsReminderCardText", requestsCount),
                CardSubtitle      = this.localizer.GetString("ActionRequiredSubTitle"),
                CardTitle         = this.localizer.GetString("TimesheetRequestsCardTitle"),
            };
            var          template = new AdaptiveCardTemplate(cardPayload);
            var          cardJson = template.Expand(welcomeCardOptions);
            AdaptiveCard card     = AdaptiveCard.FromJson(cardJson).Card;

            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = card,
            };

            return(adaptiveCardAttachment);
        }