static async Task Main(string[] args)
        {
            ITextAnalyticsService service = new TextAnalyticsService();

            bool isRunning = true;

            while (isRunning)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write("Type the message to be analyzed: ");
                Console.ForegroundColor = ConsoleColor.White;

                string message = Console.ReadLine();

                if (!string.IsNullOrEmpty(message) && message != "exit")
                {
                    await service.DoSentimentAnalysis(message);

                    Console.WriteLine("Press anything to continue...");
                    Console.ReadLine();
                    Console.Clear();
                }
                else
                {
                    isRunning = false;
                }
            }
        }
Exemple #2
0
        public async Task <IActionResult> Index(string inputText = "")
        {
            if (!string.IsNullOrEmpty(inputText))
            {
                var sentimentScore = await TextAnalyticsService.GetSentimentScore(inputText);

                var keyPhrases = await TextAnalyticsService.GetKeyPhrases(inputText);

                //Cast sentiment score as a percentage
                sentimentScore = Math.Round((sentimentScore * 100), 0);

                var viewModel = new ResultViewModel()
                {
                    SentimentScore = sentimentScore,
                    KeyPhrases     = keyPhrases,
                    OriginalText   = inputText,
                };

                return(View(viewModel));
            }
            else
            {
                return(View());
            }
        }
Exemple #3
0
        public TryWatchDialog(IStatePropertyAccessor <Models.UserData> userDataStateAccessor, IConfiguration configuration)
            : base(nameof(TryWatchDialog))
        {
            UserStateAccessor = userDataStateAccessor ?? throw new ArgumentNullException(nameof(userDataStateAccessor));

            // Cognitive Services
            _textAnalyticsService   = new TextAnalyticsService(configuration["textAnalyticsKey"], configuration["region"]);
            _distanceMatrixService  = new DistanceMatrixService(configuration["bingMapsApiKey"]);
            _faceRecognitionService = new FaceRecognitionService(configuration["faceRecognitionKey"], configuration["region"]);

            // Preset latitud and longitude for testing.
            _origin      = $"{configuration["userLatitude"]},{configuration["userLongitude"]}";
            _destination = $"{configuration["storeLatitude"]},{configuration["storeLongitude"]}";

            // Define Waterfallsteps for the new TryWatch dialog
            var tryWatchWaterfallSteps = new WaterfallStep[]
            {
                SearchClosestStoreStepAsync,
                CheckStoreCalendarStepAsync,
                NamePromptStepAsync,
                BookAppointmentStepAsync,
                SaveSelfieStepAsync,
            };

            AddDialog(new WaterfallDialog(TryWatchWaterfall, tryWatchWaterfallSteps));
            AddDialog(new TextPrompt(ConfirmStore));
            AddDialog(new TextPrompt(SelectStoreSchedule));
            AddDialog(new TextPrompt(NamePrompt));
            AddDialog(new AttachmentPrompt(BookAppointment));
        }
        public async Task <IActionResult> Index(string inputText = "")
        {
            if (!string.IsNullOrEmpty(inputText))
            {
                var sentimentScore = await TextAnalyticsService.GetSentimentScore(inputText);

                var keyPhrases = await TextAnalyticsService.GetKeyPhrases(inputText);

                var keyPhrasesAsString = string.Empty;

                foreach (var keyPhrase in keyPhrases)
                {
                    keyPhrasesAsString += keyPhrase + " ";
                }

                var viewModel = new ResultViewModel()
                {
                    SentimentScore     = sentimentScore,
                    KeyPhrases         = keyPhrases,
                    OriginalText       = inputText,
                    KeyPhrasesAsString = keyPhrasesAsString
                };

                return(View(viewModel));
            }
            else
            {
                return(View());
            }
        }
        private async Task <DialogTurnResult> AskforPhotoStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userData = await BotStateAccessor.GetAsync(stepContext.Context, () => new UserData(), cancellationToken);

            // Get the text from the activity to use to show the correct card
            var text = stepContext.Context.Activity.Text.ToLowerInvariant();
            var isPositiveFeedback = await TextAnalyticsService.GetTextSentimentAsync(text) > 0.5;

            userData.ProductWasFound = isPositiveFeedback;

            if (isPositiveFeedback)
            {
                // We go directly to the next step as we don't need any input from the user
                return(await stepContext.NextAsync());
            }
            else
            {
                return(await stepContext.PromptAsync(
                           AskForImage,
                           new PromptOptions
                {
                    Prompt = MessageFactory.Text("Do you have a photo of a watch you like? In order to help you we will need an image of a simillar watch to search."),
                    RetryPrompt = MessageFactory.Text("I didn't find any watch on the provided image. Please provide an image with a similar watch you are looking for to continue"),
                },
                           cancellationToken));
            }
        }
Exemple #6
0
        public async Task PredictNerBatchAsyncTest(string key, string endpoint, string language, List <string> queries, CliException expectedException)
        {
            if (expectedException == null)
            {
                // act
                ITextAnalyticsService predictionService = new TextAnalyticsService(key, endpoint, language);
                var result = await predictionService.PredictNerBatchAsync(queries);

                // assert
                Assert.NotNull(result);
                Assert.NotEmpty(result);
                foreach (RecognizeEntitiesResult r in result)
                {
                    Assert.NotNull(r.Entities);
                    Assert.NotEmpty(r.Entities);
                    foreach (CategorizedEntity e in r.Entities)
                    {
                        Assert.NotNull(e.Text);
                    }
                }
            }
            else
            {
                await Assert.ThrowsAsync(expectedException.GetType(), async() =>
                {
                    ITextAnalyticsService predictionService = new TextAnalyticsService(key, endpoint, language);
                    await predictionService.PredictNerBatchAsync(queries);
                });
            }
        }
Exemple #7
0
        public async Task PredictSentimentBatchAsyncTest(string key, string endpoint, string language, List <string> queries, CliException expectedException)
        {
            if (expectedException == null)
            {
                // act
                ITextAnalyticsService predictionService = new TextAnalyticsService(key, endpoint, language);
                var result = await predictionService.PredictSentimentBatchAsync(queries);

                // assert
                Assert.NotNull(result);
                Assert.NotEmpty(result);
                foreach (AnalyzeSentimentResult r in result)
                {
                    Assert.NotNull(r.DocumentSentiment);
                    Assert.NotNull(r.DocumentSentiment.ConfidenceScores);
                    Assert.NotNull(r.DocumentSentiment.Sentences);
                    Assert.NotEmpty(r.DocumentSentiment.Sentences);
                }
            }
            else
            {
                await Assert.ThrowsAsync(expectedException.GetType(), async() =>
                {
                    ITextAnalyticsService predictionService = new TextAnalyticsService(key, endpoint, language);
                    await predictionService.PredictSentimentBatchAsync(queries);
                });
            }
        }
        public IWantANewWatchDialog(IStatePropertyAccessor <UserData> botStateAccessor, IConfiguration configuration, BotConfigOptions botConfigOptions)
            : base(nameof(IWantANewWatchDialog))
        {
            BotStateAccessor  = botStateAccessor ?? throw new ArgumentNullException(nameof(botStateAccessor));
            _botConfigOptions = botConfigOptions;

            SiteImagesPath       = configuration["imageHostUrl"];
            TextAnalyticsService = new TextAnalyticsService(configuration["textAnalyticsKey"], configuration["region"]);
            CustomVisionService  = new CustomVisionService(configuration["customVisionKey"], configuration["customVisionProjectId"]);
            ProductService       = new ProductService(configuration);

            // This array defines how the Waterfall will execute.
            var waterfallSteps = new WaterfallStep[]
            {
                CheckWatchesStepAsync,
                AskforPhotoStepAsync,
                SearchWatchesStepAsync,
            };

            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            AddDialog(new WaterfallDialog(SearchWatches, waterfallSteps));
            AddDialog(new TextPrompt(ConfirmWatchFound));
            AddDialog(new AttachmentPrompt(AskForImage, ImageValidatorAsync));
            AddDialog(new TextPrompt(SearchSimilarWatches));
        }
Exemple #9
0
        // Matt Text Analytics Part 7
        public static void CallTextAnalyticsEntityAPI()
        {
            try
            {
                // Get the file name
                Console.WriteLine("Please enter a some text to analyze:");
                var message = Console.ReadLine();

                var document = new MultiLanguageInput()
                {
                    Id       = Guid.NewGuid().ToString(),
                    Language = "en-US",
                    Text     = message
                };
                var documentList = new List <MultiLanguageInput>();
                documentList.Add(document);
                var query  = new TextAnalyticsQuery(Constants.TEXT_ANALYTICS_PREVIEW_URL, Constants.TEXT_ANALYTICS_KEY, documentList.ToArray());
                var result = TextAnalyticsService.callTextAnalyticsEntityAPI(query).Result;
                ExportJSON(JsonConvert.SerializeObject(result));
                Console.WriteLine("\nPress Enter to exit ");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                Console.ReadLine();
                throw;
            }
        }
Exemple #10
0
        private void ContentService_Saving(IContentService sender, SaveEventArgs <IContent> e)
        {
            var textAnalyticsService = new TextAnalyticsService(_textAnalyticsApiKey);


            foreach (IContent content in e.SavedEntities.Where(a => a.ContentType.Alias == "comment"))
            {
                var request = new TextAnalyticsRequestDocument
                {
                    Id   = Guid.NewGuid().ToString(),
                    Text = content.GetValue <string>("text")
                };

                var    analyticsResponse = AsyncHelpers.RunSync(() => textAnalyticsService.TextAnalyticsRequestAsync(request, TextAnalyticsFeature.Languages));
                string isoLanguageCode   = analyticsResponse.DetectedLanguages.First().Iso6391Name;

                var    analyticsSentimentResponse = AsyncHelpers.RunSync(() => textAnalyticsService.TextAnalyticsRequestAsync(request, TextAnalyticsFeature.Sentiment));
                double sentimentScore             = analyticsSentimentResponse.Score;

                var    analyticsKeyPhrasesResponse = AsyncHelpers.RunSync(() => textAnalyticsService.TextAnalyticsRequestAsync(request, TextAnalyticsFeature.KeyPhrases));
                string keyPhrases = string.Join("\n", analyticsKeyPhrasesResponse.KeyPhrases);



                content.SetValue("language", isoLanguageCode);
                content.SetValue("sentiment", Math.Round(sentimentScore, 2));
                content.SetValue("keyPhrases", keyPhrases);
            }
        }
        public void ProcessServiceDeskRequest(int id)
        {
            ServiceDeskRequests      serviceDeskItem = new ServiceDeskRequests();
            DepartmentManagerService manageTicket    = new DepartmentManagerService();
            Ticket ticket = serviceDeskItem.GetTicket(id);
            IEnumerable <string> listKeyPhrases = new TextAnalyticsService().GetKeyPhrases(ticket.Body);

            manageTicket.DistributeTicket(listKeyPhrases, ticket);
        }
        public DialogAnalyzerClient(string computerVisionApiRegion, string computerVisionSubscriptionKey,
                                    string textAnalyticsApiRegion, string textAnalyticsSubscriptionKey)
        {
            // Computer Vision Service
            this.ComputerVisionService = new ComputerVisionService(computerVisionApiRegion, computerVisionSubscriptionKey);

            // Text Analytics Service
            this.TextAnalyticsService = new TextAnalyticsService(textAnalyticsApiRegion, textAnalyticsSubscriptionKey);
        }
Exemple #13
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            Loading(true);
            var tweetAnalytics = await TextAnalyticsService.AnalyzeTweet(tweet);

            Loading(false);
            BindingContext = tweetAnalytics;
        }
Exemple #14
0
        private async Task Analyze()
        {
            IsBusy = true;

            var newReviews = await TextAnalyticsService.AnalyzeText(Reviews.ToList());

            if (newReviews != null)
            {
                Reviews = new ObservableCollection <Review>(newReviews.OrderBy(x => x.Id));
            }

            IsBusy = false;
        }
        private async void AnalyzeButton_Clicked(object sender, EventArgs e)
        {
            Loading(true);

            var sentiment = await TextAnalyticsService.AnalyzeText(MessageEntry.Text);

            if (sentiment != null)
            {
                ScoreLabel.Text      = sentiment.score.ToString("N4");
                ScoreLabel.TextColor = SentimentColor.Retrieve(sentiment.score);
            }

            Loading(false);
        }
Exemple #16
0
        private async Task ProcessSentimentAnalysis(IDialogContext context, LuisResult luisResult)
        {
            var result = await TextAnalyticsService.AnalyseSentiment(luisResult.Query);

            if (result.Score.Value > 0.7)
            {
                await context.PostAsync("Merci d'apprecié nos services. Nous travaillons dur pour vous offrir un service de qualité");

                context.Wait(MessageReceived);
            }
            else
            {
                var feedbackForm = new FormDialog <FeedbackForm>(new FeedbackForm(), FeedbackForm.BuildForm, FormOptions.PromptInStart);
                context.Call <FeedbackForm>(feedbackForm, ResumeAfterDialog);
            }
        }
Exemple #17
0
        public async Task SentimentAsyncResult()
        {
            var httpResult = new HttpOperationResponse <SentimentBatchResult>();

            httpResult.Body = new SentimentBatchResult(new List <SentimentBatchResultItem>(new List <SentimentBatchResultItem>()
            {
                new SentimentBatchResultItem((double?)1)
            }), null);
            clientMock.Setup(s => s.SentimentWithHttpMessagesAsync(It.IsAny <MultiLanguageBatchInput>(), null,
                                                                   CancellationToken.None)).ReturnsAsync(httpResult);
            TextAnalyticsService textAnalyticsService = new TextAnalyticsService(clientMock.Object, configurationMock.Object, loggerMock.Object);
            var result = await textAnalyticsService.SentimentAsync(It.IsAny <string>());

            clientMock.Verify(s => s.SentimentWithHttpMessagesAsync(It.IsAny <MultiLanguageBatchInput>(), null,
                                                                    CancellationToken.None), Times.Once);
            Assert.IsType <double>(result);
            Assert.Equal(1, result);
        }
Exemple #18
0
        // Method that gets the Cloud service provider response form user

        public virtual async Task getCloudProvider(IDialogContext context, IAwaitable <CloudServiceProvider> cloudProvider)
        {
            var response = await cloudProvider;

            VirtualCloudProvider = response.ToString();
            await context.PostAsync(String.Format("Your request for virtual machine creation is under progress.We will update you via Email."));

            //"Your Virtual Mchine {0} is ready to run on {1} and supports {2} platform.", VirtualName, VirtualCloudProvider, VirtualOSName ));
            var sentence  = response;
            var sentiment = await TextAnalyticsService.DetermineSentimentAsync(sentence.ToString());

            await context.PostAsync($"You rated our service as: {Math.Round(sentiment * 10, 1)}/10");

            if (sentiment < 0.5)
            {
                PromptDialog.Confirm(context, ResumeAfterFeedbackClarification, "I see it wasn't perfect, can we contact you about this?");
            }
            context.Done(this);
        }
Exemple #19
0
        public async Task EntitiesAsyncResult()
        {
            var httpResult = new HttpOperationResponse <EntitiesBatchResult>();

            httpResult.Body = new EntitiesBatchResult(new List <EntitiesBatchResultItem>(new List <EntitiesBatchResultItem>()
            {
                new EntitiesBatchResultItem(null, new List <EntityRecord>()
                {
                    new EntityRecord("name1"), new EntityRecord("name2")
                })
            }), null);
            clientMock.Setup(s => s.EntitiesWithHttpMessagesAsync(It.IsAny <MultiLanguageBatchInput>(), null,
                                                                  CancellationToken.None)).ReturnsAsync(httpResult);
            TextAnalyticsService textAnalyticsService = new TextAnalyticsService(clientMock.Object, configurationMock.Object, loggerMock.Object);
            var result = await textAnalyticsService.EntitiesAsync(It.IsAny <string>());

            clientMock.Verify(s => s.EntitiesWithHttpMessagesAsync(It.IsAny <MultiLanguageBatchInput>(), null,
                                                                   CancellationToken.None), Times.Once);
            Assert.IsType <List <string> >(result);
            Assert.Equal("name1", result[0]);
            Assert.Equal("name2", result[1]);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                var result = await TextAnalyticsService.AnalyseSentiment(activity.Text);

                var reply = activity.CreateReply();

                reply.Text  = "Votre langue est : " + result.LanguageName + "\n\n";
                reply.Text += "Les mots clés trouvés sont : ";

                foreach (var item in result.KeyPhrases)
                {
                    reply.Text += item + " ";
                }

                if (result.Score.Value > 0.5)
                {
                    reply.Text += "\n\n Vous semblez heureux. Votre score est de : " + result.Score.Value;
                }
                else
                {
                    reply.Text += "\n\n Vous ne semblez pas heureux. Votre score est de : " + result.Score.Value;
                }

                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                await HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
 public TextAnalyticsController(TextAnalyticsService textAnalytics)
 {
     _textAnalytics = textAnalytics;
 }
        // Method not been used in the class

        /*private async Task <double> getSentimentScore(string DocumentText)
         * {
         *  string queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
         *  HttpClient client = new HttpClient()
         *  {
         *      DefaultRequestHeaders =
         *      {
         *          {
         *             "Ocp-Apim-Subscription-Key",
         *             ""
         *          },
         *
         *          {
         *              "Accept",
         *              "application/json"
         *          }
         *      }
         *  };
         *
         *  var textInput = new BatchInput
         *  {
         *      documents = new List<DocumentInput>
         *      {
         *          new DocumentInput
         *          {
         *              Id = 1,
         *              Text = DocumentText,
         *          }
         *      }
         *  };
         *
         *  var jsonInput = JsonConvert.SerializeObject(textInput);
         *  HttpResponseMessage postMessage;
         *  BatchResult response;
         *  try
         *  {
         *      postMessage = await client.PostAsync(queryUri, new StringContent(jsonInput, Encoding.UTF8, "application/json"));
         *      response = JsonConvert.DeserializeObject<BatchResult>(await postMessage.Content.ReadAsStringAsync());
         *  }
         *  catch(Exception e)
         *  {
         *      return 0.0;
         *  }
         *  return response?.documents[0]?.score ?? 0.0;
         * }*/

        /**
         * Method tonhandle the interaction with the HP Service Manager - 9.0
         **/

        // method not used it is defined in the Ticket Model

        /**
         * Method to calculate the user sentiment score
         **/

        private async Task getUserSentiment(IDialogContext context, IAwaitable <TicketModel> result)
        {
            var sentence = await result;
            // string sentenceString = sentence.DatabaseName + "-" + sentence.MiddlewareName + "-" + sentence.ServerName;
            string sentenceString = sentence.Desc + "-" + sentence.DBName + "-" + sentence.ServerName + "-" + sentence.MiddlewareName;
            //string sentenceString = sentence.Desc;

            /**
             * To call the GetQnAMakerResponse to get the responses to the user queries from QnA Maker KB
             * The QnA maker sends the appropriate response to the user queries
             **/

            await context.PostAsync("Let me search my database for a solution to your problem");

            try
            {
                var activity = (Activity)context.MakeMessage();
                activity.Text = sentenceString;

                /**
                 * Call to the sentiment analytics api
                 **/

                var sentiment = await TextAnalyticsService.DetermineSentimentAsync(sentence.ToString());

                var sentimentScore = Math.Round(sentiment * 100, 1) / 10;

                /**
                 * Query to check the user issue in the QnA maker knowledge base
                 **/

                var subscriptionKey = ConfigurationManager.AppSettings["QnaSubscriptionkey"];
                var knowledgeBaseId = ConfigurationManager.AppSettings["QnaKnowledgebaseId"];

                var responseQuery = new QnAMakerDailog.QnAMakerDialog().GetQnAMakerResponse(sentenceString, subscriptionKey, knowledgeBaseId);

                var responseAnswers = responseQuery.answers.FirstOrDefault();

                /**
                 * If the solution to the issue is found in the Kb then send the result to the user
                 **/

                if (responseAnswers != null && responseAnswers.score >= double.Parse(ConfigurationManager.AppSettings["QnAScore"]))
                {
                    await context.PostAsync(responseAnswers.answer);
                }

                /**
                 * If no solution is found then the user response from TicketModel is sent to the Dtabase APRDB and stored in dbo.BotDetails Table
                 **/

                else
                {
                    await context.PostAsync("Could not find a solution to you problem . I have raised a ticket for it, revert to you as soon as we get a solution for it");

                    try
                    {
                        string connectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                        /**
                         * Establish the connection with the SQL database
                         **/

                        SqlConnection connection = new SqlConnection(connectionEstablish);

                        /**
                         * Connection to the DB being opened
                         **/

                        connection.Open();
                        if (connection.State == System.Data.ConnectionState.Open)
                        {
                            Console.WriteLine("Connection Success");

                            /**
                             * SQL command to insert data into the table dbo.BotDetails
                             **/

                            if (sentence.Contact == null)
                            {
                                sentence.Contact = "None";
                            }

                            else if (sentence.PhoneContact == null)
                            {
                                sentence.PhoneContact = "None";
                            }

                            else
                            {
                                Console.WriteLine("Some error occured");
                            }

                            SqlCommand insertCommand = new SqlCommand(@"INSERT INTO dbo.BotDetails (TokenDescription, ServerDetails, MiddlewareDetails, DatabaseDetails, TokenDetails,
                                       SentimentScore, UserName, EmailId, ContactNo) VALUES (@TokenDescription, @ServerDetails, @MiddlewareDetails, @DatabaseDetails, @TokenDetails, @SentimentScore,
                                       @UserName, @EmailId, @ContactNo)", connection);

                            /**
                             * Commands to insert the user response to the database
                             **/

                            insertCommand.Parameters.Add(new SqlParameter("TokenDescription", sentence.Desc));
                            insertCommand.Parameters.Add(new SqlParameter("ServerDetails", sentence.ServerName));
                            insertCommand.Parameters.Add(new SqlParameter("MiddlewareDetails", sentence.MiddlewareName));
                            insertCommand.Parameters.Add(new SqlParameter("DatabaseDetails", sentence.DBName));
                            insertCommand.Parameters.Add(new SqlParameter("TokenDetails", System.DateTimeOffset.Now));
                            insertCommand.Parameters.Add(new SqlParameter("SentimentScore", sentimentScore));
                            insertCommand.Parameters.Add(new SqlParameter("UserName", sentence.Name));
                            insertCommand.Parameters.Add(new SqlParameter("EmailId", sentence.Contact));
                            insertCommand.Parameters.Add(new SqlParameter("ContactNo", sentence.PhoneContact));

                            var DBresult = insertCommand.ExecuteNonQuery();
                            if (DBresult > 0)
                            {
                                connection.Close();

                                string ReconnectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                                SqlConnection conn = new SqlConnection(ReconnectionEstablish);

                                conn.Open();

                                var selectTicketId = "Select Id from dbo.BotDetails WHERE UserName = @UserName";

                                SqlCommand selectCommand = new SqlCommand(selectTicketId, conn);

                                selectCommand.Parameters.AddWithValue("@UserName", sentence.Name);

                                using (SqlDataReader queryReader = selectCommand.ExecuteReader())
                                {
                                    while (queryReader.Read())
                                    {
                                        String retrieveId = queryReader.GetInt32(0).ToString();
                                        //await context.PostAsync("Your ticket has been raised successfully, " + retrieveId + " your token id for the raised ticket");
                                    }
                                }
                            }

                            else
                            {
                                await context.PostAsync("Some problem occured, Please try again after sometime");
                            }

                            /**
                             * Close the existing connection to the DB
                             **/

                            connection.Close();
                        }
                        else
                        {
                            /**
                             * Checks wether the connection is established or not
                             **/
                            Console.WriteLine("Not connected");
                        }

                        /**
                         * Snow connection code
                         **/
                        string DetailDescription = sentence.Desc + " the services are running on server " + sentence.ServerName + ", using " + sentence.DBName + " database and the" + sentence.MiddlewareName + " service";
                        String incidentNo        = string.Empty;
                        incidentNo = SnowLogger.CreateIncidentServiceNow(sentence.Desc, sentence.Contact, DetailDescription, sentence.CategoryName);
                        Console.WriteLine(incidentNo);
                        await context.PostAsync("Your ticket has been raised successfully, " + incidentNo + " your token id for the raised ticket");

                        await context.PostAsync("Please keep the note of above token number. as it would be used for future references");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                    context.Done(this);
                }

                /**
                 * Method to check the user sentiment and report it to the user
                 */

                await context.PostAsync($"You rated our service as: {Math.Round(sentiment * 10, 1)}/10");

                if (sentiment <= 0.5)
                {
                    PromptDialog.Confirm(context, ResumeAfterFeedbackClarification, "I see it wasn't perfect, can we contact you about this?");
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static IForm <TicketModel> BuildForm()
        {
            //Form flow builder being called

            OnCompletionAsyncDelegate <TicketModel> ConnectionRequest = async(context, state) =>
            {
                string sentenceString = state.Desc + "-" + state.DBName + "-" + state.ServerName + "-" + state.MiddlewareName;

                /**
                 * To call the GetQnAMakerResponse to get the responses to the user queries from QnA Maker KB
                 * The QnA maker sends the appropriate response to the user queries
                 **/

                await context.PostAsync("Let me search my database for a solution to your problem");

                try
                {
                    var activity = (Activity)context.MakeMessage();
                    activity.Text = sentenceString;

                    /**
                     * Call to the sentiment analytics api
                     **/

                    var sentiment = await TextAnalyticsService.DetermineSentimentAsync(sentenceString.ToString());

                    var sentimentScore = Math.Round(sentiment * 100, 1) / 10;

                    /**
                     * Query to check the user issue in the QnA maker knowledge base
                     **/

                    var subscriptionKey = ConfigurationManager.AppSettings["QnaSubscriptionkey"];
                    var knowledgeBaseId = ConfigurationManager.AppSettings["QnaKnowledgebaseId"];

                    var responseQuery = new QnAMakerDailog.QnAMakerDialog().GetQnAMakerResponse(sentenceString, subscriptionKey, knowledgeBaseId);

                    var responseAnswers = responseQuery.answers.FirstOrDefault();

                    /**
                     * If the solution to the issue is found in the Kb then send the result to the user
                     **/

                    if (responseAnswers != null && responseAnswers.score >= double.Parse(ConfigurationManager.AppSettings["QnAScore"]))
                    {
                        await context.PostAsync(responseAnswers.answer);
                    }

                    /**
                     * If no solution is found then the user response from TicketModel is sent to the Dtabase APRDB and stored in dbo.BotDetails Table
                     **/

                    else
                    {
                        await context.PostAsync("Could not find a solution to you problem . I have raised a ticket for it, revert to you as soon as we get a solution for it");

                        try
                        {
                            string connectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                            /**
                             * Establish the connection with the SQL database
                             **/

                            SqlConnection connection = new SqlConnection(connectionEstablish);

                            /**
                             * Connection to the DB being opened
                             **/

                            connection.Open();
                            if (connection.State == System.Data.ConnectionState.Open)
                            {
                                Console.WriteLine("Connection Success");

                                /**
                                 * SQL command to insert data into the table dbo.BotDetails
                                 **/

                                SqlCommand insertCommand = new SqlCommand(@"INSERT INTO dbo.BotDetails (TokenDescription, ServerDetails, MiddlewareDetails, DatabaseDetails, TokenDetails,
                                       SentimentScore, UserName, EmailId, ContactNo) VALUES (@TokenDescription, @ServerDetails, @MiddlewareDetails, @DatabaseDetails, @TokenDetails, @SentimentScore,
                                       @UserName, @EmailId, @ContactNo)", connection);

                                if (state.PhoneContact == null)
                                {
                                    state.PhoneContact = "0";
                                }
                                else
                                {
                                    state.Contact = "None";
                                }

                                /**
                                 * Commands to insert the user response to the database
                                 **/

                                insertCommand.Parameters.Add(new SqlParameter("TokenDescription", state.Desc));
                                insertCommand.Parameters.Add(new SqlParameter("ServerDetails", state.ServerName));
                                insertCommand.Parameters.Add(new SqlParameter("MiddlewareDetails", state.MiddlewareName));
                                insertCommand.Parameters.Add(new SqlParameter("DatabaseDetails", state.DBName));
                                insertCommand.Parameters.Add(new SqlParameter("TokenDetails", System.DateTimeOffset.Now));
                                insertCommand.Parameters.Add(new SqlParameter("SentimentScore", sentimentScore));
                                insertCommand.Parameters.Add(new SqlParameter("UserName", state.Name));
                                insertCommand.Parameters.Add(new SqlParameter("EmailId", state.Contact));
                                insertCommand.Parameters.Add(new SqlParameter("ContactNo", state.PhoneContact));

                                var DBresult = insertCommand.ExecuteNonQuery();
                                if (DBresult > 0)
                                {
                                    connection.Close();

                                    string ReconnectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                                    SqlConnection conn = new SqlConnection(ReconnectionEstablish);

                                    conn.Open();

                                    var selectTicketId = "Select Id from dbo.BotDetails WHERE UserName = @UserName";

                                    SqlCommand selectCommand = new SqlCommand(selectTicketId, conn);

                                    selectCommand.Parameters.AddWithValue("@UserName", state.Name);

                                    using (SqlDataReader queryReader = selectCommand.ExecuteReader())
                                    {
                                        while (queryReader.Read())
                                        {
                                            String retrieveId = queryReader.GetInt32(0).ToString();
                                            //await context.PostAsync("Your ticket has been raised successfully, " + retrieveId + " your token id for the raised ticket");
                                        }
                                    }
                                }

                                else
                                {
                                    await context.PostAsync("Some problem occured, Please try again after sometime");
                                }

                                /**
                                 * Close the existing connection to the DB
                                 **/

                                connection.Close();
                            }
                            else
                            {
                                /**
                                 * Checks wether the connection is established or not
                                 **/
                                Console.WriteLine("Not connected");
                            }

                            /**
                             * Snow connection code
                             **/
                            string DetailDescription = state.Desc + " the services are running on server " + state.ServerName + ", using " + state.DBName + " database and the" + state.MiddlewareName + " service";
                            String incidentNo        = string.Empty;
                            string contactOption;

                            /*
                             * If else condition to catch the contact option
                             */
                            if (state.ContactType == ContactTypeOptions.Email)
                            {
                                contactOption = "Email";
                            }

                            else
                            {
                                contactOption = "Phone";
                            }

                            incidentNo = SnowLogger.CreateIncidentServiceNow(state.Desc, contactOption, DetailDescription, state.CategoryName);
                            Console.WriteLine(incidentNo);
                            await context.PostAsync("Your ticket has been raised successfully, " + incidentNo + " your token id for the raised ticket");

                            await context.PostAsync("Please keep the note of above token number. as it would be used for future references");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }

                    /**
                     * Method to check the user sentiment and report it to the user
                     */

                    /*await context.PostAsync($"You rated our service as: {Math.Round(sentiment * 10, 1)}/10");
                     *
                     * if (sentiment <= 0.5)
                     * {
                     *  PromptDialog.Confirm(context, ResumeAfterFeedbackClarification, "I see it wasn't perfect, can we contact you about this?");
                     * }*/
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            };

            return(new FormBuilder <TicketModel>()
                   .Field(nameof(Name), validate: ValidateNameInfo)
                   .Field(nameof(Desc))
                   .Field(nameof(ServerName) /*validate: ValidateServerInfo*/)
                   .Field(nameof(MiddlewareName), validate: ValidateMiddlewareInfo)
                   .Field(nameof(DBName), validate: ValidateDatabaseInfo)
                   .Field(nameof(CategoryName))
                   //.Field(nameof(Priority))
                   .Field(nameof(ContactType))
                   .Field(nameof(Contact), (s) => s.ContactType == ContactTypeOptions.Email, validate: ValidateContactInformation)
                   .Field(nameof(PhoneContact), (s) => s.ContactType == ContactTypeOptions.Phone, validate: ValidatePhoneContact)
                   .AddRemainingFields()
                   .Message("According to the responses entered by you I have generated a statement for you that showscase you problem : " +
                            "{Desc} running on server {ServerName}, using {DBName} database and the {MiddlewareName} services used by you.")
                   //"Please enter Yes if this successfully describe your problem.")
                   .OnCompletion(ConnectionRequest)
                   .Build());
        }