Beispiel #1
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;
            }
        }
        /// <summary>
        /// Button event. Creates all the inputs from the excel data
        /// from each selected column and extract data based on the selected actions
        /// then displays the 'Generate form'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecuteBtn_Click(object sender, EventArgs e)
        {
            ColumnIndexes.Clear();

            if (relevantLb.Items.Count == 0)
            {
                MessageBox.Show("You haven't selected any columns that are relevant", "Error");
                return;
            }

            // Adds all the columns selected into a list
            for (int i = 0; i < relevantLb.Items.Count; i++)
            {
                ColumnIndexes.Add(GetColumnIndex(relevantLb.Items[i].ToString()));
            }

            // Objects
            TextAnalyticClient textAnalysisClient = new TextAnalyticClient();

            // Lists
            List <MultiLanguageInput> MultiInput = new List <MultiLanguageInput>();
            List <Input> Inputs = new List <Input>();

            // Variables
            int count = 0;

            // Loop through all rows in the selected columns and extract data into a 'Input'
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                for (int i = 0; i < ColumnIndexes.Count; i++)
                {
                    if (row.Cells[ColumnIndexes[i]].Value != null)
                    {
                        count++;
                        Input Input = new Input
                        {
                            Id   = Convert.ToString(count),
                            Text = Convert.ToString(row.Cells[ColumnIndexes[i]].Value)
                        };
                        Inputs.Add(Input);
                    }
                }
            }

            // Converts from Input to MultiInput
            for (int i = 0; i < Inputs.Count; i++)
            {
                MultiLanguageInput Input = new MultiLanguageInput
                {
                    Language = "En",
                    Id       = Inputs[i].Id,
                    Text     = Inputs[i].Text
                };
                MultiInput.Add(Input);
            }

            Generate GenerateFrm = new Generate(SelectedActions, Inputs, MultiInput);

            GenerateFrm.ShowDialog();
        }
Beispiel #3
0
    private List <MultiLanguageInput> ConstructMultiLanguageInputList(long mlIdentifierValue)
    {
        List <MultiLanguageInput> tempMLIList = new List <MultiLanguageInput>();
        MultiLanguageInput        mli         = null;
        SQLParametersList         paramsList  = new SQLParametersList();
        string query = "SELECT L.LanguageID, L.Name, L.MSNetCode, L.JavaLocaleCode, L.PhraseTerm, L.RightToLeftText, T." + MLColumnName + " AS Translation " +
                       " FROM Languages AS L LEFT JOIN " + MLTableName + " AS T ON T.LanguageID=L.LanguageID AND T." + MLITranslationColumn + "=@MLIdentifierValue " +
                       " WHERE L.LanguageID in (SELECT TLV.LanguageID FROM TransLanguagesCF_UE AS TLV) " +
                       " ORDER BY CASE WHEN L.LanguageID=1 THEN 1 ELSE 2 END, L.LanguageID;";

        paramsList.Add("@MLIdentifierValue", System.Data.SqlDbType.BigInt).Value = mlIdentifierValue;
        DataTable dt = dbAccess.ExecuteQuery(DataBases.LogixRT, System.Data.CommandType.Text, query, paramsList);

        foreach (DataRow row in dt.Rows)
        {
            mli            = new MultiLanguageInput();
            mli.LanguageID = Convert.ToInt32(row["LanguageID"]);
            if (mli.LanguageID == CustomerFacingLangID)
            {
                mli.Translation = MLDefaultLanguageStandardValue;
            }
            else
            {
                mli.Translation = row["Translation"].ToString();
            }
            mli.Name            = (this.Page as AuthenticatedUI).PhraseLib.Lookup(row["PhraseTerm"].ToString(), defaultLanguageId);
            mli.MSNetCode       = row["MSNetCode"].ToString();
            mli.JavaLocaleCode  = row["JavaLocaleCode"].ToString();
            mli.PhraseTerm      = row["PhraseTerm"].ToString();
            mli.RightToLeftText = row["RightToLeftText"].ToString();
            mli.IdentifierValue = mlIdentifierValue;
            tempMLIList.Add(mli);
        }
        return(tempMLIList);
    }
Beispiel #4
0
        private IEnumerable <MultiLanguageInput> SplitFiveHundredChars(string input)
        {
            var inputs = new List <MultiLanguageInput>();

            if (string.IsNullOrEmpty(input))
            {
                return(inputs);
            }

            var id = 0;

            for (var i = 0; i < input.Length; i += _splitTextLength)
            {
                var multiLanguageInput = new MultiLanguageInput
                {
                    Id       = id.ToString(CultureInfo.InvariantCulture),
                    Language = _config.TextAnalyticsLanguage
                };

                if ((i + _splitTextLength) < input.Length)
                {
                    multiLanguageInput.Text = input.Substring(i, Math.Min(500, input.Length - i));
                    id++;
                }
                else
                {
                    multiLanguageInput.Text = input;
                }

                inputs.Add(multiLanguageInput);
            }

            return(inputs);
        }
 public static Input ConvertToRegularInput(this MultiLanguageInput multiLanguageInput)
 {
     return(new Input {
         Id = multiLanguageInput.Id,
         Text = multiLanguageInput.Text
     });
 }
Beispiel #6
0
        private List <MultiLanguageInput> FetchCommentsFromDB(SqlConnection connection)
        {
            List <MultiLanguageInput> comments = new List <MultiLanguageInput>();

            try
            {
                connection.Open();
                using (var fetchComments = new SqlCommand("SELECT [AP_summary] AS [Text], [Ap_ApId] AS [ID] FROM [dbo].[IM_Appointments] WHERE [AP_summary] IS NOT NULL", connection))
                {
                    using (var commentReader = fetchComments.ExecuteReader())
                    {
                        while (commentReader.Read())
                        {
                            var comment = new MultiLanguageInput()
                            {
                                Id   = commentReader["ID"].ToString(),
                                Text = commentReader["Text"].ToString()
                            };
                            comments.Add(comment);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Couldn't read from DB");
                Console.WriteLine(ex.Message);
            }
            finally
            {
                connection.Close();
            }

            return(comments);
        }
Beispiel #7
0
    private void repMLIInputs_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //Get the translations from the multilanguage usercontrol
        if (e.Item.DataItem != null)
        {
            MultiLanguageInput    mli       = (MultiLanguageInput)e.Item.DataItem;
            CouponTierTranslation tierTrans = new CouponTierTranslation();

            tierTrans.LanguageId         = mli.LanguageID;
            tierTrans.CouponTierID       = mli.IdentifierValue.ConvertToInt32();
            tierTrans.DeliverableMessage = mli.Translation.Trim();
            tierTransData.Add(tierTrans);
        }
    }
Beispiel #8
0
        public static async Task <SentimentResult> AnalyzeWords(string words)
        {
            SentimentResult sentimentResult = new SentimentResult();

            try
            {
                var sentimentInput = new MultiLanguageInput(text: words, id: "1");

                // First find out the input language
                var detectLanguageInput = new Input(id: "1", text: words);
                var languageResult      = await client.DetectLanguageAsync(new BatchInput(new List <Input> {
                    detectLanguageInput
                }), numberOfLanguagesToDetect : 1);

                if (languageResult.Errors.Count > 0)
                {
                    return(null);
                }

                sentimentResult.DetectedLanguage = languageResult.Documents.FirstOrDefault().DetectedLanguages.FirstOrDefault().Iso6391Name;

                // Setup for the sentiment
                sentimentInput.Language = sentimentResult.DetectedLanguage;
                var mlbi = new MultiLanguageBatchInput(new List <MultiLanguageInput>()
                {
                    sentimentInput
                });

                // Find the sentiment!
                var sentimentResultCall = await client.SentimentAsync(mlbi);

                if (sentimentResultCall.Errors.Count > 0)
                {
                    return(null);
                }

                sentimentResult.SentimentAnalysis = sentimentResultCall.Documents.FirstOrDefault().Score ?? 0;

                sentimentResult.ScoreResult();

                return(sentimentResult);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(sentimentResult);
        }
        public async Task <double?> AnalyzeSentiment(string input)
        {
            var client = new TextAnalyticsAPI();

            client.AzureRegion     = AzureRegions.Westus;
            client.SubscriptionKey = "7003dfb3f5484db4829a98c046cef71b";
            var langInput  = new MultiLanguageInput("en", "1", input);
            var batchInput = new MultiLanguageBatchInput(new List <MultiLanguageInput> {
                langInput
            });
            var sentiment = await client.SentimentAsync(batchInput);

            var result = sentiment.Documents.Single();

            return(result.Score);
        }
Beispiel #10
0
    public SentimentBatchResult GetSentiment(List <SentimentPhrase> sentimentPhrases)
    {
        if (sentimentPhrases.Count > 1000)
        {
            throw new Exception("The limit of 1000 phrases has been exceeded - none of your list will have been sent for analysis ");
        }
        var items = new List <MultiLanguageInput>();

        foreach (var s in sentimentPhrases)
        {
            var input = new MultiLanguageInput(s.LanguageCode, s.Id, s.Phrase);
            items.Add(input);
        }

        var result = _client.Sentiment(new MultiLanguageBatchInput(items));

        return(result);
    }
Beispiel #11
0
        public async static Task <List <MultiLanguageInput> > GetTweets(string query)
        {
            List <MultiLanguageInput> TweetInput = new List <MultiLanguageInput>();

            Auth.SetUserCredentials(creds.ConsumerKey, creds.ConsumerSecret, creds.AccessToken, creds.AccessSecret);
            //var tweets = await SearchAsync.SearchTweets(query);
            Tweets = await SearchAsync.SearchTweets(query);

            List <Tweetinvi.Models.ITweet> tweetList = Tweets.ToList();
            int i = 0;

            foreach (Tweetinvi.Models.ITweet item in tweetList)
            {
                var k = new MultiLanguageInput("en", i.ToString(), item.FullText);
                TweetInput.Add(k);
                i++;
            }
            return(TweetInput);
        }
        public KeyPhraseBatchResult GetKeyPhraseList(IList <LanguageModel> list)
        {
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.AzureRegion     = AzureRegions.Westeurope;
            client.SubscriptionKey = "";

            var listInput = new List <MultiLanguageInput>();

            for (int i = 0; i < list.Count; i++)
            {
                var language = DetectLanguageServiceForAString(list[i].Text).Documents[0].DetectedLanguages[0].Iso6391Name;
                var input    = new MultiLanguageInput(list[i].Language, i.ToString(), list[i].Text);
                listInput.Add(input);
            }

            KeyPhraseBatchResult result2 = client.KeyPhrases(
                new MultiLanguageBatchInput(listInput));

            return(result2);
        }
        /// <summary>
        /// Button event. Collects the inputs from the list box and sends them off to the API
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void runBtn_Click(object sender, EventArgs e)
        {
            if (ItemLb.Items.Count > 0)
            {
                List <Input> Inputs = new List <Input>();
                List <MultiLanguageInput> MultiInput = new List <MultiLanguageInput>();
                int count = 0;

                for (int i = 0; i < ItemLb.Items.Count; i++)
                {
                    count++;
                    Input Input = new Input
                    {
                        Id   = Convert.ToString(count),
                        Text = Convert.ToString(ItemLb.Items[i].ToString())
                    };
                    Inputs.Add(Input);
                }

                for (int i = 0; i < Inputs.Count; i++)
                {
                    MultiLanguageInput Input = new MultiLanguageInput
                    {
                        Language = "En",
                        Id       = Inputs[i].Id,
                        Text     = Inputs[i].Text
                    };
                    MultiInput.Add(Input);
                }

                Generate GenerateFrm = new Generate(SelectedActions, Inputs, MultiInput);
                GenerateFrm.ShowDialog();
            }
            else
            {
                MessageBox.Show("No inputs available", "Error");
            }
        }
        //public List<SentimentResults> extractingKeyPhrases(List<GuestGeek_DBService.CrimeTweets> crimeTweets)
        //{
        //    // Create a client.---------------------------------------------------------------------------------------------------------------------------------
        //    ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
        //    {
        //        Endpoint = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/"
        //    };

        //    System.Console.OutputEncoding = System.Text.Encoding.UTF8;

        //    // Getting key phrases.---------------------------------------------------------------------------------------------------------------------------------
        //    Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======");

        //    List<MultiLanguageInput> keyPhrases = new List<MultiLanguageInput>();
        //    foreach (GuestGeek_DBService.CrimeTweets ct in crimeTweets)
        //    {
        //        MultiLanguageInput inp = new MultiLanguageInput(;
        //        myInp.Add(inp);
        //    }

        //    KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
        //                new List<MultiLanguageInput>()
        //                {
        //                  new MultiLanguageInput("ja", "1", "猫は幸せ"),
        //                  new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
        //                  new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
        //                  new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
        //                })).Result;

        //    // Printing key phrases.
        //    foreach (var document in result2.Documents)
        //    {
        //        Console.WriteLine("Document ID: {0} ", document.Id);

        //        Console.WriteLine("\t Key phrases:");

        //        foreach (string keyphrase in document.KeyPhrases)
        //        {
        //            Console.WriteLine("\t\t" + keyphrase);
        //        }
        //    }
        //}

        //static async void MakeRequest()
        //{
        //    var client = new HttpClient();
        //    var queryString = HttpUtility.ParseQueryString(string.Empty);

        //    // Request headers
        //    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", TwitterKeys.getTextAnalyticsKey());

        //    var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?" + queryString;

        //    HttpResponseMessage response;

        //    // Request body
        //    byte[] byteData = Encoding.UTF8.GetBytes("{body}");

        //    using (var content = new ByteArrayContent(byteData))
        //    {
        //        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        //        response = await client.PostAsync(uri, content);
        //    }
        //}

        public List <SentimentResults> fullAnalysis(List <DB_Service.CrimeTweets> crimeTweets)
        {
            // Create a client.---------------------------------------------------------------------------------------------------------------------------------
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/"
            };

            System.Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Extracting language.---------------------------------------------------------------------------------------------------------------------------------
            Console.WriteLine("===== LANGUAGE EXTRACTION ======");

            List <Input> myInp = new List <Input>();//Languages

            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                //Sentiment.Sentiment.sanitize(ct.message);
                Input inp = new Input(ct.tweet_id.ToString(), ct.message);
                myInp.Add(inp);
            }

            LanguageBatchResult result = null;

            try
            {
                result = client.DetectLanguageAsync(new BatchInput(myInp)).Result;
                //Task.Run(() => client.DetectLanguageAsync(new BatchInput(myInp)).Result).Wait();
            }
            catch (AggregateException aex)
            {
                string messages = "";

                foreach (Exception ex in aex.InnerExceptions)
                {
                    messages += ex.Message + "\r\n";
                }

                Debug.WriteLine(messages);
            }



            // Printing language results.
            List <SentimentResults> tweetLangs = new List <SentimentResults>();//Language

            foreach (var document in result.Documents)
            {
                SentimentResults tr = new SentimentResults();
                tr.language_short = document.DetectedLanguages[0].Iso6391Name;
                tr.tweet_id       = Int32.Parse(document.Id);
                tr.language       = document.DetectedLanguages[0].Name;
                tweetLangs.Add(tr);
            }

            // Getting key phrases.---------------------------------------------------------------------------------------------------------------------------------
            Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======");

            List <MultiLanguageInput> keyPhrases = new List <MultiLanguageInput>();//Key phrases
            int count = 0;

            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                string             tempLang = tweetLangs.ElementAt <SentimentResults>(count).language_short;
                MultiLanguageInput inp      = new MultiLanguageInput(tempLang, ct.tweet_id.ToString(), ct.message);
                keyPhrases.Add(inp);
                count++;
            }

            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(keyPhrases)).Result;

            // Printing key phrases.
            List <string>           phrases         = new List <string>();
            List <SentimentResults> tweetKeyPhrases = new List <SentimentResults>();

            count = 0;
            foreach (var document in result2.Documents)
            {
                //Console.WriteLine("Document ID: {0} ", document.Id);

                //Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                {
                    //Console.WriteLine("\t\t" + keyphrase);
                    phrases.Add(keyphrase);
                }
                SentimentResults sr = new SentimentResults();
                sr            = tweetLangs.ElementAt <SentimentResults>(count);
                sr.keyPhrases = phrases;
                tweetKeyPhrases.Add(sr);
                count++;
            }

            // Analyzing sentiment.---------------------------------------------------------------------------------------------------------------------------------
            Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======");

            List <MultiLanguageInput> sentiAni = new List <MultiLanguageInput>();//Sentiment Analysis

            count = 0;
            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                string             tempLang = tweetKeyPhrases.ElementAt <SentimentResults>(count).language_short;
                MultiLanguageInput inp      = new MultiLanguageInput(tempLang, ct.tweet_id.ToString(), ct.message);
                sentiAni.Add(inp);
                count++;
            }

            SentimentBatchResult result3 = client.SentimentAsync(new MultiLanguageBatchInput(sentiAni)).Result;

            // Printing sentiment results.
            List <SentimentResults> tweetSentiments = new List <SentimentResults>();

            count = 0;

            foreach (var document in result3.Documents)
            {
                //Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score);
                SentimentResults sr = new SentimentResults();
                sr             = tweetKeyPhrases.ElementAt <SentimentResults>(count);
                sr.senti_score = (double)document.Score;
                tweetSentiments.Add(sr);
                count++;
            }

            List <DB_Service.Sentiments> completeSentiments = new List <DB_Service.Sentiments>();

            foreach (SentimentResults finalResults in tweetSentiments)
            {
                DB_Service.Sentiments newSenti = new DB_Service.Sentiments();
                newSenti.tweet_id         = finalResults.tweet_id;
                newSenti.sentiment_total  = finalResults.senti_score;
                newSenti.category_primary = finalResults.language + ", " + finalResults.language_short;

                StringBuilder wholePhrase = new StringBuilder("");
                count = 0;
                foreach (String word in finalResults.keyPhrases)
                {
                    count++;
                    if (finalResults.keyPhrases.Count > count)
                    {
                        wholePhrase.Append(word + ",");
                    }
                    else
                    {
                        wholePhrase.Append(word);
                    }
                }
                completeSentiments.Add(newSenti);
            }
            DB_Service.ServiceClient service = new DB_Service.ServiceClient();
            service.addSentiments(completeSentiments);
            return(tweetSentiments);

            // Linking entities---------------------------------------------------------------------------------------------------------------------------------
            //Console.WriteLine("\n\n===== ENTITY LINKING ======");

            //EntitiesBatchResult result4 = client.EntitiesAsync(
            //        new MultiLanguageBatchInput(
            //            new List<MultiLanguageInput>()
            //            {
            //                new MultiLanguageInput("en", "0", "I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable."),
            //                new MultiLanguageInput("en", "1", "The Seattle Seahawks won the Super Bowl in 2014."),
            //            })).Result;

            //// Printing entity results.
            //foreach (var document in result4.Documents)
            //{
            //    Console.WriteLine("Document ID: {0} , Entities: {1}", document.Id, String.Join(", ", document.Entities.Select(entity => entity.Name)));
            //}
        }
        public static List <SentimentResults> fullAnalysis(List <DB_Service.CrimeTweets> crimeTweets)
        {//-------------------------------------------------------------------------------------------------------------------------------------
            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westeurope.api.cognitive.microsoft.com"
                           //https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0
            };

            //-------------------------------------------------------------------------------------------------------------------------------------
            // Extracting language

            List <Input> myInp = new List <Input>();

            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                Input inp = new Input(ct.tweet_id.ToString(), ct.message);
                myInp.Add(inp);
            }

            var result = client.DetectLanguageAsync(new BatchInput(myInp)).Result;

            List <SentimentResults> tweetLangs = new List <SentimentResults>();

            // Printing language results.
            foreach (var document in result.Documents)
            {
                SentimentResults sr = new SentimentResults();
                sr.setTweet_id(Int32.Parse(document.Id));
                sr.setLanguage_short(document.DetectedLanguages[0].Iso6391Name);
                sr.setLanguage(document.DetectedLanguages[0].Name);
                tweetLangs.Add(sr);
            }
            //-------------------------------------------------------------------------------------------------------------------------------------
            // Getting key-phrases

            List <MultiLanguageInput> keyPhrases = new List <MultiLanguageInput>();//Key phrases
            int count = 0;

            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                string             tempLang = tweetLangs.ElementAt <SentimentResults>(count).getLanguage_short();
                MultiLanguageInput inp      = new MultiLanguageInput(tempLang, ct.tweet_id.ToString(), ct.message);
                keyPhrases.Add(inp);
                count++;
            }

            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(keyPhrases)).Result;

            // Printing keyphrases
            List <string>           phrases         = new List <string>();
            List <SentimentResults> tweetKeyPhrases = new List <SentimentResults>();

            count = 0;
            foreach (var document in result2.Documents)
            {
                foreach (string keyphrase in document.KeyPhrases)
                {
                    phrases.Add(keyphrase);
                }
                SentimentResults sr = new SentimentResults();
                sr = tweetLangs.ElementAt <SentimentResults>(count);
                sr.setKeyPhrases(phrases);
                tweetKeyPhrases.Add(sr);
                count++;
            }
            //-------------------------------------------------------------------------------------------------------------------------------------
            // Getting Sentiment Analysis

            List <MultiLanguageInput> sentiAni = new List <MultiLanguageInput>();//Sentiment Analysis

            count = 0;
            foreach (DB_Service.CrimeTweets ct in crimeTweets)
            {
                string             tempLang = tweetKeyPhrases.ElementAt <SentimentResults>(count).getLanguage_short();
                MultiLanguageInput inp      = new MultiLanguageInput(tempLang, ct.tweet_id.ToString(), ct.message);
                sentiAni.Add(inp);
                count++;
            }

            SentimentBatchResult result3 = client.SentimentAsync(new MultiLanguageBatchInput(sentiAni)).Result;

            // Printing sentiment results
            List <SentimentResults> tweetSentiments = new List <SentimentResults>();

            count = 0;

            foreach (var document in result3.Documents)
            {
                SentimentResults sr = new SentimentResults();
                sr = tweetKeyPhrases.ElementAt <SentimentResults>(count);
                sr.setSenti_score((double)document.Score);
                tweetSentiments.Add(sr);
                count++;
            }

            //-------------------------------------------------------------------------------------------------------------------------------------
            // Getting Entities

            //Continue using the same list so languages wont change
            EntitiesBatchResult result4 = client.EntitiesAsync(new MultiLanguageBatchInput(sentiAni)).Result;

            // Printing entities results
            List <string>           entitiySet    = new List <string>();
            List <SentimentResults> tweetEntities = new List <SentimentResults>();

            count = 0;

            foreach (var document in result4.Documents)
            {
                foreach (EntityRecord entitiy in document.Entities)
                {
                    entitiySet.Add(entitiy.Name);
                }
                SentimentResults sr = new SentimentResults();
                sr = tweetSentiments.ElementAt <SentimentResults>(count);
                sr.setEntities(entitiySet);
                tweetEntities.Add(sr);
                count++;
            }

            //-------------------------------------------------------------------------------------------------------------------------------------
            //Add Data to Database Service

            List <DB_Service.Sentiments> completeSentiments = new List <DB_Service.Sentiments>();
            List <DB_Service.Entities>   completeEntities   = new List <DB_Service.Entities>();

            foreach (SentimentResults finalResults in tweetEntities)
            {
                //Start building Sentiment class
                DB_Service.Sentiments newSenti = new DB_Service.Sentiments();
                newSenti.tweet_id         = finalResults.getTweet_id();
                newSenti.sentiment_total  = finalResults.getSenti_score();
                newSenti.category_primary = finalResults.getLanguage() + ", " + finalResults.getLanguage_short();

                List <string> entList     = finalResults.getEntities();
                List <string> phraseList  = finalResults.getKeyPhrases();
                StringBuilder wholePhrase = new StringBuilder("");
                count = 0;
                //Start building Entity Class
                if (entList != null && entList.Count > 0)
                {
                    foreach (string entity in entList)
                    {
                        wholePhrase.Append(entity + ",");
                        //DB_Service.Entities newEntity = new DB_Service.Entities();
                        //newEntity.name = entity;
                        //newEntity.sentiment_id = -1//this is a programming design problem
                    }
                }

                if (phraseList != null && phraseList.Count > 0)
                {
                    foreach (string word in phraseList)
                    {
                        count++;
                        if (phraseList.Count > count)
                        {
                            wholePhrase.Append(word + ",");
                        }
                        else
                        {
                            wholePhrase.Append(word);
                        }
                    }
                }

                newSenti.key_phrases = wholePhrase.ToString();

                //List<string> EntList = finalResults.getEntities();
                //if(EntList != null && EntList.Count > 0)
                //{
                //    //newSenti.category_primary = EntList.ElementAt<string>(0);

                //}
                //else
                //{
                //    newSenti.category_primary = "";
                //}
                //Finish building Sentiment Class
                completeSentiments.Add(newSenti);
            }
            //Add to service now
            DB_Service.ServiceClient service = new DB_Service.ServiceClient();
            service.addSentiments(completeSentiments);

            return(tweetEntities);
        }