示例#1
0
        public async Task <bool> UpdateAsync(Guid Id, TopicsRequest topicsRequest, string GetUserId)
        {
            var topicsexist = await _context.Topics
                              .AnyAsync(s => s.Name.Equals(topicsRequest.Name) && s.AppUserId.Equals(GetUserId));

            if (topicsexist)
            {
                return(false);
            }

            var topics = await GetByIdAsync(Id, GetUserId);

            if (topics == null)
            {
                return(false);
            }

            topics.Name = topicsRequest.Name;

            _context.Topics.Update(topics);

            var filter = Builders <ChatRoom> .Filter.Eq(s => s.TopicsId, topics.Id.ToString());

            var update = Builders <ChatRoom> .Update.Set(s => s.Name, topics.Name);

            await _chatroom.UpdateOneAsync(filter, update);

            var created = await _context.SaveChangesAsync();

            return(created > 0);
        }
示例#2
0
        private async Task InsertPostTopics(TopicsRequest topicsReq, string MSCognitiveServicesAccessToken)
        {
            PTI.CognitiveServicesClient.CognitiveServicesClient objCSClient =
                new PTI.CognitiveServicesClient.CognitiveServicesClient(MSCognitiveServicesAccessToken);
            int totalPages = (int)Math.Ceiling((decimal)topicsReq.documents.Count() / (decimal)1000);

            for (int iPage = 0; iPage < totalPages; iPage++)
            {
                var reqBatch = topicsReq.documents.Skip(iPage * 1000).Take(1000);
                var tmpreq   = new PTI.CognitiveServicesClient.MSCognitiveServices.Topics.TopicsRequest();
                tmpreq.stopWords       = new string[0];
                tmpreq.topicsToExclude = new string[0];
                tmpreq.documents       = reqBatch.ToArray();
                await objCSClient.GetTopics(tmpreq);

                //var topicsResponse = await objCSClient.GetTopics(tmpreq);
                //using (MoodDetector.DataAccess.MoodDetectorContext ctx =
                //    new DataAccess.MoodDetectorContext())
                //{
                //    ctx.Configuration.AutoDetectChangesEnabled = false;
                //    foreach (var singleTopicRecord in topicsResponse.documents)
                //    {
                //        var userPost = ctx.FacebookUserPosts.Where(p => p.PostId == singleTopicRecord.id).FirstOrDefault();
                //        var objNewSentimentRecord = new DataAccess.FacebookUserPostSentiment();
                //        objNewSentimentRecord.FacebookUserPostId = userPost.FacebookUserPostId;
                //        objNewSentimentRecord.Score = singleTopicRecord.score;
                //        ctx.FacebookUserPostSentiments.Add(objNewSentimentRecord);
                //    }
                //    ctx.SaveChanges();
                //}
            }
        }
示例#3
0
        public async Task <AuthResponse> UpdateAsync(Guid Id, TopicsRequest topicsRequest)
        {
            var response = await _httpService.Put <TopicsRequest, AuthResponse>($"{url}/{Id}", topicsRequest);

            if (!response.Success)
            {
                throw new ApplicationException(await response.GetBody());
            }

            return(response.Response);
        }
示例#4
0
        public async Task <AuthResponse> CreateAsync(TopicsRequest topicsRequest)
        {
            var response = await _httpService.Post <TopicsRequest, AuthResponse>(APIRoute.Topics.Create, topicsRequest);

            if (!response.Success)
            {
                throw new ApplicationException(await response.GetBody());
            }

            return(response.Response);
        }
示例#5
0
        public async Task GetTopics(TopicsRequest request)
        {
            string     getTopicsUrl  = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/topics";
            HttpClient objHttpClient =
                new HttpClient();
            string        jsonRequest   = Newtonsoft.Json.JsonConvert.SerializeObject(request);
            StringContent objStrContent = new StringContent(jsonRequest);

            objStrContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            objStrContent.Headers.Add("Ocp-Apim-Subscription-Key", AccessToken);
            var result = await objHttpClient.PostAsync(getTopicsUrl, objStrContent);

            var resultString = await result.Content.ReadAsStringAsync();
        }
示例#6
0
        public async Task <IActionResult> Update([FromRoute] Guid topicsId, [FromBody] TopicsRequest topicsRequest)
        {
            var topics = await _topicsService.UpdateAsync(topicsId, topicsRequest, GetUserId());

            if (!topics)
            {
                return(Ok(new AuthResponse
                {
                    Error = "The Name Already Exist"
                }));
            }

            return(Ok(new AuthResponse
            {
                Token = "The Topic is Updated"
            }));
        }
示例#7
0
        public async Task <bool> CreateAsync(TopicsRequest topicsRequest, string GetUserId)
        {
            var topicsexist = await _context.Topics
                              .AnyAsync(s => s.Name.Equals(topicsRequest.Name) && s.AppUserId.Equals(GetUserId));

            if (topicsexist)
            {
                return(false);
            }

            var newTopics = new Topics
            {
                Id          = Guid.NewGuid(),
                Name        = topicsRequest.Name,
                AppUserId   = GetUserId,
                CreatedDate = DateTime.Now
            };

            _context.Topics.Add(newTopics);

            var newChapter = new Chapter
            {
                Id          = Guid.NewGuid(),
                Name        = "Welcome",
                TopicsId    = newTopics.Id,
                CreatedDate = DateTime.Now
            };

            _context.Chapters.Add(newChapter);

            var newChatRoom = new ChatRoom
            {
                Name         = newTopics.Name,
                CreatedDate  = DateTime.Now,
                TopicsId     = newTopics.Id.ToString(),
                ChatMessages = new ChatMessage [] {}
            };

            await _chatroom.InsertOneAsync(newChatRoom);

            var created = await _context.SaveChangesAsync();

            return(created > 0);
        }
示例#8
0
        // GET: Facebook
        public async Task ImportMyPosts()
        {
            string MSCognitiveServicesAccessToken =
                System.Configuration.ConfigurationManager.AppSettings[
                    GlobalConstants.MSCSTextAnalyticsKey
                ];
            string WatsonPIUserName =
                ConfigurationManager.AppSettings[GlobalConstants.WatsonPIUserName];
            string WatsonPIPassword =
                ConfigurationManager.AppSettings[GlobalConstants.WatsonPIPassword];
            //Check https://developers.facebook.com/docs/graph-api/reference/v2.8/user/feed
            FacebookClient objClient = CreateFacebookClient();
            dynamic        myPosts   = await objClient.GetTaskAsync(@"me/posts?fields=id,application,caption,created_time,description,from,message,name,status_type,story,type");

            string myPostsJson = myPosts.ToString();

            Models.Entities.Facebook.MyPosts objMyPosts =
                Newtonsoft.Json.JsonConvert.DeserializeObject <Models.Entities.Facebook.MyPosts>
                    (myPostsJson);
            List <Models.Entities.Facebook.MyPosts> lstMyPosts =
                new List <Models.Entities.Facebook.MyPosts>();

            lstMyPosts.Add(objMyPosts);
            string userId     = objMyPosts.data.First().from.id;
            int    count      = 0;
            int    totalPosts = 0;

            //while (count++ <= 2)
            while (objMyPosts.paging != null && !String.IsNullOrWhiteSpace(objMyPosts.paging.next))
            {
                myPosts = await objClient.GetTaskAsync(objMyPosts.paging.next);

                myPostsJson = myPosts.ToString();
                objMyPosts  =
                    Newtonsoft.Json.JsonConvert.DeserializeObject <Models.Entities.Facebook.MyPosts>
                        (myPostsJson);
                lstMyPosts.Add(objMyPosts);
                //totalPosts += objMyPosts.data.Where(p => !string.IsNullOrWhiteSpace(p.message)).Count();
            }
            var allNotEmptyMessages = lstMyPosts.SelectMany(p => p.data.Where(x => !String.IsNullOrWhiteSpace(x.message)));

            totalPosts = allNotEmptyMessages.Count();
            PTI.CognitiveServicesClient.MSCognitiveServices.Sentiment.SentimentRequest
                sentimentReq = new PTI.CognitiveServicesClient.MSCognitiveServices.Sentiment.SentimentRequest();
            sentimentReq.documents =
                new PTI.CognitiveServicesClient.MSCognitiveServices.Sentiment.SentimentRequestDocument[totalPosts];
            TopicsRequest topicsReq = new TopicsRequest();

            topicsReq.documents = new TopicsRequestDocument[totalPosts];
            KeyPhrasesRequest keyPhrasesReq = new KeyPhrasesRequest();

            keyPhrasesReq.documents = new KeyPhrasesRequestDocument[totalPosts];
            PersonalityInsightsRequest personalityInsightsReq =
                new PersonalityInsightsRequest();

            personalityInsightsReq.contentItems =
                new Contentitem[totalPosts];
            int iPos = 0;
            var detectedLanguages =
                (await DetectLanguage(allNotEmptyMessages, MSCognitiveServicesAccessToken)).SelectMany(p => p.documents);

            foreach (var singlePost in allNotEmptyMessages)
            {
                if (!string.IsNullOrWhiteSpace(singlePost.message))
                {
                    sentimentReq.documents[iPos]      = new PTI.CognitiveServicesClient.MSCognitiveServices.Sentiment.SentimentRequestDocument();
                    sentimentReq.documents[iPos].id   = singlePost.id;
                    sentimentReq.documents[iPos].text = singlePost.message;

                    topicsReq.documents[iPos]      = new TopicsRequestDocument();
                    topicsReq.stopWords            = new string[0];
                    topicsReq.topicsToExclude      = new string[0];
                    topicsReq.documents[iPos].id   = singlePost.id;
                    topicsReq.documents[iPos].text = singlePost.message;

                    keyPhrasesReq.documents[iPos]      = new KeyPhrasesRequestDocument();
                    keyPhrasesReq.documents[iPos].id   = singlePost.id;
                    keyPhrasesReq.documents[iPos].text = singlePost.message;

                    personalityInsightsReq.contentItems[iPos] =
                        new Contentitem();
                    personalityInsightsReq.contentItems[iPos].content = singlePost.message;
                    personalityInsightsReq.contentItems[iPos].id      = singlePost.id;

                    var language = detectedLanguages.Where(p => p.id == singlePost.id).FirstOrDefault();
                    if (language != null && language.detectedLanguages.Count() > 0)
                    {
                        string languageCode = language.detectedLanguages.First().iso6391Name;
                        personalityInsightsReq.contentItems[iPos].language = languageCode;
                        sentimentReq.documents[iPos].language  = languageCode;
                        keyPhrasesReq.documents[iPos].language = languageCode;
                    }
                    iPos++;
                }
            }
            try
            {
                SaveToDatabase(lstMyPosts);
                await InsertPostsSentiment(sentimentReq, MSCognitiveServicesAccessToken);
                await InsertPostTopics(topicsReq, MSCognitiveServicesAccessToken);
                await InsertKeyPhrases(keyPhrasesReq, MSCognitiveServicesAccessToken);

                var piLanguageGroup = personalityInsightsReq.contentItems.GroupBy(p => p.language)
                                      .Select(x =>
                                              new
                {
                    Language = x.Key,
                    Value    = new PersonalityInsightsRequest()
                    {
                        contentItems = x.ToArray()
                    }
                }
                                              ).Where(p => p.Language == "en" || p.Language == "es");
                foreach (var singleLanguageRequest in piLanguageGroup)
                {
                    await InsertPersonalityInsights(singleLanguageRequest.Value, piUsername : WatsonPIUserName, piPassword : WatsonPIPassword, facebookUserId : userId);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#9
0
 /// <summary> Setter constructor. </summary>
 public Topics(TopicsRequest request)
 {
     Request  = request;
     Response = new TopicsResponse();
 }