├── .gitignore ├── LICENSE.me ├── README.md ├── example ├── .vs │ └── config │ │ └── applicationhost.config ├── Api.Ai.Example.sln ├── Bot │ └── Api.Ai.Example.Bot.Application │ │ ├── Api.Ai.Example.Bot.Application.csproj │ │ ├── App_Start │ │ ├── BotAppBootstrap.cs │ │ └── WebApiConfig.cs │ │ ├── Controllers │ │ └── MessagesController.cs │ │ ├── Global.asax │ │ ├── Global.asax.cs │ │ ├── Properties │ │ └── AssemblyInfo.cs │ │ ├── Web.Debug.config │ │ ├── Web.Release.config │ │ ├── Web.config │ │ ├── default.htm │ │ └── packages.config └── Console │ └── Api.Ai.Example.Console │ ├── Api.Ai.Example.Console.csproj │ ├── App.config │ ├── Program.cs │ ├── Properties │ └── AssemblyInfo.cs │ └── packages.config └── src ├── Api.Ai.Csharp.nuspec ├── Api.Ai.sln ├── ApplicationService └── Api.Ai.ApplicationService │ ├── Api.Ai.ApplicationService.csproj │ ├── ApiAiAppService.cs │ ├── ContextAppService.cs │ ├── EntitiesAppService.cs │ ├── Extensions │ └── HttpResponseMessageExtension.cs │ ├── Factories │ ├── AbstractApiAiAppServiceFactory.cs │ ├── ApiAiAppServiceFactory.cs │ └── IApiAiAppServiceFactory.cs │ ├── Interfaces │ ├── IApiAiAppService.cs │ ├── IContextAppService.cs │ ├── IEntitiesAppService.cs │ ├── IIntentsAppService.cs │ ├── IQueryAppService.cs │ ├── ITtsAppService.cs │ └── IUserEntitiesAppService.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── QueryAppService.cs │ ├── TtsAppService.cs │ ├── app.config │ └── packages.config ├── Domain ├── Api.Ai.Domain.DataTransferObject │ ├── Api.Ai.Domain.DataTransferObject.csproj │ ├── ApiAiVersion.cs │ ├── Context.cs │ ├── Entity.cs │ ├── Entry.cs │ ├── Extensions │ │ ├── QueryExtension.cs │ │ └── TtsExtension.cs │ ├── Parameters │ │ ├── Date.cs │ │ └── DatePeriod.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Request │ │ ├── LocationRequest.cs │ │ ├── OriginalRequest.cs │ │ ├── QueryRequest.cs │ │ ├── RequestBase.cs │ │ └── TtsRequest.cs │ ├── Response │ │ ├── EntitiesResponse.cs │ │ ├── FulfillmentResponse.cs │ │ ├── Message │ │ │ ├── BaseMessageResponse.cs │ │ │ ├── CardMessageResponse.cs │ │ │ ├── ImageMessageResponse.cs │ │ │ ├── PayloadMessageResponse.cs │ │ │ ├── QuickReplyMessageResponse.cs │ │ │ └── TextMessageResponse.cs │ │ ├── MetadataResponse.cs │ │ ├── QueryResponse.cs │ │ ├── ResponseBase.cs │ │ ├── StatusREsponse.cs │ │ ├── TtsResponse.cs │ │ └── WebhookResponse.cs │ ├── Serializer │ │ ├── ApiAiJson.cs │ │ └── Converters │ │ │ ├── JsonCreationConverter.cs │ │ │ └── MessageCollectionConverter.cs │ └── packages.config ├── Api.Ai.Domain.Enum │ ├── Api.Ai.Domain.Enum.csproj │ ├── Extensions │ │ └── EnumExtensions.cs │ ├── Language.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── RequestType.cs │ ├── Source.cs │ ├── Type.cs │ └── packages.config └── Api.Ai.Domain.Service │ ├── Api.Ai.Domain.Service.csproj │ ├── Exceptions │ └── ApiAiException.cs │ ├── Factories │ └── IHttpClientFactory.cs │ ├── Interfaces │ └── IHttpClient.cs │ ├── Properties │ └── AssemblyInfo.cs │ └── packages.config ├── Infrastructure └── Api.Ai.Infrastructure │ ├── Api.Ai.Infrastructure.csproj │ ├── Factories │ └── HttpClientFactory.cs │ ├── Http │ └── ApiAiHttpClient.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── app.config │ └── packages.config └── Test └── Api.Ai.Test.Unit ├── Api.Ai.Test.Unit.csproj ├── Properties └── AssemblyInfo.cs ├── SerializerTest.cs └── app.config /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | [Rr]eleases/ 14 | x64/ 15 | x86/ 16 | build/ 17 | bld/ 18 | [Bb]in/ 19 | [Oo]bj/ 20 | [Bb]ower_components/ 21 | [Nn]ode_modules/ 22 | # Roslyn cache directories 23 | *.ide/ 24 | .vs/ 25 | 26 | # MSTest test Results 27 | [Tt]est[Rr]esult*/ 28 | [Bb]uild[Ll]og.* 29 | 30 | #NUNIT 31 | *.VisualState.xml 32 | TestResult.xml 33 | 34 | # Build Results of an ATL Project 35 | [Dd]ebugPS/ 36 | [Rr]eleasePS/ 37 | dlldata.c 38 | 39 | *_i.c 40 | *_p.c 41 | *_i.h 42 | *.ilk 43 | *.meta 44 | *.obj 45 | *.pch 46 | *.pdb 47 | *.pgc 48 | *.pgd 49 | *.rsp 50 | *.sbr 51 | *.tlb 52 | *.tli 53 | *.tlh 54 | *.tmp 55 | *.tmp_proj 56 | *.log 57 | *.vspscc 58 | *.vssscc 59 | .builds 60 | *.pidb 61 | *.svclog 62 | *.scc 63 | 64 | # Chutzpah Test files 65 | _Chutzpah* 66 | 67 | # Visual C++ cache files 68 | ipch/ 69 | *.aps 70 | *.ncb 71 | *.opensdf 72 | *.sdf 73 | *.cachefile 74 | 75 | # Visual Studio profiler 76 | *.psess 77 | *.vsp 78 | *.vspx 79 | 80 | # TFS 2012 Local Workspace 81 | $tf/ 82 | 83 | # Guidance Automation Toolkit 84 | *.gpState 85 | 86 | # ReSharper is a .NET coding add-in 87 | _ReSharper*/ 88 | *.[Rr]e[Ss]harper 89 | *.DotSettings.user 90 | 91 | # JustCode is a .NET coding addin-in 92 | .JustCode 93 | 94 | # TeamCity is a build add-in 95 | _TeamCity* 96 | 97 | # DotCover is a Code Coverage Tool 98 | *.dotCover 99 | 100 | # NCrunch 101 | _NCrunch_* 102 | .*crunch*.local.xml 103 | 104 | # MightyMoose 105 | *.mm.* 106 | AutoTest.Net/ 107 | 108 | # Web workbench (sass) 109 | .sass-cache/ 110 | 111 | # Installshield output folder 112 | [Ee]xpress/ 113 | 114 | # DocProject is a documentation generator add-in 115 | DocProject/buildhelp/ 116 | DocProject/Help/*.HxT 117 | DocProject/Help/*.HxC 118 | DocProject/Help/*.hhc 119 | DocProject/Help/*.hhk 120 | DocProject/Help/*.hhp 121 | DocProject/Help/Html2 122 | DocProject/Help/html 123 | 124 | # Click-Once directory 125 | publish/ 126 | 127 | # Publish Web Output 128 | *.[Pp]ublish.xml 129 | *.azurePubxml 130 | # TODO: Comment the next line if you want to checkin your web deploy settings 131 | # but database connection strings (with potential passwords) will be unencrypted 132 | *.pubxml 133 | 134 | # NuGet Packages 135 | *.nupkg 136 | # The packages folder can be ignored because of Package Restore 137 | **/packages/* 138 | # except build/, which is used as an MSBuild target. 139 | !**/packages/build/ 140 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 141 | #!**/packages/repositories.config 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | bower_components/ 163 | 164 | # RIA/Silverlight projects 165 | Generated_Code/ 166 | 167 | # Backup & report files from converting an old project file 168 | # to a newer Visual Studio version. Backup files are not needed, 169 | # because we have git ;-) 170 | _UpgradeReport_Files/ 171 | Backup*/ 172 | UpgradeLog*.XML 173 | UpgradeLog*.htm 174 | 175 | # SQL Server files 176 | *.mdf 177 | *.ldf 178 | 179 | # Business Intelligence projects 180 | *.rdl.data 181 | *.bim.layout 182 | *.bim_*.settings 183 | 184 | # Microsoft Fakes 185 | FakesAssemblies/ -------------------------------------------------------------------------------- /LICENSE.me: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C# api.ai 2 | 3 | A C# wrapper for the [api.ai](https://api.ai/).
4 | This library makes very simple to integrate .NET applications with [api.ai](https://api.ai/) 5 | 6 | ## Installation 7 | 8 | To install Api.Ai.Csharp, run the following command in the [Package Manager Console](https://docs.nuget.org/consume/package-manager-console) 9 | >PM> Install-Package Api.Ai.Csharp 10 | 11 | ### Begin 12 | 13 | "Api.ai provides developers and companies with the advanced tools they need to build conversational user interfaces for apps and 14 | hardware devices". To begin, you need to have an [api.ai](https://api.ai/) account. 15 | 16 | See api.ai [documentation](https://docs.api.ai/docs) for more details. 17 | 18 | ### Structure 19 | 20 | The solution structure (.sln) is based in [The Onion Architecture](http://bit.ly/1r54LZv) 21 | 22 | [DataTranferObject (DTO)](https://en.wikipedia.org/wiki/Data_transfer_object) project, contains the call parameters used as either parameters in the URL or JSON keys in the POST body 23 | 24 | * [query - submit voice or text queries](https://docs.api.ai/v12/docs/query) 25 | * [QueryRequest](http://bit.ly/1Sb1ljp) 26 | * [QueryResponse](http://bit.ly/23JTGQE) 27 | 28 | * [tts - get text-to-speech](https://docs.api.ai/v12/docs/tts)
29 | * [TtsRequest](http://bit.ly/1XLjFjC) 30 | * [TtsResponse](http://bit.ly/1QqBNcy) 31 | 32 | * [entities - manage entities](https://docs.api.ai/v12/docs/entities)
33 | * [Entity](https://goo.gl/SbpzfL) 34 | * [Entry](https://goo.gl/5HyMo6) 35 | * [EntitiesResponse](https://goo.gl/u7lfXd) 36 | 37 | * [userEntities - manage user-level entities](https://docs.api.ai/v12/docs/userEntities)
38 | not implemented 39 | 40 | * [intents - manage intents](https://docs.api.ai/v12/docs/intents)
41 | not implemented 42 | 43 | * [wehook - receiving](https://docs.api.ai/docs/webhook)
44 | * [WebhookResponse](https://goo.gl/f3q2dr) 45 | 46 | 47 | [ApplicationService](http://bit.ly/1VEQrF6) project implements the application services. 48 | 49 | * [ApiAiAppService](http://bit.ly/240DPd4)
50 | Base properties and methods of application service. 51 | 52 | * [QueryAppService](http://bit.ly/1VC6qUT)
53 | Query application service.
54 | Process natural language in either text form or sound file. 55 | 56 | * [TtsAppService](http://bit.ly/23MJUNG)
57 | Tts application service.
58 | Used to perform text-to-speech - generate speech (audio file) from text. 59 | 60 | * [EntitiesAppService]()
61 | Entitie application service 62 | The entities app service is used to create, retrieve, update and delete developer-defined entity objects. 63 | 64 | * [UserEntitiesAppService]()
65 | not implemented 66 | 67 | * [IntentsAppService]()
68 | not implemented 69 | 70 | ### Usage 71 | 72 | 1. Using [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection), the configuration of the application with [Simple Injector](https://simpleinjector.org/index.html) might look something like this: 73 | 74 | ```csharp 75 | var container = new Container(); 76 | 77 | container.RegisterSingleton(container); 78 | container.Register(); 79 | container.Register(); 80 | ``` 81 | 82 | 2. Get container api.ai app service factory 83 | 84 | ```csharp 85 | var apiAiAppServiceFactory = container.GetInstance(); 86 | ``` 87 | 88 | 3. Create query app service 89 | 90 | ```csharp 91 | var queryAppService = apiAiAppServiceFactory.CreateQueryAppService("https://api.api.ai/v1", 92 | "YOUR_ACCESS_TOKEN"); 93 | ``` 94 | 95 | 4. Create query request 96 | 97 | ```csharp 98 | var queryRequest = new QueryRequest 99 | { 100 | SessionId = "1", 101 | Query = new string[] { "Hello, I want a pizza" }, 102 | Lang = Domain.Enum.Language.English 103 | }; 104 | ``` 105 | 106 | 5. Call api.ai query by http get method 107 | 108 | ```csharp 109 | var queryResponse = await queryAppService.GetQueryAsync(queryRequest); 110 | ``` 111 | 112 | 5.1 Or call api.ai query by http post method (recommended) 113 | 114 | ```csharp 115 | var queryResponse = await queryAppService.PostQueryAsync(queryRequest); 116 | ``` 117 | 118 | Use [ApiAiJson](http://bit.ly/1Qo3h2F) to Serialize/Deserialize response. 119 | 120 | ```csharp 121 | var json = ApiAiJson.Serialize(queryResponse); 122 | ``` 123 | 124 | json property value: 125 | 126 | ```json 127 | { 128 | "result": { 129 | "source": "agent", 130 | "resolvedQuery": "Hello, I want a pizza", 131 | "score": 1.0, 132 | "action": "order.pizza", 133 | "parameters": {}, 134 | "contexts": [ 135 | { 136 | "name": "pizza", 137 | "lifespan": 5 138 | }, 139 | { 140 | "name": "pizza-type", 141 | "lifespan": 5 142 | } 143 | ], 144 | "fulfillment": { 145 | "speech": "Sure, let me help you choose the best pizza for you! What flavor would you like?" 146 | }, 147 | "metadata": { 148 | "intentId": "f5c9fb83-b99e-4af5-bae7-6405a6501d10", 149 | "webhookUsed": false, 150 | "intentName": "pizza" 151 | } 152 | }, 153 | "id": "46ead378-2d8a-41cf-a876-eed8bb531dab", 154 | "timestamp": "2016-04-20T21:05:50.997Z", 155 | "status": { 156 | "code": 200, 157 | "errorType": "success" 158 | } 159 | } 160 | ``` 161 | 162 | [Download the examples](http://bit.ly/1SwgSwj) for test your agent :)
163 | 164 | See the [Bot Application Project](http://bit.ly/23MMcfx) sample which contains code of how to create
165 | and publish your bot in [Microsoft Bot Framework](https://dev.botframework.com/)
166 | 167 | [Download and install the Bot Application template](http://bit.ly/1TlTL4A) 168 | 169 | ### TODO 170 | 171 | - [x] Create tts DataTranferObject 172 | - [x] Implement TtsAppService 173 | - [x] Create entities DataTranferObject 174 | - [x] Implement EntitiesAppService 175 | - [x] Create webhook DataTranferObject 176 | - [ ] Create userEntities DataTranferObject 177 | - [ ] Implement UserEntitiesAppService 178 | - [ ] Create intents DataTranferObject 179 | - [ ] Implement IntentsAppService 180 | - [ ] Write unit tests 181 | 182 | ### License 183 | 184 | This software is open source, licensed under the Apache License.
185 | See [LICENSE.me](https://github.com/brunobrandes/api-ai-csharp/blob/master/LICENSE.me) for details. 186 | -------------------------------------------------------------------------------- /example/Api.Ai.Example.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26403.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Console", "Console", "{557976B5-95F6-4400-8323-78053B3BC6D1}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Example.Console", "Console\Api.Ai.Example.Console\Api.Ai.Example.Console.csproj", "{20D87F02-9C21-49EA-8980-B8417E9D77F1}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Bot", "Bot", "{01E433B0-0414-4B74-B172-C7F1D3620871}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Example.Bot.Application", "Bot\Api.Ai.Example.Bot.Application\Api.Ai.Example.Bot.Application.csproj", "{A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {20D87F02-9C21-49EA-8980-B8417E9D77F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {20D87F02-9C21-49EA-8980-B8417E9D77F1}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {20D87F02-9C21-49EA-8980-B8417E9D77F1}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {20D87F02-9C21-49EA-8980-B8417E9D77F1}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {20D87F02-9C21-49EA-8980-B8417E9D77F1} = {557976B5-95F6-4400-8323-78053B3BC6D1} 34 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4} = {01E433B0-0414-4B74-B172-C7F1D3620871} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Api.Ai.Example.Bot.Application.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | 8 | 9 | 2.0 10 | {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4} 11 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} 12 | Library 13 | Properties 14 | Api.Ai.Example.Bot.Application 15 | Api.Ai.Example.Bot.Application 16 | v4.6.1 17 | true 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | true 29 | full 30 | false 31 | bin\ 32 | DEBUG;TRACE 33 | prompt 34 | 4 35 | 36 | 37 | pdbonly 38 | true 39 | bin\ 40 | TRACE 41 | prompt 42 | 4 43 | 44 | 45 | 46 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.ApplicationService.dll 47 | 48 | 49 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.DataTransferObject.dll 50 | 51 | 52 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.Enum.dll 53 | 54 | 55 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.Service.dll 56 | 57 | 58 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Infrastructure.dll 59 | 60 | 61 | ..\..\packages\Microsoft.Bot.Connector.1.1.0.0\lib\net45\Microsoft.Bot.Connector.dll 62 | True 63 | 64 | 65 | 66 | ..\..\packages\Microsoft.Rest.ClientRuntime.1.8.2\lib\net45\Microsoft.Rest.ClientRuntime.dll 67 | True 68 | 69 | 70 | ..\..\packages\Microsoft.WindowsAzure.ConfigurationManager.3.2.1\lib\net40\Microsoft.WindowsAzure.Configuration.dll 71 | True 72 | 73 | 74 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 75 | 76 | 77 | ..\..\packages\SimpleInjector.3.2.0-alpha2\lib\net45\SimpleInjector.dll 78 | True 79 | 80 | 81 | ..\..\packages\SimpleInjector.Extensions.ExecutionContextScoping.3.2.0-alpha2\lib\net45\SimpleInjector.Extensions.ExecutionContextScoping.dll 82 | True 83 | 84 | 85 | ..\..\packages\SimpleInjector.Integration.WebApi.3.2.0-alpha2\lib\net45\SimpleInjector.Integration.WebApi.dll 86 | True 87 | 88 | 89 | 90 | 91 | 92 | ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 93 | True 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | ..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 107 | True 108 | 109 | 110 | ..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll 111 | True 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | Global.asax 130 | 131 | 132 | 133 | 134 | 135 | 136 | Web.config 137 | 138 | 139 | Web.config 140 | 141 | 142 | 143 | 144 | 10.0 145 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 146 | 147 | 148 | true 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | True 158 | True 159 | 3978 160 | / 161 | http://localhost:3978/ 162 | False 163 | False 164 | 165 | 166 | False 167 | 168 | 169 | 170 | 171 | 178 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/App_Start/BotAppBootstrap.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Factories; 2 | using Api.Ai.Domain.Service.Factories; 3 | using Api.Ai.Infrastructure.Factories; 4 | using SimpleInjector; 5 | using SimpleInjector.Integration.WebApi; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Web; 10 | using System.Web.Http; 11 | 12 | namespace Api.Ai.Example.Bot.Application 13 | { 14 | public class BotAppBootstrap 15 | { 16 | public static Container RegisterContainer(HttpConfiguration config) 17 | { 18 | var container = new Container(); 19 | 20 | container.RegisterWebApiControllers(config); 21 | 22 | container.RegisterSingleton(container); 23 | 24 | container.RegisterSingleton(); 25 | container.RegisterSingleton(); 26 | 27 | config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 28 | 29 | return container; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/App_Start/WebApiConfig.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Serialization; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Web.Http; 7 | 8 | namespace Api.Ai.Example.Bot.Application 9 | { 10 | public static class WebApiConfig 11 | { 12 | public static void Register(HttpConfiguration config) 13 | { 14 | #region Formatters 15 | 16 | // Json settings 17 | config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 18 | config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 19 | config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; 20 | JsonConvert.DefaultSettings = () => new JsonSerializerSettings() 21 | { 22 | ContractResolver = new CamelCasePropertyNamesContractResolver(), 23 | Formatting = Newtonsoft.Json.Formatting.Indented, 24 | NullValueHandling = NullValueHandling.Ignore, 25 | }; 26 | 27 | #endregion 28 | // Web API configuration and services 29 | 30 | // Web API routes 31 | config.MapHttpAttributeRoutes(); 32 | 33 | config.Routes.MapHttpRoute( 34 | name: "DefaultApi", 35 | routeTemplate: "api/{controller}/{id}", 36 | defaults: new { id = RouteParameter.Optional } 37 | ); 38 | 39 | var container = BotAppBootstrap.RegisterContainer(config); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Controllers/MessagesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | using System.Web.Http; 7 | using System.Web.Http.Description; 8 | using Microsoft.Bot.Connector; 9 | using Newtonsoft.Json; 10 | using Api.Ai.ApplicationService.Factories; 11 | using Api.Ai.Domain.Service.Factories; 12 | using Api.Ai.Domain.DataTransferObject.Request; 13 | using Api.Ai.Domain.Enum; 14 | 15 | namespace Api.Ai.Example.Bot.Application 16 | { 17 | [BotAuthentication] 18 | public class MessagesController : ApiController 19 | { 20 | #region Private Fields 21 | 22 | private readonly IApiAiAppServiceFactory _apiAiAppServiceFactory; 23 | private readonly IHttpClientFactory _httpClientFactory; 24 | 25 | #endregion 26 | 27 | #region Constructor 28 | 29 | public MessagesController(IApiAiAppServiceFactory apiAiAppServiceFactory, IHttpClientFactory httpClientFactory) 30 | { 31 | _apiAiAppServiceFactory = apiAiAppServiceFactory; 32 | _httpClientFactory = httpClientFactory; 33 | } 34 | 35 | #endregion 36 | 37 | #region Private Methods 38 | 39 | private Message HandleSystemMessage(Message message) 40 | { 41 | if (message.Type == "Ping") 42 | { 43 | Message reply = message.CreateReplyMessage(); 44 | reply.Type = "Ping"; 45 | return reply; 46 | } 47 | else if (message.Type == "DeleteUserData") 48 | { 49 | // Implement user deletion here 50 | // If we handle user deletion, return a real message 51 | } 52 | else if (message.Type == "BotAddedToConversation") 53 | { 54 | } 55 | else if (message.Type == "BotRemovedFromConversation") 56 | { 57 | } 58 | else if (message.Type == "UserAddedToConversation") 59 | { 60 | } 61 | else if (message.Type == "UserRemovedFromConversation") 62 | { 63 | } 64 | else if (message.Type == "EndOfConversation") 65 | { 66 | } 67 | 68 | return null; 69 | } 70 | 71 | /// 72 | /// Call query api.ai 73 | /// 74 | /// 75 | /// 76 | private async Task GetSpeechAsync(Message message) 77 | { 78 | var result = "Ooops ! Me desculpe, ainda não sei sobre isso :("; 79 | 80 | try 81 | { 82 | var queryAppService = _apiAiAppServiceFactory.CreateQueryAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN"); 83 | 84 | var queryRequest = new QueryRequest 85 | { 86 | Query = new string[] { message.Text }, 87 | Lang = Language.Portuguese, 88 | SessionId = message.Id 89 | }; 90 | 91 | var queryResponse = await queryAppService.GetQueryAsync(queryRequest); 92 | 93 | if (queryResponse != null && queryResponse.Result != null) 94 | { 95 | if (queryResponse.Status != null) 96 | { 97 | if (queryResponse.Status.Code == (int)HttpStatusCode.OK) 98 | { 99 | if (queryResponse.Result.Fulfillment != null && string.IsNullOrEmpty(queryResponse.Result.Fulfillment.Speech)) 100 | { 101 | result = "Ooops ! Me desculpe, ainda não sei sobre isso :("; 102 | } 103 | else 104 | { 105 | result = queryResponse.Result.Fulfillment.Speech; 106 | } 107 | } 108 | } 109 | } 110 | } 111 | catch { } 112 | 113 | return result; 114 | } 115 | 116 | #endregion 117 | 118 | #region Api Methods 119 | 120 | /// 121 | /// POST: api/Messages 122 | /// Receive a message from a user and reply to it 123 | /// 124 | public async Task Post([FromBody]Message message) 125 | { 126 | if (message.Type == "Message") 127 | { 128 | var speech = await GetSpeechAsync(message); 129 | 130 | // return our reply to the user 131 | return message.CreateReplyMessage(speech); 132 | } 133 | else 134 | { 135 | return HandleSystemMessage(message); 136 | } 137 | } 138 | 139 | #endregion 140 | } 141 | } -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="Api.Ai.Example.Bot.Application.WebApiApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Http; 6 | using System.Web.Routing; 7 | 8 | namespace Api.Ai.Example.Bot.Application 9 | { 10 | public class WebApiApplication : System.Web.HttpApplication 11 | { 12 | protected void Application_Start() 13 | { 14 | GlobalConfiguration.Configure(WebApiConfig.Register); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Example.Bot.Application")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Example.Bot.Application")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a8ba1066-5695-4d71-abb4-65e5a5e0c3d4")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Web.Debug.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Web.Release.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/default.htm: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 |

Api.Ai.Example.Bot.Application

9 |

Describe your bot here and your terms of use etc.

10 |

Visit Bot Framework to register your bot. When you register it, remember to set your bot's endpoint to

https://your_bots_hostname/api/messages

11 | 12 | 13 | -------------------------------------------------------------------------------- /example/Bot/Api.Ai.Example.Bot.Application/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /example/Console/Api.Ai.Example.Console/Api.Ai.Example.Console.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {20D87F02-9C21-49EA-8980-B8417E9D77F1} 8 | Exe 9 | Properties 10 | Api.Ai.Example.Console 11 | Api.Ai.Example.Console 12 | v4.6.1 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.ApplicationService.dll 38 | 39 | 40 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.DataTransferObject.dll 41 | 42 | 43 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.Enum.dll 44 | 45 | 46 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Domain.Service.dll 47 | 48 | 49 | ..\..\packages\Api.Ai.Csharp.1.0.2.3\lib\net461\Api.Ai.Infrastructure.dll 50 | 51 | 52 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 53 | 54 | 55 | ..\..\packages\SimpleInjector.3.1.5\lib\net45\SimpleInjector.dll 56 | True 57 | 58 | 59 | 60 | 61 | ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 62 | True 63 | 64 | 65 | ..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 66 | True 67 | 68 | 69 | ..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll 70 | True 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | Designer 87 | 88 | 89 | 90 | 97 | -------------------------------------------------------------------------------- /example/Console/Api.Ai.Example.Console/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/Console/Api.Ai.Example.Console/Program.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Factories; 2 | using Api.Ai.Domain.DataTransferObject; 3 | using Api.Ai.Domain.DataTransferObject.Request; 4 | using Api.Ai.Domain.DataTransferObject.Response; 5 | using Api.Ai.Domain.DataTransferObject.Serializer; 6 | using Api.Ai.Domain.Service.Factories; 7 | using Api.Ai.Infrastructure.Factories; 8 | using SimpleInjector; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | 13 | namespace Api.Ai.Example.Console 14 | { 15 | class Program 16 | { 17 | static void Main(string[] args) 18 | { 19 | var container = new Container(); 20 | 21 | container.RegisterSingleton(container); 22 | container.Register(); 23 | container.Register(); 24 | 25 | //Get container api.ai app service factory 26 | var apiAiAppServiceFactory = container.GetInstance(); 27 | 28 | Query(container, apiAiAppServiceFactory); 29 | Tts(container, apiAiAppServiceFactory); 30 | Entity(container, apiAiAppServiceFactory); 31 | Context(container, apiAiAppServiceFactory); 32 | 33 | System.Console.ReadLine(); 34 | } 35 | 36 | #region Private Methods 37 | 38 | private static void Query(Container container, IApiAiAppServiceFactory apiAiAppServiceFactory) 39 | { 40 | ///Create full contact app service 41 | var queryAppService = apiAiAppServiceFactory.CreateQueryAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN"); 42 | 43 | ///Create query request 44 | var queryRequest = new QueryRequest 45 | { 46 | SessionId = "1", 47 | Query = new string[] { "Hello, I want a pizza" }, 48 | Lang = Domain.Enum.Language.English 49 | }; 50 | 51 | /// Call api.ai query by get 52 | var queryResponse = queryAppService.PostQueryAsync(queryRequest).Result; 53 | 54 | System.Console.Write(ApiAiJson.Serialize(queryResponse)); 55 | } 56 | 57 | private static void Tts(Container container, IApiAiAppServiceFactory apiAiAppServiceFactory) 58 | { 59 | ///Create full contact app service 60 | var ttsAppService = apiAiAppServiceFactory.CreateTtsAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN"); 61 | 62 | ///Create query request 63 | var ttsRequest = new TtsRequest 64 | { 65 | Text = "Hello, I want a pizza" 66 | }; 67 | 68 | /// First - Create a path 69 | string path = @"D:\api-ai-csharp\tts"; 70 | 71 | /// Call api.ai query by get 72 | var ttsResponse = ttsAppService.GetTtsAsync(ttsRequest).Result; 73 | 74 | if (ttsResponse == null) 75 | { 76 | throw new Exception("tts error - Get tts async returned null"); 77 | } 78 | 79 | var fileName = ttsResponse.WriteToFile(path).Result; 80 | 81 | System.Console.Write($"File created: {path}\\{fileName}"); 82 | } 83 | 84 | private static void Entity(Container container, IApiAiAppServiceFactory apiAiAppServiceFactory) 85 | { 86 | var entityAppService = apiAiAppServiceFactory.CreateEntitiesAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN"); 87 | 88 | var entities = entityAppService.GetAllAsync().Result; 89 | 90 | if (entities != null) 91 | { 92 | System.Console.Write($"{entities.Count} entities found."); 93 | 94 | var entity = entityAppService.GetByIdAsync(entities.FirstOrDefault().Id).Result; 95 | } 96 | 97 | try 98 | { 99 | var newEntity = new Entity { Name = "test", Entries = new List { { new Entry { Value = "test", Synonyms = new List { "test" } } } } }; 100 | 101 | newEntity.Id = entityAppService.CreateAsync(new Entity { Name = "test", Entries = new List { { new Entry { Value = "test", Synonyms = new List { "test" } } } } }).Result; 102 | 103 | if (!string.IsNullOrEmpty(newEntity.Id)) 104 | { 105 | entityAppService.AddEntriesSpecifiedEntityAsync(newEntity.Id, new List { { new Entry { Value = "test-2", Synonyms = new List { "a", "b" } } } }).Wait(); 106 | 107 | entityAppService.UpdatesEntityEntriesAsync(newEntity.Id, new List { { new Entry { Value = "test-2", Synonyms = new List { "c", "d" } } } }).Wait(); 108 | 109 | newEntity.Name = "test-up"; 110 | 111 | entityAppService.UpdateAsync(newEntity).Wait(); 112 | 113 | entityAppService.DeleteAsync(newEntity.Id).Wait(); 114 | } 115 | } 116 | catch (Exception ex) 117 | { 118 | System.Console.Write($"Error - {ex.ToString()}"); 119 | } 120 | } 121 | 122 | private static void Context(Container container, IApiAiAppServiceFactory apiAiAppServiceFactory) 123 | { 124 | var contextAppService = apiAiAppServiceFactory.CreateContextAppService("https://api.api.ai/v1", "YOUR_ACCESS_TOKEN"); 125 | 126 | try 127 | { 128 | contextAppService.DeleteAsync("11").Wait(); 129 | } 130 | catch (Exception ex) 131 | { 132 | System.Console.Write($"Error - {ex.ToString()}"); 133 | } 134 | } 135 | 136 | #endregion 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /example/Console/Api.Ai.Example.Console/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Example.Console")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Example.Console")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("20d87f02-9c21-49ea-8980-b8417e9d77f1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /example/Console/Api.Ai.Example.Console/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Api.Ai.Csharp.nuspec: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Api.Ai.Csharp 5 | 1.0.2.4 6 | Api.Ai.Csharp 7 | Bruno Brandes 8 | Bruno Brandes 9 | https://github.com/brunobrandes/api-ai-csharp 10 | https://github.com/brunobrandes/api-ai-csharp 11 | false 12 | A C# wrapper for the api.ai 13 | Create api.ai exception - Show api error details; Deserialize all message collection types. 14 | Bruno Brandes 15 | pt-BR 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/Api.Ai.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Domain", "Domain", "{596634F2-D16D-482E-9DC8-8D70A077D12D}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{7BCFDE65-C709-4C9A-82E4-D1995B3663FA}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Domain.Enum", "Domain\Api.Ai.Domain.Enum\Api.Ai.Domain.Enum.csproj", "{A7F5E2F0-CFD3-4070-8A37-EC3728587F1E}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Domain.Service", "Domain\Api.Ai.Domain.Service\Api.Ai.Domain.Service.csproj", "{0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Infrastructure", "Infrastructure\Api.Ai.Infrastructure\Api.Ai.Infrastructure.csproj", "{BF7434CB-C80D-44A7-9FF0-6AA8AB950B61}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Domain.DataTransferObject", "Domain\Api.Ai.Domain.DataTransferObject\Api.Ai.Domain.DataTransferObject.csproj", "{7D744B12-250D-47A6-99F4-5BBDE1FB8AE6}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApplicationService", "ApplicationService", "{3D6C1EB3-C1B5-467A-8099-781C3EA6AEFD}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.ApplicationService", "ApplicationService\Api.Ai.ApplicationService\Api.Ai.ApplicationService.csproj", "{6848EDCA-4533-4BFF-AEC9-C8F984B74521}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{4F318574-5A41-4D90-8992-9442C0BE809F}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Ai.Test.Unit", "Test\Api.Ai.Test.Unit\Api.Ai.Test.Unit.csproj", "{0F4FA7C3-3388-4F24-AC1E-A3E440C3C982}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982}.Release|Any CPU.Build.0 = Release|Any CPU 56 | EndGlobalSection 57 | GlobalSection(SolutionProperties) = preSolution 58 | HideSolutionNode = FALSE 59 | EndGlobalSection 60 | GlobalSection(NestedProjects) = preSolution 61 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E} = {596634F2-D16D-482E-9DC8-8D70A077D12D} 62 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7} = {596634F2-D16D-482E-9DC8-8D70A077D12D} 63 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61} = {7BCFDE65-C709-4C9A-82E4-D1995B3663FA} 64 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6} = {596634F2-D16D-482E-9DC8-8D70A077D12D} 65 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521} = {3D6C1EB3-C1B5-467A-8099-781C3EA6AEFD} 66 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982} = {4F318574-5A41-4D90-8992-9442C0BE809F} 67 | EndGlobalSection 68 | EndGlobal 69 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Api.Ai.ApplicationService.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6848EDCA-4533-4BFF-AEC9-C8F984B74521} 8 | Library 9 | Properties 10 | Api.Ai.ApplicationService 11 | Api.Ai.ApplicationService 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 35 | 36 | 37 | 38 | 39 | ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 40 | True 41 | 42 | 43 | ..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 44 | True 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | {7d744b12-250d-47a6-99f4-5bbde1fb8ae6} 75 | Api.Ai.Domain.DataTransferObject 76 | 77 | 78 | {a7f5e2f0-cfd3-4070-8a37-ec3728587f1e} 79 | Api.Ai.Domain.Enum 80 | 81 | 82 | {0f6f0f2c-1a13-4607-81d8-2449d0e7b6e7} 83 | Api.Ai.Domain.Service 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 98 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/ApiAiAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using Api.Ai.Domain.Service.Factories; 3 | using Api.Ai.Domain.Service.Interfaces; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.ApplicationService 11 | { 12 | public class ApiAiAppService : IApiAiAppService 13 | { 14 | #region Private Fields 15 | 16 | private readonly IServiceProvider _serviceProvider; 17 | private readonly IHttpClientFactory _htpClientFactory; 18 | 19 | private string _baseUrl; 20 | private string _accessToken; 21 | 22 | 23 | #endregion 24 | 25 | #region Constructor 26 | 27 | public ApiAiAppService(IServiceProvider serviceProvider, IHttpClientFactory htpClientFactory) 28 | { 29 | _serviceProvider = serviceProvider; 30 | _htpClientFactory = htpClientFactory; 31 | } 32 | 33 | #endregion 34 | 35 | #region IApiAiAppService 36 | 37 | public IHttpClientFactory HttpClientFactory 38 | { 39 | get 40 | { 41 | return _htpClientFactory; 42 | } 43 | } 44 | 45 | public string BaseUrl 46 | { 47 | get 48 | { 49 | return _baseUrl; 50 | } 51 | } 52 | 53 | public string AccessToken 54 | { 55 | get 56 | { 57 | return _accessToken; 58 | } 59 | } 60 | 61 | 62 | public void Initializer(string baseUrl, string accessToken) 63 | { 64 | _baseUrl = baseUrl; 65 | _accessToken = accessToken; 66 | } 67 | 68 | #endregion 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/ContextAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using Api.Ai.Domain.Service.Factories; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Api.Ai.ApplicationService.Extensions; 9 | using Api.Ai.Domain.DataTransferObject.Response; 10 | using System.Net.Http; 11 | using Api.Ai.Domain.DataTransferObject.Serializer; 12 | 13 | namespace Api.Ai.ApplicationService 14 | { 15 | public class ContextAppService : ApiAiAppService, IContextAppService 16 | { 17 | #region Contructor 18 | 19 | public ContextAppService(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory) 20 | : base(serviceProvider, httpClientFactory) 21 | { 22 | } 23 | 24 | #endregion 25 | 26 | #region IContextAppService 27 | 28 | public async Task DeleteAsync(string sessionId) 29 | { 30 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 31 | { 32 | var httpResponseMessage = await httpClient.DeleteAsync(new Uri($"{BaseUrl}/contexts?sessionId={sessionId}")); 33 | 34 | var content = await httpResponseMessage.ToStringContentAsync(); 35 | 36 | var responseBase = ApiAiJson.Deserialize(content); 37 | 38 | if (responseBase == null) 39 | { 40 | throw new Exception("Delete contexts error - Deserialize content is null or empty."); 41 | } 42 | 43 | if (!responseBase.Status.IsSuccessStatusCode) 44 | { 45 | throw new Exception($"Delete contexts error - Invalid http status code '{responseBase.Status.Code}'"); 46 | } 47 | 48 | } 49 | } 50 | 51 | #endregion 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/EntitiesAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Api.Ai.Domain.DataTransferObject; 8 | using Api.Ai.Domain.DataTransferObject.Response; 9 | using Api.Ai.Domain.Service.Factories; 10 | using Api.Ai.Domain.DataTransferObject.Extensions; 11 | using Api.Ai.Domain.Enum; 12 | using System.Net.Http; 13 | using Api.Ai.ApplicationService.Extensions; 14 | using Api.Ai.Domain.DataTransferObject.Serializer; 15 | using Api.Ai.Domain.Service.Exceptions; 16 | using System.Net; 17 | 18 | namespace Api.Ai.ApplicationService 19 | { 20 | public class EntitiesAppService : ApiAiAppService, IEntitiesAppService 21 | { 22 | #region Contructor 23 | 24 | public EntitiesAppService(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory) 25 | : base(serviceProvider, httpClientFactory) 26 | { 27 | } 28 | 29 | #endregion 30 | 31 | #region IEntitiesAppService Members 32 | 33 | public async Task> GetAllAsync() 34 | { 35 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 36 | { 37 | var httpResponseMessage = await httpClient.GetAsync(new Uri($"{BaseUrl}/entities")); 38 | 39 | var content = await httpResponseMessage.ToStringContentAsync(); 40 | return ApiAiJson>.Deserialize(content); 41 | 42 | } 43 | } 44 | 45 | public async Task GetByIdAsync(string id) 46 | { 47 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 48 | { 49 | var httpResponseMessage = await httpClient.GetAsync(new Uri($"{BaseUrl}/entities/{id}?v={ApiAiVersion.Default}")); 50 | 51 | var content = await httpResponseMessage.ToStringContentAsync(); 52 | return ApiAiJson.Deserialize(content); 53 | } 54 | } 55 | 56 | public async Task CreateAsync(Entity entity) 57 | { 58 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 59 | { 60 | var httpResponseMessage = await httpClient.PostAsync(new Uri($"{BaseUrl}/entities?v={ApiAiVersion.Default}"), 61 | new StringContent(ApiAiJson.Serialize(entity), Encoding.UTF8, "application/json")); 62 | 63 | var content = await httpResponseMessage.ToStringContentAsync(); 64 | var responseBase = ApiAiJson.Deserialize(content); 65 | 66 | if (responseBase == null) 67 | { 68 | throw new ApiAiException(HttpStatusCode.Conflict, "Create entity error - Deserialize content is null or empty."); 69 | } 70 | 71 | if (!responseBase.Status.IsSuccessStatusCode) 72 | { 73 | throw new ApiAiException(responseBase.Status.Code, "Create entity error."); 74 | } 75 | 76 | return responseBase.Id; 77 | } 78 | } 79 | 80 | public async Task UpdateAsync(Entity entity) 81 | { 82 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 83 | { 84 | var httpResponseMessage = await httpClient.PutAsync(new Uri($"{BaseUrl}/entities/{entity.Id}"), 85 | new StringContent(ApiAiJson.Serialize(entity), Encoding.UTF8, "application/json")); 86 | 87 | var content = await httpResponseMessage.ToStringContentAsync(); 88 | var responseBase = ApiAiJson.Deserialize(content); 89 | 90 | if (responseBase == null) 91 | { 92 | throw new ApiAiException(HttpStatusCode.Conflict, "Update entity error - Deserialize content is null or empty."); 93 | } 94 | 95 | if (!responseBase.Status.IsSuccessStatusCode) 96 | { 97 | throw new ApiAiException(responseBase.Status.Code, "Update entity error."); 98 | } 99 | } 100 | } 101 | 102 | public async Task DeleteAsync(string id) 103 | { 104 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 105 | { 106 | var httpResponseMessage = await httpClient.DeleteAsync(new Uri($"{BaseUrl}/entities/{id}?v={ApiAiVersion.Default}")); 107 | 108 | var content = await httpResponseMessage.ToStringContentAsync(); 109 | var responseBase = ApiAiJson.Deserialize(content); 110 | 111 | if (responseBase == null) 112 | { 113 | throw new ApiAiException(HttpStatusCode.Conflict, "Delete entity error - Deserialize content is null or empty."); 114 | } 115 | 116 | if (!responseBase.Status.IsSuccessStatusCode) 117 | { 118 | throw new ApiAiException(responseBase.Status.Code, "Delete entity error."); 119 | } 120 | } 121 | } 122 | 123 | public async Task AddEntriesSpecifiedEntityAsync(string id, List entries) 124 | { 125 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 126 | { 127 | var httpResponseMessage = await httpClient.PostAsync(new Uri($"{BaseUrl}/entities/{id}/entries"), 128 | new StringContent(ApiAiJson>.Serialize(entries), Encoding.UTF8, "application/json")); 129 | 130 | var content = await httpResponseMessage.ToStringContentAsync(); 131 | var responseBase = ApiAiJson.Deserialize(content); 132 | 133 | if (responseBase == null) 134 | { 135 | throw new ApiAiException(HttpStatusCode.Conflict, "Add entries specified entity error - Deserialize content is null or empty."); 136 | } 137 | 138 | if (!responseBase.Status.IsSuccessStatusCode) 139 | { 140 | throw new ApiAiException(responseBase.Status.Code, "Add entries specified entity error."); 141 | } 142 | } 143 | } 144 | 145 | public async Task UpdatesEntityEntriesAsync(string id, List entries) 146 | { 147 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 148 | { 149 | var httpResponseMessage = await httpClient.PutAsync(new Uri($"{BaseUrl}/entities/{id}/entries"), 150 | new StringContent(ApiAiJson>.Serialize(entries), Encoding.UTF8, "application/json")); 151 | 152 | var content = await httpResponseMessage.ToStringContentAsync(); 153 | var responseBase = ApiAiJson.Deserialize(content); 154 | 155 | if (responseBase == null) 156 | { 157 | throw new ApiAiException(HttpStatusCode.Conflict, "Updates entity entries error - Deserialize content is null or empty."); 158 | } 159 | 160 | if (!responseBase.Status.IsSuccessStatusCode) 161 | { 162 | throw new ApiAiException(responseBase.Status.Code, "Updates entity entries error."); 163 | } 164 | } 165 | } 166 | 167 | #endregion 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Extensions/HttpResponseMessageExtension.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Response; 2 | using Api.Ai.Domain.DataTransferObject.Serializer; 3 | using Api.Ai.Domain.Service.Exceptions; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Net; 9 | using System.Net.Http; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | using System.Web.Http; 13 | 14 | namespace Api.Ai.ApplicationService.Extensions 15 | { 16 | public static class HttpResponseMessageExtension 17 | { 18 | #region Private Methods 19 | 20 | private static async Task ValidateResponse(HttpResponseMessage httpResponseMessage) 21 | { 22 | if (!httpResponseMessage.IsSuccessStatusCode) 23 | { 24 | var errorDetails = string.Empty; 25 | 26 | if (httpResponseMessage.Content != null) 27 | { 28 | var content = await httpResponseMessage.Content.ReadAsStringAsync(); 29 | 30 | if (!string.IsNullOrEmpty(content)) 31 | { 32 | try 33 | { 34 | var queryResponse = ApiAiJson.Deserialize(content); 35 | 36 | if (queryResponse != null && queryResponse.Status != null && !string.IsNullOrEmpty(queryResponse.Status.ErrorDetails)) 37 | { 38 | errorDetails = queryResponse.Status.ErrorDetails; 39 | } 40 | } 41 | catch { } 42 | } 43 | } 44 | 45 | throw new ApiAiException(httpResponseMessage.StatusCode, !string.IsNullOrEmpty(errorDetails) ? errorDetails : "Http response message error."); 46 | } 47 | 48 | if (httpResponseMessage.Content == null) 49 | { 50 | throw new ApiAiException(httpResponseMessage.StatusCode, "api.ai content returned is null."); 51 | } 52 | } 53 | 54 | #endregion 55 | 56 | #region Public Methods 57 | 58 | public static async Task ToStringContentAsync(this HttpResponseMessage httpResponseMessage) 59 | { 60 | await ValidateResponse(httpResponseMessage); 61 | 62 | var content = await httpResponseMessage.Content.ReadAsStringAsync(); 63 | 64 | if (string.IsNullOrEmpty(content)) 65 | { 66 | throw new ApiAiException(HttpStatusCode.Conflict, "api.ai string content returned null or empty."); 67 | } 68 | 69 | return content; 70 | } 71 | 72 | public static async Task ToStreamContentAsync(this HttpResponseMessage httpResponseMessage) 73 | { 74 | await ValidateResponse(httpResponseMessage); 75 | 76 | var content = await httpResponseMessage.Content.ReadAsStreamAsync(); 77 | 78 | if (content == null || content.Length == 0) 79 | { 80 | throw new ApiAiException(HttpStatusCode.Conflict, "api.ai stream content returned null."); 81 | } 82 | 83 | return content; 84 | } 85 | 86 | #endregion 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Factories/AbstractApiAiAppServiceFactory.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using Api.Ai.Domain.DataTransferObject.Response; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.ApplicationService.Factories 10 | { 11 | public abstract class AbstractApiAiAppServiceFactory : IApiAiAppServiceFactory 12 | { 13 | #region IFullContactAppServiceFactory 14 | 15 | public abstract IQueryAppService CreateQueryAppService(string url, string apiKey); 16 | public abstract ITtsAppService CreateTtsAppService(string url, string apiKey); 17 | public abstract IEntitiesAppService CreateEntitiesAppService(string url, string apiKey); 18 | public abstract IContextAppService CreateContextAppService(string url, string apiKey); 19 | 20 | #endregion 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Factories/ApiAiAppServiceFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Api.Ai.ApplicationService.Interfaces; 7 | 8 | namespace Api.Ai.ApplicationService.Factories 9 | { 10 | public class ApiAiAppServiceFactory : AbstractApiAiAppServiceFactory 11 | { 12 | #region Private Fields 13 | 14 | private readonly IServiceProvider _serviceProvider; 15 | 16 | #endregion 17 | 18 | #region Constructor 19 | 20 | public ApiAiAppServiceFactory(IServiceProvider serviceProvider) 21 | { 22 | _serviceProvider = serviceProvider; 23 | } 24 | 25 | #endregion 26 | 27 | #region AbstractApiAiAppServiceFactory Members 28 | 29 | public override IQueryAppService CreateQueryAppService(string url, string apiKey) 30 | { 31 | var queryAppService = _serviceProvider.GetService(typeof(QueryAppService)) as IQueryAppService; 32 | 33 | if (queryAppService == null) 34 | { 35 | throw new Exception("ServiceProvider get 'IQueryAppService' service error."); 36 | } 37 | 38 | queryAppService.Initializer(url, apiKey); 39 | 40 | return queryAppService; 41 | 42 | } 43 | 44 | public override ITtsAppService CreateTtsAppService(string url, string apiKey) 45 | { 46 | var ttsAppService = _serviceProvider.GetService(typeof(TtsAppService)) as ITtsAppService; 47 | 48 | if (ttsAppService == null) 49 | { 50 | throw new Exception("ServiceProvider get 'ITtsAppService' service error."); 51 | } 52 | 53 | ttsAppService.Initializer(url, apiKey); 54 | 55 | return ttsAppService; 56 | 57 | } 58 | 59 | public override IEntitiesAppService CreateEntitiesAppService(string url, string apiKey) 60 | { 61 | var entitiesAppService = _serviceProvider.GetService(typeof(EntitiesAppService)) as IEntitiesAppService; 62 | 63 | if (entitiesAppService == null) 64 | { 65 | throw new Exception("ServiceProvider get 'IEntitiesAppService' service error."); 66 | } 67 | 68 | entitiesAppService.Initializer(url, apiKey); 69 | 70 | return entitiesAppService; 71 | } 72 | 73 | public override IContextAppService CreateContextAppService(string url, string apiKey) 74 | { 75 | var contextAppService = _serviceProvider.GetService(typeof(ContextAppService)) as IContextAppService; 76 | 77 | if (contextAppService == null) 78 | { 79 | throw new Exception("ServiceProvider get 'IContextAppService' service error."); 80 | } 81 | 82 | contextAppService.Initializer(url, apiKey); 83 | return contextAppService; 84 | } 85 | 86 | #endregion 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Factories/IApiAiAppServiceFactory.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using Api.Ai.Domain.DataTransferObject.Response; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.ApplicationService.Factories 10 | { 11 | public interface IApiAiAppServiceFactory 12 | { 13 | IQueryAppService CreateQueryAppService(string url, string apiKey); 14 | ITtsAppService CreateTtsAppService(string url, string apiKey); 15 | IEntitiesAppService CreateEntitiesAppService(string url, string apiKey); 16 | IContextAppService CreateContextAppService(string url, string apiKey); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IApiAiAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Response; 2 | using Api.Ai.Domain.Service.Factories; 3 | using Api.Ai.Domain.Service.Interfaces; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.ApplicationService.Interfaces 11 | { 12 | public interface IApiAiAppService 13 | { 14 | IHttpClientFactory HttpClientFactory { get; } 15 | 16 | /// 17 | /// Base Url 18 | /// 19 | string BaseUrl { get; } 20 | 21 | /// 22 | /// access token 23 | /// 24 | string AccessToken { get; } 25 | 26 | /// 27 | /// Initializer parameters. 28 | /// 29 | /// 30 | /// 31 | void Initializer(string baseUrl, string accessToken); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IContextAppService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.ApplicationService.Interfaces 8 | { 9 | public interface IContextAppService : IApiAiAppService 10 | { 11 | Task DeleteAsync(string sessionId); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IEntitiesAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject; 2 | using Api.Ai.Domain.DataTransferObject.Response; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.ApplicationService.Interfaces 10 | { 11 | public interface IEntitiesAppService : IApiAiAppService 12 | { 13 | /// 14 | /// Retrieves a list of all entities for the agent. 15 | /// The following request returns all entities for the agent that is associated with the access token. 16 | /// 17 | /// 18 | Task> GetAllAsync(); 19 | 20 | /// 21 | /// Retrieves the specified entity. 22 | /// The following request returns the entity with ID of {eid} 23 | /// 24 | /// 25 | /// 26 | Task GetByIdAsync(string id); 27 | 28 | /// 29 | /// Creates a new entity. 30 | /// The POST body is an entity object without the "id", "isEnum", and "automatedExpansion" elements. 31 | /// 32 | /// 33 | /// 34 | Task CreateAsync(Entity entity); 35 | 36 | /// 37 | /// Adds entries to the specified entity. 38 | /// The POST body is an array of entity entry objects in JSON format. 39 | /// 40 | /// 41 | /// 42 | /// 43 | Task AddEntriesSpecifiedEntityAsync(string id, List entries); 44 | 45 | /// 46 | /// Updates the specified entity. 47 | /// The following request updates an entity of ID {eid} 48 | /// 49 | /// 50 | /// 51 | Task UpdateAsync(Entity entity); 52 | 53 | /// 54 | /// Updates entity entries. 55 | /// he following request updates the {sample} entity entry corresponding to the reference value {sample-value}. 56 | /// 57 | /// 58 | /// 59 | Task UpdatesEntityEntriesAsync(string id, List entries); 60 | 61 | /// 62 | /// Deletes the specified entity. 63 | /// The following request deletes an entity of ID {eid} 64 | /// 65 | /// 66 | /// 67 | Task DeleteAsync(string id); 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IIntentsAppService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.ApplicationService.Interfaces 8 | { 9 | interface IIntentsAppService 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IQueryAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Request; 2 | using Api.Ai.Domain.DataTransferObject.Response; 3 | using Api.Ai.Domain.Service.Factories; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.ApplicationService.Interfaces 11 | { 12 | public interface IQueryAppService : IApiAiAppService 13 | { 14 | Task GetQueryAsync(QueryRequest request); 15 | 16 | Task PostQueryAsync(QueryRequest request); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/ITtsAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Request; 2 | using Api.Ai.Domain.DataTransferObject.Response; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.ApplicationService.Interfaces 10 | { 11 | public interface ITtsAppService : IApiAiAppService 12 | { 13 | Task GetTtsAsync(TtsRequest request); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Interfaces/IUserEntitiesAppService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.ApplicationService.Interfaces 8 | { 9 | interface IUserEntitiesAppService 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.ApplicationService")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.ApplicationService")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6848edca-4533-4bff-aec9-c8f984b74521")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/QueryAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Api.Ai.Domain.DataTransferObject.Request; 8 | using Api.Ai.Domain.DataTransferObject.Response; 9 | using Api.Ai.Domain.Service.Interfaces; 10 | using Api.Ai.Domain.Service.Factories; 11 | using System.Net.Http; 12 | using System.Net; 13 | using Api.Ai.Domain.DataTransferObject.Extensions; 14 | using Api.Ai.ApplicationService.Extensions; 15 | using Api.Ai.Domain.DataTransferObject.Serializer; 16 | 17 | namespace Api.Ai.ApplicationService 18 | { 19 | public class QueryAppService : ApiAiAppService, IQueryAppService 20 | { 21 | #region Contructor 22 | 23 | public QueryAppService(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory) 24 | : base(serviceProvider, httpClientFactory) 25 | { 26 | } 27 | 28 | #endregion 29 | 30 | #region IQueryAppService Members 31 | 32 | public async Task GetQueryAsync(QueryRequest request) 33 | { 34 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 35 | { 36 | var uri = new Uri($"{BaseUrl}/{request.ToHttpGetQueryString()}"); 37 | 38 | var httpResponseMessage = await httpClient.GetAsync(uri); 39 | 40 | var content = await httpResponseMessage.ToStringContentAsync(); 41 | return ApiAiJson.Deserialize(content); 42 | } 43 | } 44 | 45 | public async Task PostQueryAsync(QueryRequest request) 46 | { 47 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 48 | { 49 | var uri = new Uri($"{BaseUrl}/{request.ToHttpPostQueryString()}"); 50 | 51 | var queryRequestJson = ApiAiJson.Serialize(request); 52 | 53 | var httpResponseMessage = await httpClient.PostAsync(uri, new StringContent(queryRequestJson, Encoding.UTF8, "application/json")); 54 | 55 | var content = await httpResponseMessage.ToStringContentAsync(); 56 | return ApiAiJson.Deserialize(content); 57 | } 58 | } 59 | 60 | #endregion 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/TtsAppService.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.ApplicationService.Interfaces; 2 | using Api.Ai.Domain.DataTransferObject.Extensions; 3 | using Api.Ai.Domain.DataTransferObject.Request; 4 | using Api.Ai.Domain.DataTransferObject.Response; 5 | using Api.Ai.Domain.Service.Factories; 6 | using System; 7 | using System.Threading.Tasks; 8 | using Api.Ai.ApplicationService.Extensions; 9 | 10 | namespace Api.Ai.ApplicationService 11 | { 12 | public class TtsAppService : ApiAiAppService, ITtsAppService 13 | { 14 | #region Contructor 15 | 16 | public TtsAppService(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory) 17 | : base(serviceProvider, httpClientFactory) 18 | { 19 | } 20 | 21 | #endregion 22 | 23 | #region ITtsAppService members 24 | 25 | public async Task GetTtsAsync(TtsRequest request) 26 | { 27 | using (var httpClient = HttpClientFactory.Create(AccessToken)) 28 | { 29 | httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US"); 30 | 31 | var httpResponseMessage = await httpClient.GetAsync(new Uri($"{BaseUrl}/{request.ToQueryString()}")); 32 | 33 | var content = await httpResponseMessage.ToStreamContentAsync(); 34 | return new TtsResponse(content); 35 | } 36 | } 37 | 38 | #endregion 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/ApplicationService/Api.Ai.ApplicationService/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Api.Ai.Domain.DataTransferObject.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7D744B12-250D-47A6-99F4-5BBDE1FB8AE6} 8 | Library 9 | Properties 10 | Api.Ai.Domain.DataTransferObject 11 | Api.Ai.Domain.DataTransferObject 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | {a7f5e2f0-cfd3-4070-8a37-ec3728587f1e} 81 | Api.Ai.Domain.Enum 82 | 83 | 84 | 85 | 86 | 87 | 88 | 95 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/ApiAiVersion.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject 8 | { 9 | public static class ApiAiVersion 10 | { 11 | public const string Default = "20150910"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Context.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject 8 | { 9 | public class Context 10 | { 11 | public string Name { get; set; } 12 | 13 | public Dictionary Parameters { get; set; } 14 | 15 | public int? Lifespan { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Entity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject 9 | { 10 | /// 11 | /// The entity JSON object contains all information about an entity, including its ID, name, and entries. 12 | /// 13 | public class Entity 14 | { 15 | #region Public Properties 16 | 17 | /// 18 | /// A unique identifier for the entity. 19 | /// 20 | [DefaultValue(null)] 21 | public string Id { get; set; } 22 | 23 | /// 24 | /// The name of the entity. 25 | /// 26 | public string Name { get; set; } 27 | 28 | /// 29 | /// An array of entry objects, which contain reference values and synonyms. 30 | /// 31 | public List Entries { get; set; } 32 | 33 | /// 34 | /// Indicates if the entity is a mapping or an enum type entity. 35 | /// 36 | [DefaultValue(false)] 37 | public bool IsEnum { get; set; } 38 | 39 | /// 40 | /// Indicates if the entity can be automatically expanded. 41 | /// 42 | [DefaultValue(false)] 43 | public bool AutomatedExpansion { get; set; } 44 | 45 | #endregion 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Entry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject 8 | { 9 | public class Entry 10 | { 11 | /// 12 | /// For mapping entities: a canonical name to be used in place of synonyms. 13 | /// 14 | public string Value { get; set; } 15 | 16 | /// 17 | /// Array of strings that can include simple strings (for words and phrases) or references to other entites (with or without aliases). 18 | /// 19 | public List Synonyms { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Extensions/QueryExtension.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Request; 2 | using Api.Ai.Domain.Enum; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.DataTransferObject.Extensions 10 | { 11 | public static class QueryExtension 12 | { 13 | private static string ToQueryString(this QueryRequest queryRequest) 14 | { 15 | string result = $"query?v={queryRequest.V}"; 16 | 17 | if (queryRequest.Query == null) 18 | { 19 | throw new ArgumentNullException("Query string 'query' is null or empty."); 20 | } 21 | 22 | return result; 23 | } 24 | 25 | public static string ToHttpGetQueryString(this QueryRequest queryRequest) 26 | { 27 | string result = ToQueryString(queryRequest); 28 | 29 | result += $"&query={queryRequest.Query.FirstOrDefault()}"; 30 | 31 | if (!string.IsNullOrEmpty(queryRequest.Timezone)) 32 | { 33 | result += $"&timezone={queryRequest.Timezone}"; 34 | } 35 | 36 | result += $"&lang={queryRequest.Lang}"; 37 | 38 | if (queryRequest.Contexts != null && queryRequest.Contexts.Count() > 0) 39 | { 40 | foreach (var context in queryRequest.Contexts) 41 | { 42 | result += $"&contexts={context.Name}"; 43 | } 44 | } 45 | 46 | if (queryRequest.Location != null) 47 | { 48 | if (!string.IsNullOrEmpty(queryRequest.Location.Latitude) && !string.IsNullOrEmpty(queryRequest.Location.Longitude)) 49 | { 50 | result += $"&latitude={queryRequest.Location.Latitude}&longitude={queryRequest.Location.Longitude}"; 51 | } 52 | } 53 | 54 | if (!string.IsNullOrEmpty(queryRequest.SessionId)) 55 | { 56 | result += $"&sessionId={queryRequest.SessionId}"; 57 | } 58 | 59 | return result; 60 | } 61 | 62 | public static string ToHttpPostQueryString(this QueryRequest queryRequest) 63 | { 64 | return ToQueryString(queryRequest); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Extensions/TtsExtension.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Request; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject.Extensions 9 | { 10 | public static class TtsExtension 11 | { 12 | public static string ToQueryString(this TtsRequest ttsRequest) 13 | { 14 | string result = $"/tts?v={ttsRequest.V}"; 15 | 16 | if (string.IsNullOrEmpty(ttsRequest.Text)) 17 | { 18 | throw new ArgumentNullException("Query string 'query' is null or empty."); 19 | } 20 | 21 | return result += $"&text={ttsRequest.Text}"; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Parameters/Date.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Parameters 8 | { 9 | public class Date 10 | { 11 | public long Calendar { get; set; } 12 | public bool Exact { get; set; } 13 | public bool SpecifiedTimezone { get; set; } 14 | public bool Midnight { get; set; } 15 | public string RfcString { get; set; } 16 | public bool OnlyDate { get; set; } 17 | public bool DateTime { get; set; } 18 | public int Hours { get; set; } 19 | public int Minutes { get; set; } 20 | public int DayOfWeek { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Parameters/DatePeriod.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Parameters 8 | { 9 | public class DatePeriod 10 | { 11 | public Date StartDate { get; set; } 12 | public Date EndDate { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Domain.DataTransferObject")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Domain.DataTransferObject")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("7d744b12-250d-47a6-99f4-5bbde1fb8ae6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Request/LocationRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Request 8 | { 9 | public class LocationRequest 10 | { 11 | #region Public Properties 12 | 13 | public string Latitude { get; set; } 14 | public string Longitude { get; set; } 15 | 16 | #endregion 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Request/OriginalRequest.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.Enum; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject.Request 9 | { 10 | public class OriginalRequest 11 | { 12 | /// 13 | /// Request source name. 14 | /// Possible values: "facebook", "kik", "slack", "slack_testbot", "line", 15 | /// "skype", "spark", "telegram", "tropo", "twilio", "twilio-ip", "twitter" 16 | /// 17 | public Source Source { get; set; } 18 | 19 | /// 20 | /// Request data. 21 | /// 22 | public object Data { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Request/QueryRequest.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Request; 2 | using Api.Ai.Domain.Enum; 3 | using Newtonsoft.Json; 4 | using Newtonsoft.Json.Converters; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Api.Ai.Domain.DataTransferObject.Request 12 | { 13 | public class QueryRequest : RequestBase 14 | { 15 | #region Public Properties 16 | 17 | /// 18 | /// The natural language text to be processed. The request can have multiple query parameters. 19 | /// 20 | public string[] Query { get; set; } 21 | 22 | /// 23 | /// The confidence of the corresponding query parameter having been correctly recognized by a 24 | /// speech recognition system. 0 represents no confidence and 1 represents the highest confidence. 25 | /// 26 | public float[] Confidence { get; set; } 27 | 28 | /// 29 | /// A string token up to 36 symbols long, used to identify the client and to manage sessions parameters (including contexts) per client. 30 | /// 31 | public string SessionId { get; set; } 32 | 33 | /// 34 | /// Language tag. 35 | /// 36 | public Language Lang { get; set; } 37 | 38 | /// 39 | /// Array of additional input context objects. 40 | /// 41 | public Context[] Contexts { get; set; } 42 | 43 | /// 44 | /// If true, all current contexts in a session will be reset before the new ones are set. False by default. 45 | /// 46 | public bool ResetContexts { get; set; } 47 | 48 | /// 49 | /// Array of entities that replace developer defined entities for this request only. The entity(ies) need to exist in the developer console 50 | /// 51 | public Entity[] Entities { get; set; } 52 | 53 | /// 54 | /// Time zone from IANA Time Zone Database. 55 | /// 56 | public string Timezone { get; set; } 57 | 58 | /// 59 | /// Latitude and longitude values. 60 | /// 61 | public LocationRequest Location { get; set; } 62 | 63 | /// 64 | /// Full request coming from the integrated platform (Facebook Messenger, Slack, etc.) 65 | /// 66 | public OriginalRequest OriginalRequest { get; set; } 67 | 68 | #endregion 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Request/RequestBase.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.Enum; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.DataTransferObject.Request 10 | { 11 | public class RequestBase 12 | { 13 | #region Private Fields 14 | 15 | private string _v; 16 | 17 | #endregion 18 | 19 | #region Public Properties 20 | 21 | /// 22 | /// Version of the protocol, e.g. v=20150910 23 | /// 24 | [JsonIgnore] 25 | public string V 26 | { 27 | get 28 | { 29 | if (string.IsNullOrEmpty(_v)) 30 | { 31 | _v = ApiAiVersion.Default; 32 | } 33 | 34 | return _v; 35 | } 36 | set 37 | { 38 | _v = value; 39 | } 40 | } 41 | } 42 | 43 | #endregion 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Request/TtsRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Request 8 | { 9 | /// 10 | /// The tts endpoint is used to perform text-to-speech - generate speech (audio file) from text. 11 | /// 12 | public class TtsRequest : RequestBase 13 | { 14 | #region Public Properties 15 | 16 | /// 17 | /// Text 18 | /// 19 | public string Text { get; set; } 20 | 21 | #endregion 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/EntitiesResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response 8 | { 9 | public class EntityResponse 10 | { 11 | #region Public Properties 12 | 13 | public string Id { get; set; } 14 | public string Name { get; set; } 15 | public int Count { get; set; } 16 | public string Preview { get; set; } 17 | 18 | #endregion 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/FulfillmentResponse.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Response.Message; 2 | using Api.Ai.Domain.DataTransferObject.Serializer.Converters; 3 | using Newtonsoft.Json; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Domain.DataTransferObject.Response 11 | { 12 | [Serializable] 13 | public class FulfillmentResponse 14 | { 15 | #region Public Properties 16 | 17 | /// 18 | /// ext to be pronounced to the user / shown on the screen 19 | /// 20 | public string Speech { get; set; } 21 | 22 | /// 23 | /// Array of message objects 24 | /// 25 | [JsonConverter(typeof(MessageCollectionConverter))] 26 | public BaseMessageResponse[] Messages { get; set; } 27 | 28 | #endregion 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/BaseMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Serializer.Converters; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Runtime.Serialization; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 11 | { 12 | [JsonObject] 13 | public abstract class BaseMessageResponse 14 | { 15 | public int Type { get; set; } 16 | 17 | public abstract void SetMessageType(); 18 | 19 | #region Private Methods 20 | 21 | [OnDeserialized] 22 | private void OnDeserialized(StreamingContext context) 23 | { 24 | SetMessageType(); 25 | } 26 | 27 | [OnSerialized] 28 | private void OnSerialized(StreamingContext context) 29 | { 30 | SetMessageType(); 31 | } 32 | 33 | #endregion 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/CardMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 9 | { 10 | [Serializable] 11 | public class CardMessageResponse : BaseMessageResponse 12 | { 13 | #region Constructor 14 | 15 | public CardMessageResponse() 16 | { 17 | SetMessageType(); 18 | } 19 | 20 | #endregion 21 | 22 | #region Public Properties 23 | 24 | /// 25 | /// Card title. 26 | /// 27 | public string Title { get; set; } 28 | 29 | /// 30 | /// Card subtitle. 31 | /// 32 | public string Subtitle { get; set; } 33 | 34 | /// 35 | /// 36 | /// 37 | public string ImageUrl { get; set; } 38 | 39 | /// 40 | /// Array of objects corresponding to card buttons. 41 | /// 42 | public CardMessageResponseButton[] Buttons { get; set; } 43 | 44 | 45 | #endregion 46 | 47 | #region MessageResponse Members 48 | 49 | public override void SetMessageType() 50 | { 51 | this.Type = (int)Enum.Type.Card; 52 | } 53 | 54 | #endregion 55 | } 56 | 57 | /// 58 | /// Card buttons. 59 | /// 60 | public class CardMessageResponseButton 61 | { 62 | /// 63 | /// Button text. 64 | /// 65 | public string Text { get; set; } 66 | 67 | /// 68 | /// A text sent back to API.AI or a URL to open. 69 | /// 70 | public string Postback { get; set; } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/ImageMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 8 | { 9 | [Serializable] 10 | public class ImageMessageResponse : BaseMessageResponse 11 | { 12 | #region Constructor 13 | 14 | public ImageMessageResponse() 15 | { 16 | SetMessageType(); 17 | } 18 | 19 | #endregion 20 | 21 | #region Public Properties 22 | 23 | /// 24 | /// Public URL to the image file. 25 | /// 26 | public string ImageUrl { get; set; } 27 | 28 | #endregion 29 | 30 | #region MessageResponse Members 31 | 32 | public override void SetMessageType() 33 | { 34 | this.Type = (int)Enum.Type.Image; 35 | } 36 | 37 | #endregion 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/PayloadMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 8 | { 9 | /// 10 | /// Custom payload message object 11 | /// 12 | public class PayloadMessageResponse : BaseMessageResponse 13 | { 14 | #region Constructor 15 | 16 | public PayloadMessageResponse() 17 | { 18 | SetMessageType(); 19 | } 20 | 21 | #endregion 22 | 23 | #region Public Properties 24 | 25 | /// 26 | /// Developer defined JSON. It is sent without modifications 27 | /// 28 | public object Payload { get; set; } 29 | 30 | #endregion 31 | 32 | #region BaseMessageResponse Members 33 | 34 | public override void SetMessageType() 35 | { 36 | this.Type = (int)Enum.Type.Payload; 37 | } 38 | 39 | #endregion 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/QuickReplyMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 8 | { 9 | [Serializable] 10 | public class QuickReplyMessageResponse : BaseMessageResponse 11 | { 12 | #region Constructor 13 | 14 | public QuickReplyMessageResponse() 15 | { 16 | SetMessageType(); 17 | } 18 | 19 | #endregion 20 | 21 | #region Public Properties 22 | 23 | /// 24 | /// Quick replies title. 25 | /// 26 | public string Title { get; set; } 27 | 28 | /// 29 | /// Array of strings corresponding to quick replies. 30 | /// 31 | public string[] Replies { get; set; } 32 | 33 | #endregion 34 | 35 | #region MessageResponse Members 36 | 37 | public override void SetMessageType() 38 | { 39 | this.Type = (int)Enum.Type.QuickReply; 40 | } 41 | 42 | #endregion 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/Message/TextMessageResponse.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Serializer.Converters; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Runtime.Serialization; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Domain.DataTransferObject.Response.Message 11 | { 12 | public class TextMessageResponse : BaseMessageResponse 13 | { 14 | #region Constructor 15 | 16 | public TextMessageResponse() 17 | { 18 | SetMessageType(); 19 | } 20 | 21 | #endregion 22 | 23 | #region Public Properties 24 | 25 | /// 26 | /// Agent's text reply. Line breaks are supported for Facebook Messenger, Kik, Slack, and Telegram one-click integrations. 27 | /// 28 | public string Speech { get; set; } 29 | 30 | #endregion 31 | 32 | #region MessageResponse Members 33 | 34 | public override void SetMessageType() 35 | { 36 | this.Type = (int)Enum.Type.Text; 37 | } 38 | 39 | #endregion 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/MetadataResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response 8 | { 9 | public class MetadataResponse 10 | { 11 | #region Public Properties 12 | 13 | /// 14 | /// ID of the intent that produced this result. 15 | /// 16 | public string IntentId { get; set; } 17 | 18 | /// 19 | /// Indicates wheather webhook functionaly is enabled in the triggered intent. 20 | /// 21 | public bool WebhookUsed { get; set; } 22 | 23 | /// 24 | /// Name of the intent that produced this result. 25 | /// 26 | public string IntentName { get; set; } 27 | 28 | #endregion 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/QueryResponse.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Serializer.Converters; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.DataTransferObject.Response 10 | { 11 | [Serializable] 12 | public class QueryResponse : ResponseBase 13 | { 14 | #region Public Properties 15 | 16 | public QueryResult Result { get; set; } 17 | 18 | #endregion 19 | } 20 | 21 | [Serializable] 22 | public class QueryResult 23 | { 24 | #region Public Properties 25 | 26 | /// 27 | /// Source of the answer. Could be "agent" if the response was retrieved from the agent. 28 | /// 29 | public string Source { get; set; } 30 | 31 | /// 32 | /// The query that was used to produce this result. 33 | /// 34 | public string ResolvedQuery { get; set; } 35 | 36 | /// 37 | /// An action to take. 38 | /// 39 | public string Action { get; set; } 40 | 41 | /// 42 | /// true if the triggered intent has required parameters and not all the required parameter values have been collected 43 | /// false if all required parameter values have been collected or if the triggered intent doesn't containt any required parameters 44 | /// 45 | public bool ActionIncomplete { get; set; } 46 | 47 | /// 48 | /// Parameters to be used by the action. 49 | /// 50 | public Dictionary Parameters { get; set; } 51 | 52 | /// 53 | /// Array of context objects with the fields "name", "parameters", "lifespan". 54 | /// 55 | public Context[] Contexts { get; set; } 56 | 57 | /// 58 | /// Data about fulfillment, speech, structured fulfillment data, etc. 59 | /// 60 | public FulfillmentResponse Fulfillment { get; set; } 61 | 62 | /// 63 | /// Matching score for the intent 64 | /// 65 | public float Score { get; set; } 66 | 67 | /// 68 | /// Contains data on intents and contexts. 69 | /// 70 | public MetadataResponse Metadata { get; set; } 71 | 72 | #endregion 73 | 74 | #region Public Methods 75 | 76 | /// 77 | /// Get context by name 78 | /// 79 | /// 80 | /// 81 | public Context GetContextByName(string name) 82 | { 83 | if (this.Contexts == null || this.Contexts.Count() == 0) 84 | { 85 | throw new NullReferenceException("Contexts is null or empty."); 86 | } 87 | 88 | var context = this.Contexts.Where(x => x.Name == name).FirstOrDefault(); 89 | 90 | if (context == null) 91 | { 92 | throw new KeyNotFoundException($"Context '{name}' not found."); 93 | } 94 | 95 | return context; 96 | } 97 | 98 | /// 99 | /// Get parameter value in context (name) by key 100 | /// 101 | /// 102 | /// 103 | /// 104 | public object GetContextParameterValueByNameKey(string name, string key) 105 | { 106 | var context = GetContextByName(name); 107 | 108 | object result = null; 109 | 110 | if (!context.Parameters.TryGetValue(key, out result)) 111 | { 112 | throw new KeyNotFoundException($"Context '{name}' and parameter key '{key}' not found."); 113 | } 114 | 115 | return result; 116 | } 117 | 118 | /// 119 | /// Get parameter value by key 120 | /// 121 | /// 122 | /// 123 | public object GetParameterValueByKey(string key) 124 | { 125 | if (this.Contexts == null || this.Contexts.Count() == 0) 126 | { 127 | throw new NullReferenceException("Contexts is null or empty."); 128 | } 129 | 130 | object result = null; 131 | 132 | foreach (var context in this.Contexts) 133 | { 134 | if (context.Parameters.TryGetValue(key, out result)) 135 | { 136 | return result; 137 | } 138 | } 139 | 140 | throw new KeyNotFoundException($"Parameter '{key}' not found."); 141 | } 142 | 143 | #endregion 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/ResponseBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response 8 | { 9 | public class ResponseBase 10 | { 11 | #region Public Properties 12 | 13 | /// 14 | /// Unique identifier of the result. 15 | /// 16 | public string Id { get; set; } 17 | 18 | /// 19 | /// Date and time of the request in UTC timezone using ISO-8601 format. 20 | /// 21 | public DateTime Timestamp { get; set; } 22 | 23 | /// 24 | /// Contains data on how the request succeeded or failed. 25 | /// 26 | public StatusResponse Status { get; set; } 27 | 28 | /// 29 | /// Session id informed on request. 30 | /// 31 | public string SessionId { get; set; } 32 | 33 | #endregion 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/StatusREsponse.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject.Response 9 | { 10 | public class StatusResponse 11 | { 12 | #region Public Properties 13 | 14 | /// 15 | /// HTTP status code 16 | /// 17 | public int Code { get; set; } 18 | 19 | /// 20 | /// Text description of error, or "success" if no error. 21 | /// 22 | public string ErrorType { get; set; } 23 | 24 | /// 25 | /// D of the error. Optionally returned if the request failed. 26 | /// 27 | public string ErrorId { get; set; } 28 | 29 | /// 30 | /// Text details of the error. Only returned if the request failed. 31 | /// 32 | public string ErrorDetails { get; set; } 33 | 34 | /// 35 | /// Check Code http status is success (200). 36 | /// 37 | [JsonIgnore] 38 | public bool IsSuccessStatusCode 39 | { 40 | get 41 | { 42 | if (Code == 200) 43 | { 44 | return true; 45 | } 46 | 47 | return false; 48 | } 49 | } 50 | 51 | #endregion 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/TtsResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.DataTransferObject.Response 9 | { 10 | public class TtsResponse : IDisposable 11 | { 12 | #region Private Fields 13 | 14 | private readonly byte[] _bytes; 15 | private readonly Stream _stream; 16 | 17 | #endregion 18 | 19 | #region Contructor 20 | 21 | public TtsResponse(Stream stream) 22 | { 23 | if (stream != null && stream.Length > 0) 24 | { 25 | _stream = stream; 26 | _bytes = ReadFully(stream); 27 | } 28 | 29 | } 30 | 31 | #endregion 32 | 33 | #region Public Properties 34 | 35 | public byte[] Bytes { get { return _bytes; } } 36 | 37 | public Stream Stream { get { return _stream; } } 38 | 39 | #endregion 40 | 41 | #region Private Methods 42 | 43 | private byte[] ReadFully(Stream stream) 44 | { 45 | byte[] buffer = new byte[stream.Length]; 46 | using (MemoryStream ms = new MemoryStream()) 47 | { 48 | int read; 49 | while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) 50 | { 51 | ms.Write(buffer, 0, read); 52 | } 53 | return ms.ToArray(); 54 | } 55 | } 56 | 57 | #endregion 58 | 59 | #region Public Methods 60 | 61 | /// 62 | /// Create a file. 63 | /// 64 | /// Path not include filne name. 65 | /// File name 66 | public async Task WriteToFile(string path) 67 | { 68 | if (!string.IsNullOrEmpty(path)) 69 | { 70 | // Determine whether the directory exists. 71 | if (!Directory.Exists(path)) 72 | { 73 | // Try to create the directory. 74 | DirectoryInfo di = Directory.CreateDirectory(path); 75 | } 76 | 77 | if (_bytes != null && _bytes.Count() > 0) 78 | { 79 | var fileName = $"{Guid.NewGuid().ToString()}.wav"; 80 | 81 | using (FileStream fileStream = new FileStream($"{path}\\{fileName}", FileMode.Create)) 82 | { 83 | await fileStream.WriteAsync(_bytes, 0, _bytes.Length); 84 | return fileName; 85 | } 86 | } 87 | else 88 | { 89 | throw new Exception("Write to file error - Byte array is empty."); 90 | } 91 | } 92 | else 93 | { 94 | throw new Exception("Write to file error - Path is null or empty."); 95 | } 96 | 97 | } 98 | 99 | #endregion 100 | 101 | #region IDisposable Members 102 | 103 | public void Dispose() 104 | { 105 | if (_stream != null) 106 | { 107 | _stream.Close(); 108 | } 109 | 110 | GC.SuppressFinalize(this); 111 | } 112 | 113 | #endregion 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Response/WebhookResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.DataTransferObject.Response 8 | { 9 | public class WebhookResponse 10 | { 11 | /// 12 | /// Voice response to the request. 13 | /// 14 | public string Speech { get; set; } 15 | 16 | /// 17 | /// Text displayed on the user device screen. 18 | /// 19 | public string DisplayText { get; set; } 20 | 21 | /// 22 | /// Additional data required for performing the action on the client side. 23 | /// The data is sent to the client in the original form and is not processed by Api.ai. 24 | /// 25 | public Dictionary Data { get; set; } 26 | 27 | /// 28 | /// Array of context objects set after intent completion. 29 | /// 30 | public Context[] ContextOut { get; set; } 31 | 32 | /// 33 | /// Data source 34 | /// 35 | public string Source { get; set; } 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Serializer/ApiAiJson.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using Newtonsoft.Json.Serialization; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Domain.DataTransferObject.Serializer 11 | { 12 | public class ApiAiJson 13 | { 14 | #region Private Fields 15 | 16 | private static JsonSerializerSettings _settings = new JsonSerializerSettings() 17 | { 18 | NullValueHandling = NullValueHandling.Ignore, 19 | ContractResolver = new CamelCasePropertyNamesContractResolver(), 20 | Formatting = Formatting.Indented 21 | 22 | }; 23 | 24 | #endregion 25 | 26 | #region Constructor 27 | 28 | static ApiAiJson() 29 | { 30 | _settings.Converters.Add(new StringEnumConverter()); 31 | } 32 | 33 | #endregion 34 | 35 | #region Public Methods 36 | 37 | public static string Serialize(T t) 38 | { 39 | return JsonConvert.SerializeObject(t, _settings); 40 | } 41 | 42 | public static T Deserialize(string json) 43 | { 44 | return JsonConvert.DeserializeObject(json, _settings); 45 | } 46 | 47 | #endregion 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Serializer/Converters/JsonCreationConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Linq; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.DataTransferObject.Serializer.Converters 10 | { 11 | public abstract class JsonCreationConverter : JsonConverter 12 | { 13 | protected abstract T Create(Type objectType, JObject jObject); 14 | 15 | public override bool CanConvert(Type objectType) 16 | { 17 | return objectType.IsSubclassOf(typeof(T)); 18 | } 19 | 20 | //This method never gets called 21 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 22 | { 23 | var jsonObject = JObject.Load(reader); 24 | var target = Create(objectType, jsonObject); 25 | serializer.Populate(jsonObject.CreateReader(), target); 26 | return target; 27 | 28 | } 29 | 30 | //I just kinda guessed at this code 31 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 32 | { 33 | if (this.CanConvert(value.GetType())) 34 | { 35 | serializer.Serialize(writer, value); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/Serializer/Converters/MessageCollectionConverter.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.DataTransferObject.Response.Message; 2 | using Newtonsoft.Json; 3 | using Newtonsoft.Json.Linq; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using Api.Ai.Domain.DataTransferObject.Serializer; 10 | 11 | namespace Api.Ai.Domain.DataTransferObject.Serializer.Converters 12 | { 13 | public class MessageCollectionConverter : JsonConverter 14 | { 15 | public override bool CanConvert(Type objectType) 16 | { 17 | return objectType == typeof(BaseMessageResponse[]); 18 | } 19 | 20 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 21 | { 22 | BaseMessageResponse[] result = null; 23 | 24 | var jArray = JArray.Load(reader); 25 | 26 | if (jArray != null) 27 | { 28 | result = new BaseMessageResponse[jArray.Count]; 29 | 30 | for (var i = 0; i < jArray.Count; i++) 31 | { 32 | var messageType = (Domain.Enum.Type)System.Enum.Parse(typeof(Domain.Enum.Type), jArray[i]["type"].ToString()); 33 | 34 | switch (messageType) 35 | { 36 | case Domain.Enum.Type.Text: 37 | result[i] = ApiAiJson.Deserialize(jArray[i].ToString()); 38 | break; 39 | 40 | case Domain.Enum.Type.Card: 41 | result[i] = ApiAiJson.Deserialize(jArray[i].ToString()); 42 | break; 43 | 44 | case Domain.Enum.Type.QuickReply: 45 | result[i] = ApiAiJson.Deserialize(jArray[i].ToString()); 46 | break; 47 | 48 | case Domain.Enum.Type.Image: 49 | result[i] = ApiAiJson.Deserialize(jArray[i].ToString()); 50 | break; 51 | 52 | case Domain.Enum.Type.Payload: 53 | result[i] = ApiAiJson.Deserialize(jArray[i].ToString()); 54 | break; 55 | 56 | default: 57 | result[i] = null; 58 | break; 59 | } 60 | } 61 | } 62 | 63 | return result; 64 | } 65 | 66 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 67 | { 68 | serializer.Serialize(writer, (BaseMessageResponse[])value); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.DataTransferObject/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Api.Ai.Domain.Enum.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A7F5E2F0-CFD3-4070-8A37-EC3728587F1E} 8 | Library 9 | Properties 10 | Api.Ai.Domain.Enum 11 | Api.Ai.Domain.Enum 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 65 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Extensions/EnumExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.Enum 10 | { 11 | public static class EnumExtensions 12 | { 13 | public static string DisplayName(this System.Enum source) 14 | { 15 | var fi = source.GetType().GetField(source.ToString()); 16 | 17 | var attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false); 18 | 19 | if (attributes != null && attributes.Length > 0) return attributes[0].Value; 20 | else return source.ToString(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Language.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel; 6 | using System.Linq; 7 | using System.Runtime.Serialization; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Api.Ai.Domain.Enum 12 | { 13 | [JsonConverter(typeof(StringEnumConverter))] 14 | public enum Language 15 | { 16 | [EnumMember(Value = "en")] 17 | English = 0, 18 | 19 | [EnumMember(Value = "pt-br")] 20 | BrazilianPortuguese = 1, 21 | 22 | [EnumMember(Value = "zh-hk")] 23 | ChineseCantonese = 2, 24 | 25 | [EnumMember(Value = "zh-cn")] 26 | ChineseSimplified = 3, 27 | 28 | [EnumMember(Value = "zh-tw")] 29 | ChineseTraditional = 4, 30 | 31 | [EnumMember(Value = "nl")] 32 | Dutch = 5, 33 | 34 | [EnumMember(Value = "fr")] 35 | French = 6, 36 | 37 | [EnumMember(Value = "de")] 38 | German = 7, 39 | 40 | [EnumMember(Value = "it")] 41 | Italian = 8, 42 | 43 | [EnumMember(Value = "ja")] 44 | Japanese = 9, 45 | 46 | [EnumMember(Value = "ko")] 47 | Korean = 10, 48 | 49 | [EnumMember(Value = "pt")] 50 | Portuguese = 11, 51 | 52 | [EnumMember(Value = "ru")] 53 | Russian = 12, 54 | 55 | [EnumMember(Value = "es")] 56 | Spanish = 13, 57 | 58 | [EnumMember(Value = "uk")] 59 | Ukrainian = 14 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Domain.Enum")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Domain.Enum")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a7f5e2f0-cfd3-4070-8a37-ec3728587f1e")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/RequestType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.Enum 8 | { 9 | public enum RequestType 10 | { 11 | Query = 0, 12 | Tts = 1, 13 | Entities = 2, 14 | UserEntities = 3, 15 | Intents = 4 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Source.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Runtime.Serialization; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Domain.Enum 11 | { 12 | [JsonConverter(typeof(StringEnumConverter))] 13 | public enum Source 14 | { 15 | [EnumMember(Value = "facebook")] 16 | Facebook = 0, 17 | 18 | [EnumMember(Value = "kik")] 19 | Kik = 1, 20 | 21 | [EnumMember(Value = "slack")] 22 | Slack = 2, 23 | 24 | [EnumMember(Value = "slack_testbot")] 25 | SlackTestbot = 3, 26 | 27 | [EnumMember(Value = "line")] 28 | Line = 4, 29 | 30 | [EnumMember(Value = "skype")] 31 | Skype = 5, 32 | 33 | [EnumMember(Value = "spark")] 34 | Spark = 6, 35 | 36 | [EnumMember(Value = "telegram")] 37 | Telegram = 7, 38 | 39 | [EnumMember(Value = "tropo")] 40 | Tropo = 8, 41 | 42 | [EnumMember(Value = "twilio")] 43 | Twilio = 9, 44 | 45 | [EnumMember(Value = "twilio-ip")] 46 | TwilioIp = 10, 47 | 48 | [EnumMember(Value = "twitter")] 49 | Twitter = 11 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/Type.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Api.Ai.Domain.Enum 8 | { 9 | /// 10 | /// Message query response type. 11 | /// 12 | public enum Type 13 | { 14 | Text = 0, 15 | Card = 1, 16 | QuickReply = 2, 17 | Image = 3, 18 | Payload = 4 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Enum/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/Api.Ai.Domain.Service.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {0F6F0F2C-1A13-4607-81D8-2449D0E7B6E7} 8 | Library 9 | Properties 10 | Api.Ai.Domain.Service 11 | Api.Ai.Domain.Service 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 62 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/Exceptions/ApiAiException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.Service.Exceptions 9 | { 10 | public class ApiAiException : Exception 11 | { 12 | #region Public Properties 13 | 14 | public HttpStatusCode Code { get; set; } 15 | 16 | #endregion 17 | 18 | #region Constructor 19 | 20 | public ApiAiException(string message) : 21 | base(message) 22 | { 23 | this.Code = HttpStatusCode.InternalServerError; 24 | } 25 | 26 | public ApiAiException(HttpStatusCode code, string message) : 27 | base(message) 28 | { 29 | this.Code = code; 30 | } 31 | 32 | public ApiAiException(int code, string message) : 33 | base(message) 34 | { 35 | this.Code = (HttpStatusCode)code; 36 | } 37 | 38 | #endregion 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/Factories/IHttpClientFactory.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.Service.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Api.Ai.Domain.Service.Factories 9 | { 10 | public interface IHttpClientFactory 11 | { 12 | IHttpClient Create(); 13 | 14 | IHttpClient Create(string accessToken); 15 | 16 | IHttpClient Create(TimeSpan timeout, string accessToken); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/Interfaces/IHttpClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Api.Ai.Domain.Service.Interfaces 10 | { 11 | public interface IHttpClient : IDisposable 12 | { 13 | HttpRequestHeaders DefaultRequestHeaders { get; } 14 | 15 | TimeSpan Timeout { get; set; } 16 | 17 | Task GetAsync(Uri url); 18 | 19 | Task PostAsync(Uri requestUri, HttpContent content); 20 | 21 | Task PutAsync(Uri requestUri, HttpContent content); 22 | 23 | Task DeleteAsync(Uri requestUri); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Domain.Service")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Domain.Service")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0f6f0f2c-1a13-4607-81d8-2449d0e7b6e7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Domain/Api.Ai.Domain.Service/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/Api.Ai.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {BF7434CB-C80D-44A7-9FF0-6AA8AB950B61} 8 | Library 9 | Properties 10 | Api.Ai.Infrastructure 11 | Api.Ai.Infrastructure 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 35 | 36 | 37 | 38 | 39 | ..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 40 | True 41 | 42 | 43 | ..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 44 | True 45 | 46 | 47 | ..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll 48 | True 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | {0f6f0f2c-1a13-4607-81d8-2449d0e7b6e7} 69 | Api.Ai.Domain.Service 70 | 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/Factories/HttpClientFactory.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.Service.Factories; 2 | using Api.Ai.Domain.Service.Interfaces; 3 | using Api.Ai.Infrastructure.Http; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Infrastructure.Factories 11 | { 12 | public class HttpClientFactory : IHttpClientFactory 13 | { 14 | #region Private Fields 15 | 16 | private readonly IServiceProvider _serviceProvider; 17 | 18 | #endregion 19 | 20 | #region Contructor 21 | 22 | public HttpClientFactory(IServiceProvider serviceProvider) 23 | { 24 | _serviceProvider = serviceProvider; 25 | } 26 | 27 | #endregion 28 | 29 | #region IDispatcherFactory Members 30 | 31 | /// 32 | /// Create with default timeout 60s 33 | /// 34 | /// 35 | public IHttpClient Create() 36 | { 37 | return Create(TimeSpan.FromSeconds(60), string.Empty); 38 | } 39 | 40 | public IHttpClient Create(string accessToken) 41 | { 42 | return Create(TimeSpan.FromSeconds(60), accessToken); 43 | } 44 | 45 | public IHttpClient Create(TimeSpan timeout, string accessToken) 46 | { 47 | var result = _serviceProvider.GetService(typeof(ApiAiHttpClient)) as IHttpClient; 48 | 49 | if (result == null) 50 | { 51 | throw new Exception("Unexpected error get service provider ApiAiHttpClient"); 52 | } 53 | 54 | if (!string.IsNullOrEmpty(accessToken)) 55 | { 56 | result.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}"); 57 | } 58 | 59 | result.Timeout = timeout; 60 | 61 | return result; 62 | } 63 | 64 | #endregion 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/Http/ApiAiHttpClient.cs: -------------------------------------------------------------------------------- 1 | using Api.Ai.Domain.Service.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Api.Ai.Infrastructure.Http 11 | { 12 | public class ApiAiHttpClient : IHttpClient 13 | { 14 | #region Private Fields 15 | 16 | private readonly HttpClient _httpClient; 17 | 18 | #endregion 19 | 20 | #region Constructor 21 | 22 | public ApiAiHttpClient(IServiceProvider serviceProvider) 23 | { 24 | _httpClient = new HttpClient(); 25 | } 26 | 27 | #endregion 28 | 29 | #region IHttpClient Members 30 | 31 | public HttpRequestHeaders DefaultRequestHeaders 32 | { 33 | get 34 | { 35 | return _httpClient.DefaultRequestHeaders; 36 | } 37 | } 38 | 39 | public TimeSpan Timeout 40 | { 41 | get 42 | { 43 | return _httpClient.Timeout; 44 | } 45 | set 46 | { 47 | _httpClient.Timeout = value; 48 | } 49 | } 50 | 51 | public Task GetAsync(Uri uri) 52 | { 53 | var httpResponseMessage = _httpClient.GetAsync(uri); 54 | 55 | if (httpResponseMessage == null) 56 | { 57 | throw new Exception("Get async error - Http response message is null."); 58 | } 59 | 60 | return httpResponseMessage; 61 | } 62 | 63 | public Task PostAsync(Uri requestUri, HttpContent content) 64 | { 65 | var httpResponseMessage = _httpClient.PostAsync(requestUri, content); 66 | 67 | if (httpResponseMessage == null) 68 | { 69 | throw new Exception("Post async error - Http response message is null."); 70 | } 71 | 72 | return httpResponseMessage; 73 | } 74 | 75 | public Task PutAsync(Uri requestUri, HttpContent content) 76 | { 77 | var httpResponseMessage = _httpClient.PutAsync(requestUri.AbsoluteUri, content); 78 | 79 | if (httpResponseMessage == null) 80 | { 81 | throw new Exception("Put async error - Http response message is null."); 82 | } 83 | 84 | return httpResponseMessage; 85 | } 86 | 87 | public Task DeleteAsync(Uri requestUri) 88 | { 89 | var httpResponseMessage = _httpClient.DeleteAsync(requestUri); 90 | 91 | if (httpResponseMessage == null) 92 | { 93 | throw new Exception("Delete async error - Http response message is null."); 94 | } 95 | 96 | return httpResponseMessage; 97 | } 98 | 99 | public void Dispose() 100 | { 101 | _httpClient.Dispose(); 102 | } 103 | 104 | #endregion 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Infrastructure")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Infrastructure")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("bf7434cb-c80d-44a7-9ff0-6aa8ab950b61")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/Infrastructure/Api.Ai.Infrastructure/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/Test/Api.Ai.Test.Unit/Api.Ai.Test.Unit.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {0F4FA7C3-3388-4F24-AC1E-A3E440C3C982} 7 | Library 8 | Properties 9 | Api.Ai.Test.Unit 10 | Api.Ai.Test.Unit 11 | v4.6.1 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | {6848edca-4533-4bff-aec9-c8f984b74521} 59 | Api.Ai.ApplicationService 60 | 61 | 62 | {7d744b12-250d-47a6-99f4-5bbde1fb8ae6} 63 | Api.Ai.Domain.DataTransferObject 64 | 65 | 66 | {a7f5e2f0-cfd3-4070-8a37-ec3728587f1e} 67 | Api.Ai.Domain.Enum 68 | 69 | 70 | {0f6f0f2c-1a13-4607-81d8-2449d0e7b6e7} 71 | Api.Ai.Domain.Service 72 | 73 | 74 | {bf7434cb-c80d-44a7-9ff0-6aa8ab950b61} 75 | Api.Ai.Infrastructure 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | False 86 | 87 | 88 | False 89 | 90 | 91 | False 92 | 93 | 94 | False 95 | 96 | 97 | 98 | 99 | 100 | 101 | 108 | -------------------------------------------------------------------------------- /src/Test/Api.Ai.Test.Unit/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Api.Ai.Test.Unit")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Api.Ai.Test.Unit")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0f4fa7c3-3388-4f24-ac1e-a3e440c3c982")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Test/Api.Ai.Test.Unit/SerializerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Api.Ai.Domain.DataTransferObject.Request; 4 | using Api.Ai.Domain.DataTransferObject.Response; 5 | using System.Collections.Generic; 6 | using Api.Ai.Domain.DataTransferObject.Parameters; 7 | using Api.Ai.Domain.DataTransferObject; 8 | using Api.Ai.Domain.DataTransferObject.Response.Message; 9 | using Api.Ai.Domain.DataTransferObject.Serializer; 10 | 11 | namespace Api.Ai.Test.Unit 12 | { 13 | [TestClass] 14 | public class SerializerTest 15 | { 16 | #region Private Methods 17 | 18 | private QueryRequest GetQueryRequest() 19 | { 20 | return new QueryRequest 21 | { 22 | SessionId = "1", 23 | Query = new string[] { "Hello, I want a pizza" }, 24 | Lang = Domain.Enum.Language.English 25 | }; 26 | } 27 | 28 | private QueryResponse GetQueryResponse() 29 | { 30 | var queryResponse = new QueryResponse 31 | { 32 | Id = Guid.NewGuid().ToString(), 33 | SessionId = "1", 34 | Status = new StatusResponse { Code = 200 }, 35 | Timestamp = DateTime.Now, 36 | Result = new QueryResult 37 | { 38 | Fulfillment = new FulfillmentResponse 39 | { 40 | Speech = string.Empty, 41 | Messages = new BaseMessageResponse[3] 42 | { 43 | new TextMessageResponse { Speech = "It's working." }, 44 | new CardMessageResponse { Title = "title", Subtitle = "subtitle", ImageUrl = "http://127.0.0.1" }, 45 | new PayloadMessageResponse {Payload = "{ \"object\": }" } 46 | } 47 | }, 48 | Contexts = new Context[1] 49 | { 50 | new Context 51 | { 52 | Name = "context-1", 53 | Parameters = new Dictionary() 54 | { 55 | { "parameter-key-1", "parameter-valeu-1" }, 56 | { "parameter-key-2", new DatePeriod { EndDate = new Date { Calendar = 1470841200000 }, StartDate = new Date { Calendar = 1470841200000 } } } 57 | } 58 | } 59 | } 60 | } 61 | }; 62 | 63 | return queryResponse; 64 | } 65 | 66 | private WebhookResponse GetWebhookResponse() 67 | { 68 | return new WebhookResponse 69 | { 70 | Speech = "Webhook response test.", 71 | Source = "unit-test" 72 | }; 73 | } 74 | 75 | #endregion 76 | 77 | #region Test Methods 78 | 79 | [TestMethod] 80 | public void Serialize_Deserialize_QueryRequest() 81 | { 82 | var queryRequest = GetQueryRequest(); 83 | 84 | var json = ApiAiJson.Serialize(queryRequest); 85 | 86 | Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"lang\": \"en\"")); 87 | var deserializeQueryRequest = ApiAiJson.Deserialize(json); 88 | 89 | Assert.IsTrue(queryRequest.Query[0] == deserializeQueryRequest.Query[0]); 90 | } 91 | 92 | [TestMethod] 93 | public void Serialize_Deserialize_QueryResponse() 94 | { 95 | var queryResponse = GetQueryResponse(); 96 | 97 | var datePeriod = queryResponse.Result.GetParameterValueByKey("parameter-key-2"); 98 | 99 | var json = ApiAiJson.Serialize(queryResponse); 100 | 101 | Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"code\": 200")); 102 | 103 | var deserializeQueryResponse = ApiAiJson.Deserialize(json); 104 | 105 | json = ApiAiJson.Serialize(deserializeQueryResponse); 106 | 107 | Assert.IsTrue(deserializeQueryResponse.Result.Fulfillment.Messages.Length > 0 && json.Contains("\"title\": \"title\"") 108 | && json.Contains("\"subtitle\": \"subtitle\"") && json.Contains("object")); 109 | 110 | Assert.IsTrue(queryResponse.Id == deserializeQueryResponse.Id); 111 | } 112 | 113 | [TestMethod] 114 | public void Serialize_Deserialize_WebhookResponse() 115 | { 116 | var webhookResponse = GetWebhookResponse(); 117 | 118 | var json = ApiAiJson.Serialize(webhookResponse); 119 | 120 | Assert.IsTrue(!string.IsNullOrWhiteSpace(json) && json.Contains("\"source\": \"unit-test\"")); 121 | 122 | var deserializeWebhookResponse = ApiAiJson.Deserialize(json); 123 | 124 | Assert.IsTrue(webhookResponse.Source == deserializeWebhookResponse.Source); 125 | } 126 | 127 | #endregion 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/Test/Api.Ai.Test.Unit/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------