microsoft / AdaptiveCards

A new way for developers to exchange card content in a common and consistent way.
https://adaptivecards.io
MIT License
1.76k stars 550 forks source link

.NET Convert JSON schema to a model #411

Closed jrmcdona closed 6 years ago

jrmcdona commented 7 years ago

Hi, Is there a simple method to build a schema in the visualizer then either use that JSON directly in C# or convert it to .NET based model? Just trying to figure out the fastest way to build the Adaptive card in .NET after visualizer/JSON.

Thanks

EricDahlvang commented 7 years ago

One option is to save the .json in your bot project, and load the file directly:

public async Task<string> GetCardText(string cardName)
{
    var path = HostingEnvironment.MapPath($"/Cards/{cardName}.json");
    if (!File.Exists(path))
        return string.Empty;

    using (var f = File.OpenText(path))
    {
        return await f.ReadToEndAsync();
    }
}

Then, add that as an attachment to the return message like:

var returnMessage = dialogContext.MakeMessage();

returnMessage.Attachments.Add(new Attachment()
{
    Content = await GetCardText("[Card File Name Here]"),
    ContentType = AdaptiveCard.ContentType,
    Name = "Card"
});
jrmcdona commented 7 years ago

very cool, thanks

Yashu1904 commented 7 years ago

@EricDahlvang I have tried the same steps as you mentioned above, but I got a problem like can't render card. Hope you help me to sort it out. screenshot 1

Thanks in Advance, Yashwanth.

PoojaSha commented 6 years ago

Hi Yashu,

If you could please tell how did you resolve the issue, I am also facing the same.

PoojaSha commented 6 years ago

@Yashu1904

CleberDSantos commented 6 years ago

It's working fine for me.

Install-Package AdaptiveCards -IncludePrerelease

        var json = await GetCardText("card1");
        AdaptiveCardParseResult jsonResult = AdaptiveCard.FromJson(json);

        replyMessage.Attachments.Add(new Attachment()
        {
            Content = jsonResult.Card,
            ContentType = AdaptiveCard.ContentType,
            Name = "Card"
        });
PoojaSha commented 6 years ago

AdaptiveCardParseResult class and FromJSON method is not being recognized. Did you create it? Can you please show the implementation of it? @CleberDSantos

CleberDSantos commented 6 years ago

Install-Package AdaptiveCards -IncludePrerelease

PoojaSha commented 6 years ago

I have already installed Adaptive Cards package.

On entering above command, it gives following error

At line:1 char:16

PoojaSha commented 6 years ago

Please help @CleberDSantos

CleberDSantos commented 6 years ago

Try

Option 1: uninstall-Package AdaptiveCards Install-Package AdaptiveCards -IncludePrerelease

image

Option 2: Delete package folder

image

and rebuild you solution

Option 3:

In Manager nuget packages:

image

Select the checkbox

image

PoojaSha commented 6 years ago

Hi @CleberDSantos ,

On entering "Find-Package AdaptiveCards" it displays following, which means cards do exist in my code Id Versions Description


Microsoft.AdaptiveCards {0.5.1} This library implements classes for building and serializing adaptive card objects
Time Elapsed: 00:00:02.6086086

But on entering PM> uninstall-Package AdaptiveCards it displays following:

Uninstall-Package : Project 'Default' is not found. At line:1 char:18

Kindly help. I have tried uninstall-Package Microsoft.AdaptiveCards too

CleberDSantos commented 6 years ago

Please, check if you selected correct project on nuget package console:

image

If yes, check the package.config:

image

CleberDSantos commented 6 years ago

I had to downgrade to 1.0.0-beta03, because not working for me with the last beta version:

image

image

image

matthidinger commented 6 years ago

Hi @CleberDSantos, what is the issue you were seeing with beta08?

CleberDSantos commented 6 years ago

Hi @matthidinger. When I'm using the beta08 the adptive card not render for me.

image

image

But, when I'm using beta03 it's working fine. I don't know what's going on.

Package installed on my project:

<packages>
  <package id="AdaptiveCards" version="1.0.0-beta03" targetFramework="net46" />
  <package id="Autofac" version="4.6.2" targetFramework="net46" />
  <package id="Chronic.Signed" version="0.3.2" targetFramework="net46" />
  <package id="Microsoft.AdaptiveCards" version="0.5.1" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.Bot.Builder" version="3.11.0" targetFramework="net46" />
  <package id="Microsoft.Bot.Connector" version="3.11.1" targetFramework="net46" />
  <package id="Microsoft.CSharp" version="4.4.0" targetFramework="net46" />
  <package id="Microsoft.IdentityModel.Protocol.Extensions" version="1.0.4.403061554" targetFramework="net46" />
  <package id="Microsoft.Rest.ClientRuntime" version="2.3.10" targetFramework="net46" />
  <package id="Microsoft.WindowsAzure.ConfigurationManager" version="3.2.3" targetFramework="net46" />
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net46" />
  <package id="System.IdentityModel.Tokens.Jwt" version="4.0.4.403061554" targetFramework="net46" />
</packages>

card json


{
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.0",
    "speak": "<s>The forecast for Seattle January 20 is mostly clear with a High of 51 degrees and Low of 40 degrees</s>",
    "body": [
        {
            "type": "TextBlock",
            "text": "Seattle, WA",
            "size": "large",
            "isSubtle": true
        },
        {
            "type": "TextBlock",
            "text": "September 18, 7:30 AM",
            "spacing": "none"
        },
        {
            "type": "ColumnSet",
            "columns": [
        {
          "type": "Column",
          "width": "auto",
          "items": [
            {
              "type": "Image",
              "url": "http://messagecardplayground.azurewebsites.net/assets/Mostly%20Cloudy-Square.png",
              "size": "small"
            }
          ]
        },
                {
                    "type": "Column",
                    "width": "auto",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "42",
                            "size": "extraLarge",
                            "spacing": "none"
                        }
                    ]
                },
                {
                    "type": "Column",
                    "width": "stretch",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": " ",
                            "weight": "bolder",
                            "spacing": "small"
                        },
                        {
                            "type": "TextBlock",
                            "text": "°F",
                            "weight": "bolder",
                            "spacing": "small"
                        }
                    ]
                },
                {
                    "type": "Column",
                    "width": "stretch",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "Hi 51",
                            "horizontalAlignment": "left"
                        },
                        {
                            "type": "TextBlock",
                            "text": "Lo 40",
                            "horizontalAlignment": "left",
                            "spacing": "none"
                        }
                    ]
                }
            ]
        }
    ]
} 
matthidinger commented 6 years ago

Can you share the c# code you're using to generate the Json, and/or the Json payloads geneated by beta03 and beta08 so I can see the dinrrrences

PoojaSha commented 6 years ago

Hi @matthidinger,

I am trying to render my Adaptive card on Workplace using Bot Framework in C#. The same card is displaying fine on Facebook messenger. But if I publish it on Workplace chat, it is coming as blank. Could you please help me with the possible solution?

Thanks much

CleberDSantos commented 6 years ago

My code is very simple, I'm using the @EricDahlvang approach to read the json file.

       [LuisIntent("")]
        public async Task None(IDialogContext context, LuisResult result)
        {

            var replyMessage = context.MakeMessage();
            var json = await GetCardText("card1");

            AdaptiveCardParseResult cardParseResult = AdaptiveCard.FromJson(json);

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

            await context.PostAsync(replyMessage);
        }

        public async Task<string> GetCardText(string cardName)
        {
            var path = HostingEnvironment.MapPath($"/Cards/{cardName}.json");
            if (!File.Exists(path))
                return string.Empty;

            using (var f = File.OpenText(path))
            {
                return await f.ReadToEndAsync();
            }
        }

Beta08 json result:

{
  "type": "message",
  "timestamp": "2017-11-23T18:36:14.723Z",
  "localTimestamp": "2017-11-23T16:36:14-02:00",
  "serviceUrl": "http://localhost:53152",
  "channelId": "emulator",
  "from": {
    "id": "a9cm8nj22hak",
    "name": "Bot"
  },
  "conversation": {
    "id": "n88el9e61fc4"
  },
  "recipient": {
    "id": "default-user"
  },
  "membersAdded": [],
  "membersRemoved": [],
  "locale": "en-US",
  "text": "",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "content": {
        "version": "1.0",
        "speak": "<s>The forecast for Seattle January 20 is mostly clear with a High of 51 degrees and Low of 40 degrees</s>",
        "body": [
          {
            "size": "large",
            "isSubtle": true,
            "text": "Seattle, WA"
          },
          {
            "text": "September 18, 7:30 AM",
            "spacing": "none"
          },
          {
            "columns": [
              {
                "width": "auto",
                "items": [
                  {
                    "size": "small",
                    "url": "http://messagecardplayground.azurewebsites.net/assets/Mostly%20Cloudy-Square.png"
                  }
                ]
              },
              {
                "width": "auto",
                "items": [
                  {
                    "size": "extraLarge",
                    "text": "42",
                    "spacing": "none"
                  }
                ]
              },
              {
                "width": "stretch",
                "items": [
                  {
                    "weight": "bolder",
                    "text": " ",
                    "spacing": "small"
                  },
                  {
                    "weight": "bolder",
                    "text": "°F",
                    "spacing": "small"
                  }
                ]
              },
              {
                "width": "stretch",
                "items": [
                  {
                    "text": "Hi 51"
                  },
                  {
                    "text": "Lo 40",
                    "spacing": "none"
                  }
                ]
              }
            ]
          }
        ],
        "actions": [],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
      },
      "name": "Card"
    }
  ],
  "entities": [],
  "replyToId": "2kbkn68cnl44",
  "id": "lb84m4f09124"
}

Beta03 json result:

{
  "type": "message",
  "timestamp": "2017-11-23T18:37:31.585Z",
  "localTimestamp": "2017-11-23T16:37:31-02:00",
  "serviceUrl": "http://localhost:53152",
  "channelId": "emulator",
  "from": {
    "id": "a9cm8nj22hak",
    "name": "Bot"
  },
  "conversation": {
    "id": "n88el9e61fc4"
  },
  "recipient": {
    "id": "default-user"
  },
  "membersAdded": [],
  "membersRemoved": [],
  "locale": "en-US",
  "text": "",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "content": {
        "type": "AdaptiveCard",
        "version": "1.0",
        "speak": "<s>The forecast for Seattle January 20 is mostly clear with a High of 51 degrees and Low of 40 degrees</s>",
        "body": [
          {
            "type": "TextBlock",
            "size": "large",
            "weight": null,
            "color": null,
            "isSubtle": true,
            "text": "Seattle, WA",
            "horizontalAlignment": "left",
            "wrap": false,
            "maxLines": 0
          },
          {
            "type": "TextBlock",
            "size": null,
            "weight": null,
            "color": null,
            "isSubtle": false,
            "text": "September 18, 7:30 AM",
            "horizontalAlignment": "left",
            "wrap": false,
            "maxLines": 0,
            "spacing": "none"
          },
          {
            "type": "ColumnSet",
            "columns": [
              {
                "type": "Column",
                "width": "auto",
                "items": [
                  {
                    "type": "Image",
                    "size": "small",
                    "style": null,
                    "url": "http://messagecardplayground.azurewebsites.net/assets/Mostly%20Cloudy-Square.png",
                    "horizontalAlignment": "left"
                  }
                ]
              },
              {
                "type": "Column",
                "width": "auto",
                "items": [
                  {
                    "type": "TextBlock",
                    "size": "extraLarge",
                    "weight": null,
                    "color": null,
                    "isSubtle": false,
                    "text": "42",
                    "horizontalAlignment": "left",
                    "wrap": false,
                    "maxLines": 0,
                    "spacing": "none"
                  }
                ]
              },
              {
                "type": "Column",
                "width": "stretch",
                "items": [
                  {
                    "type": "TextBlock",
                    "size": null,
                    "weight": "bolder",
                    "color": null,
                    "isSubtle": false,
                    "text": " ",
                    "horizontalAlignment": "left",
                    "wrap": false,
                    "maxLines": 0,
                    "spacing": "small"
                  },
                  {
                    "type": "TextBlock",
                    "size": null,
                    "weight": "bolder",
                    "color": null,
                    "isSubtle": false,
                    "text": "°F",
                    "horizontalAlignment": "left",
                    "wrap": false,
                    "maxLines": 0,
                    "spacing": "small"
                  }
                ]
              },
              {
                "type": "Column",
                "width": "stretch",
                "items": [
                  {
                    "type": "TextBlock",
                    "size": null,
                    "weight": null,
                    "color": null,
                    "isSubtle": false,
                    "text": "Hi 51",
                    "horizontalAlignment": "left",
                    "wrap": false,
                    "maxLines": 0
                  },
                  {
                    "type": "TextBlock",
                    "size": null,
                    "weight": null,
                    "color": null,
                    "isSubtle": false,
                    "text": "Lo 40",
                    "horizontalAlignment": "left",
                    "wrap": false,
                    "maxLines": 0,
                    "spacing": "none"
                  }
                ]
              }
            ]
          }
        ],
        "actions": []
      },
      "name": "Card"
    }
  ],
  "entities": [],
  "replyToId": "101jfkja8ga5",
  "id": "71ne41g6c4d4"
}

Result:

image

matthidinger commented 6 years ago

The "type" property is being stripped from everything, that should definitely not be happening. Let me investigate and get a fix out as soon as possible

CleberDSantos commented 6 years ago

Great

I guess the issue is in Microsoft.Bot.Builder.

image

image

But, it's just a suggestion ^^

matthidinger commented 6 years ago

I'm having a hard time reproducing. All of our tests are working too, and we deserialize from files in the many tests.

Are you able to reproduce where exactly the "type" properties are being stripped? Is it what your service is returning or is it once the payload gets to webchat/emulator?

CleberDSantos commented 6 years ago

I'm copying from details field.

Localhost bot emulator test,

image

But i had the same issue in webchat iframe:

image

And Skype Channel:

image

matthidinger commented 6 years ago

Ok thanks, I've got a repo. Going to investigate with the BF team, stay tuned!

matthidinger commented 6 years ago

This should be fixed with the beta09 package that will be releasing shortly. Thanks for your patience!

artemious7 commented 5 years ago

The conversation above seems to me mostly irrelevant to the issue topic - ".NET Convert JSON schema to a model". @jrmcdona has asked

to build a schema in the visualizer then either use that JSON directly in C# or convert it to .NET based model

The solution provided here was to read JSON from a file and use it for adaptive card. But how do I fill the schema with my values? I thought Adaptive cards were not meant to be static, but show relevant content each time user requests a card. If I parse the JSON schema, I'll have to find each element and fill it with my values. But using C# adaptive cards library model would simplify it.

Is there any JSON-schema-to-C#-model converter?

arafattehsin commented 5 years ago

@artemious7 I am looking for the similar solution. Please let me know if you were able to get it done somehow.

Massi-G commented 5 years ago

@artemious7 where you able to solve this, if yes please can you share solution to populating adaptive cards with values

arafattehsin commented 5 years ago

Hello @Massi-G, I think I was able to do that long back ago. I will try to look for the code snippet for you once I am free tomorrow.

artemious7 commented 5 years ago

Hello @Massi-G, I asked this question here and Microsoft replied:

There is an early preview of [Data Binding in Adaptive Cards] (microsoft/AdaptiveCards#2448).

I guess it has already become generally available since then.

artemious7 commented 5 years ago

However, I didn't use the new data binding feature. I used Adaptive Cards v1, so I had to clone adaptive card nodes and change the values according to my data. Here's some code from my project

Massi-G commented 5 years ago

Hi

Thank you for the code snippet, I have seen the adaptive card binding document. However, that presumed a lot and as I am new at the adaptive cards will try and work through it.

Kind Regards [signature_170447147]

Massimo Gatta | Business Analyst

PUBLICIS COMMERCE Cambridge Retail Park, 22 Witkoppen Road, Paulshof PostNet Suite #249, Private Bag X87, Bryanston, 2024 Phone: +27 (0)87 255 1257

www.creativecounsel.co.zahttp://www.creativecounsel.co.za/ www.publicisgroupe.comhttp://www.publicisgroupe.com/

From: artemious7 notifications@github.com Sent: Thursday, July 11, 2019 3:11 PM To: microsoft/AdaptiveCards AdaptiveCards@noreply.github.com Cc: Massimo Gatta massimo.gatta@publicis.co.za; Mention mention@noreply.github.com Subject: Re: [microsoft/AdaptiveCards] .NET Convert JSON schema to a model (#411)

However, I didn't use the new data binding feature. I used Adaptive Cards v1, so I had to clone adaptive card nodes and change the values according to my data. Here's some code from my projecthttps://gist.github.com/artemious7/e5a8f7d92e30b3b2607e9b8fad3b3d31

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/microsoft/AdaptiveCards/issues/411?email_source=notifications&email_token=ALYENSPKRTWD2HZESQJFDQDP64WNFA5CNFSM4DOZV272YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODZWUTOA#issuecomment-510478776, or mute the threadhttps://github.com/notifications/unsubscribe-auth/ALYENSPEFPL5Y7KXO3N2L6LP64WNFANCNFSM4DOZV27Q.


Disclaimer The information in this email and any attachments may contain proprietary and confidential information that is intended for the addressee(s) only. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, retention or use of the contents of this information is prohibited. When addressed to our clients or vendors, any information contained in this e-mail or any attachments is subject to the terms and conditions in any governing contract. If you have received this e-mail in error, please immediately contact the sender and delete the e-mail.