Exemple #1
0
        public IndexModule()
        {
            //commentss
            Get["/"] = parameters =>
            {
                //var vids = new Videos();
                //var testVid = new VideoDto { Angle = "front", Description = "awesome winner", Player = "Federer", Stroke = "forehand", YoutubeId = "asdfsnyew2" };
                //vids.AddVideo(testVid);


                //List<VideoDto> lstVids = vids.GetAll();
                var newsMode = new ValueLookUp().Get("EspnNewsMode");

                var viewModel = new IndexViewModel();
                viewModel.BlogBaseURl = AppSetting.BlogEngineBaseUrl;

                if (newsMode == "server")
                {
                    viewModel.EspnNewsURl = "/services/news";
                }
                else
                {
                    string clientOnlyUrl = string.Format("{0}?apikey={1}&callback=JSON_CALLBACK", AppSetting.EspnHeadlinesUrl, AppSetting.EspnApiKey);
                    viewModel.EspnNewsURl = clientOnlyUrl;
                }

                //getting bing search results
                var bing = new BingSearch();
                viewModel.VideoResults = bing.GetVideoSearchResults();

                //return View["index", viewModel].AsCacheable(DateTime.Now.AddSeconds(30));
                return(View["index", viewModel]);
            };
        }
        public virtual async Task GetClientID(IDialogContext context, IAwaitable <IMessageActivity> response)
        {
            var clientID = await response;

            usuario = new Usuario();
            // Validación de usuario en base de datos.
            try
            {
                using (Data.Database db = new Data.Database())
                {
                    usuario = await db.RetrieveUser(clientID.Text);
                }
            } catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }


            await context.PostAsync($"Te confirmo que tu número de cliente es: {clientID.Text}. Es bueno tenerte de vuelta, ¿Dime que te pareció la película {usuario.MovieName}?");

            _calificacion = new Calificacion()
            {
                UserID  = clientID.Text,
                MovieID = usuario.MovieName
            };
            using (BingSearch bs = new BingSearch())
            {
                var message    = context.MakeMessage();
                var attachment = GetThumbnailCard(usuario.MovieName, usuario.Rating.ToString(), string.Empty, await bs.BuscarImagen(usuario.MovieName));
                message.Attachments.Add(attachment);
                await context.PostAsync(message);
            }
            PromptDialog.Choice(context, RateMovie, MovieRatings, "Selecciona la puntuación con la que calificarías la película");
        }
Exemple #3
0
        protected async Task <Activity> BuildBingReply(string text)
        {
            dynamic res = await BingSearch.CallBingSearch(text);

            Activity replyToConversation = msg.CreateReply();

            replyToConversation.Type        = "message";
            replyToConversation.Attachments = new List <Attachment>();
            List <CardAction> cardButtons = new List <CardAction>();
            CardAction        plButton    = new CardAction()
            {
                Value = res.displayUrl,
                Type  = "openUrl",
                Title = text
            };

            cardButtons.Add(plButton);
            ThumbnailCard plCard = new ThumbnailCard()
            {
                Title    = res.name,
                Subtitle = res.snippet,
                //Images = cardImages,
                Buttons = cardButtons
            };
            Attachment plAttachment = plCard.ToAttachment();

            replyToConversation.Attachments.Add(plAttachment);
            return(replyToConversation);
        }
        public async System.Threading.Tasks.Task BingNoResultsReturnedAsync()
        {
            ISearchEngine bing    = new BingSearch();
            var           results = await bing.GetSearchResultListAsync("asdasdsadadfdwefvtrvrtbwohbtygfvycvwregerge", 1);

            Assert.IsTrue(results.Count == 0);
        }
        public async System.Threading.Tasks.Task BingFixedResultReturnedAsync()
        {
            ISearchEngine bing    = new BingSearch();
            var           results = await bing.GetSearchResultListAsync("test", 1);

            Assert.IsTrue(results.Count == 1);
        }
Exemple #6
0
        public IndexModule()
        {
            //commentss
            Get["/"] = parameters =>
            {
                //var vids = new Videos();
                //var testVid = new VideoDto { Angle = "front", Description = "awesome winner", Player = "Federer", Stroke = "forehand", YoutubeId = "asdfsnyew2" };
                //vids.AddVideo(testVid);

                //List<VideoDto> lstVids = vids.GetAll();
                var newsMode = new ValueLookUp().Get("EspnNewsMode");

                var viewModel = new IndexViewModel();
                viewModel.BlogBaseURl = AppSetting.BlogEngineBaseUrl;

                if (newsMode == "server")
                {
                    viewModel.EspnNewsURl = "/services/news";
                }
                else
                {
                    string clientOnlyUrl = string.Format("{0}?apikey={1}&callback=JSON_CALLBACK", AppSetting.EspnHeadlinesUrl, AppSetting.EspnApiKey);
                    viewModel.EspnNewsURl = clientOnlyUrl;

                }

                //getting bing search results
                var bing = new BingSearch();
                viewModel.VideoResults = bing.GetVideoSearchResults();

                //return View["index", viewModel].AsCacheable(DateTime.Now.AddSeconds(30));
                return View["index", viewModel];
            };
        }
Exemple #7
0
        private async Task <DialogTurnResult> InitialStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var    query           = stepContext.Context.Activity.Text;
            string searchType      = query.Substring(0, 2);
            var    bingSearch      = new BingSearch(stepContext.Context);
            string subscriptionKey = configuration.GetValue <string>("BingSearchKey");

            switch (searchType)
            {
            case "i ":
                await bingSearch.ImageSearch(subscriptionKey, query.Substring(2));

                return(await stepContext.EndDialogAsync());

            case "v ":
                await bingSearch.VideoSearch(subscriptionKey, query.Substring(2));

                return(await stepContext.EndDialogAsync());

            case "w ":
                await bingSearch.WebSearch(subscriptionKey, query.Substring(2));

                return(await stepContext.EndDialogAsync());

            default:
                return(await stepContext.BeginDialogAsync(nameof(QnAMakerDialog), null, cancellationToken));
            }
        }
        public static async void showBingWikiHeroCard(IMessageActivity message, BingSearch searchResult)
        {
            //Make reply activity and set layout
            Activity reply = ((Activity)message).CreateReply();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            HeroCard card = new HeroCard()
            {
                Title    = searchResult.webPages.value[0].name,
                Subtitle = "Powered By Bing Search API",
                Text     = searchResult.webPages.value[0].snippet,
                Buttons  = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Read More",
                        Type  = ActionTypes.OpenUrl,
                        Value = searchResult.webPages.value[0].displayUrl
                    }
                }
            };

            reply.Attachments.Add(card.ToAttachment());


            //make connector and reply message
            ConnectorClient connector = new ConnectorClient(new Uri(reply.ServiceUrl));
            await connector.Conversations.SendToConversationAsync(reply);
        }
        public static BingSearch getSearchResult(string searchQuery)
        {
            BingSearch bs = new BingSearch();

            bs = Newtonsoft.Json.JsonConvert.DeserializeObject <BingSearch>(BingWebSearch(searchQuery).jsonResult);

            return(bs);
        }
        public async Task ArtistInfo(IDialogContext context, LuisResult result)
        {
            QureyController qc     = new QureyController();
            string          entity = "";
            string          ans    = "";

            qc.PostQuestionOne(result.Query, result.TopScoringIntent.Intent, result.TopScoringIntent.Score.ToString(), "0");

            if (result.Entities != null)
            {
                switch (result.Entities.Count)
                {
                case 1:
                    entity += result.Entities[0].Entity;
                    break;

                case 2:
                    entity += result.Entities[0].Entity + " " + result.Entities[1].Entity;
                    break;

                case 3:
                    entity += result.Entities[0].Entity + " " + result.Entities[1].Entity + " " + result.Entities[2].Entity;
                    break;
                }
            }
            else
            {
                entity = result.Query;
            }

            await context.PostAsync("Here are results i found : ");

            try
            {
                BingSearch bingSearch = new BingSearch();

                bingSearch = BingSearchData.getSearchResult(entity);

                if (bingSearch != null)
                {
                    CardUtil.showBingWikiHeroCard((IMessageActivity)context.Activity, bingSearch);
                    ans = bingSearch.news.readLink;
                }
                else
                {
                    await context.PostAsync($"I couldn't find a artist info :0");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error when filtering artists: {e}");
            }
            if (ans == "")
            {
                ans = "";
            }
            qc.PostAnswerOne(ans, result.TopScoringIntent.Intent);
        }
        /// <summary>
        /// MainViewModel constructor. Creates <see cref="BingAutoSuggest"/> and <see cref="BingSearch"/> objects and the search command
        /// </summary>
        public MainViewModel()
        {
            _autoSuggest = new BingAutoSuggest();
            _bingSearch  = new BingSearch();

            SearchCommand = new DelegateCommand(Search);

            SelectedSearchType = SearchTypes.FirstOrDefault();
        }
Exemple #12
0
        private Status GenerateSuggestions(WorkflowInstance workflowInstance, ServerEntity entity, Dictionary <string, string> suggestionList)
        {
            Item item = entity as Item;

            if (item == null)
            {
                TraceLog.TraceError("Entity is not an Item");
                return(Status.Error);
            }

            try
            {
                BingSearch bingSearch = new BingSearch();

                // retrieve and format the search template, or if one doesn't exist, use $(Intent)

                string searchTemplate = null;
                if (InputParameters.TryGetValue(ActivityParameters.SearchTemplate, out searchTemplate) == false)
                {
                    searchTemplate = String.Format("$({0})", ActivityVariables.Intent);
                }
                string query = ExpandVariables(workflowInstance, searchTemplate);

                if (String.IsNullOrWhiteSpace(query))
                {
                    TraceLog.TraceInfo("No query to issue Bing");
                    return(Status.Complete);
                }

                // make a synchronous webservice call to bing
                //
                // Async has the problem that the caller of this method assumes that a
                // populated suggestionList will come out.  If it doesn't, the state will execute
                // again and trigger a fresh set of suggestions to be generated.  Eventually all
                // queries will return and populate the suggestions DB with duplicate data.
                // This can be fixed once we move to a "real" workflow system such as WF.
                var results = bingSearch.Query(query);
                foreach (var r in results)
                {
                    WebResult result = r as WebResult;
                    if (result != null)
                    {
                        suggestionList[result.Title] = result.Url;
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.TraceException("Bing query failed", ex);
                return(Status.Error);
            }

            // this activity is typically last and once links have been generated, no need
            // to keep the workflow instance around
            return(Status.Complete);
        }
Exemple #13
0
        public async Task <List <SearchEngineResult> > Search(string query, string keyWord)
        {
            var bingSearch = new BingSearch();

            var policy = Policy.Handle <WebException>()
                         .WaitAndRetryAsync(5, a => TimeSpan.FromMilliseconds(200));

            return(await policy.ExecuteAsync(async() =>
                                             await bingSearch.BingWebSearchAsync(query, keyWord)
                                             ));
        }
Exemple #14
0
        private IList <ISearch> GetImplementedSearchEngines()
        {
            GoogleSearch google = new GoogleSearch();
            BingSearch   bing   = new BingSearch();

            IList <ISearch> engines = new List <ISearch>();

            engines.Add(google);
            engines.Add(bing);

            return(engines);
        }
Exemple #15
0
        public async Task BingTest()
        {
            ISearch _searchEngine;

            IList <ISearch> engines = new List <ISearch>();

            _searchEngine = new BingSearch();

            var result = await _searchEngine.TotalResults(".net");

            Assert.IsNotNull(result);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            GoogleSearch oGoogleSearch = new GoogleSearch();
            BingSearch   oBingSearch   = new BingSearch();

            Console.WriteLine("Type programming languages and press enter:");

            ///GET DATA FROM INPUT
            string data = Console.ReadLine();

            ///SEPARATING DATA FROM INPUT BY SPACE
            var toSearchList = data.Split(' ');

            long googleSearchResult = default(long);
            long bingSearchResult   = default(long);

            List <Result> googleResultList = new List <Result>();
            Result        googleResult     = new Result();

            List <Result> bingResultList = new List <Result>();
            Result        bingResult     = new Result();

            foreach (var item in toSearchList)
            {
                ///SEARCH IN GOOGLE
                googleResult       = oGoogleSearch.GetGoogleSearchList(item);
                googleSearchResult = googleResult.ErrorMessage != null ? default(int) : googleResult.GoogleAmount;

                googleResultList.Add(googleResult);

                ///SEARCH IN BING
                bingResult       = oBingSearch.GetBingSearchList(item);
                bingSearchResult = bingResult.ErrorMessage != null ? default(int) : bingResult.BingAmount;

                bingResultList.Add(bingResult);

                Console.WriteLine($"{item}:\n\tGoogle: {googleSearchResult}\n\tMSN Search: {bingSearchResult}\n");
            }

            string programmingLanguageGoogleWinner = googleResultList.FirstOrDefault(m => m.GoogleAmount == googleResultList.Max(x => x.GoogleAmount)).ProgrammingLanguage;
            string programmingLanguageBingWinner   = bingResultList.FirstOrDefault(m => m.BingAmount == bingResultList.Max(x => x.BingAmount)).ProgrammingLanguage;

            Console.WriteLine($"Google winner: {programmingLanguageGoogleWinner}\n");
            Console.WriteLine($"MSN winner: {programmingLanguageBingWinner}\n");

            string totalWinnerSearch = googleResultList.Max(x => x.GoogleAmount) > bingResultList.Max(x => x.BingAmount) ? programmingLanguageGoogleWinner : programmingLanguageBingWinner;

            Console.WriteLine($"Total winner: {totalWinnerSearch}");

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
Exemple #17
0
        private Status GenerateSuggestions(WorkflowInstance workflowInstance, ServerEntity entity, Dictionary<string, string> suggestionList)
        {
            Item item = entity as Item;
            if (item == null)
            {
                TraceLog.TraceError("Entity is not an Item");
                return Status.Error;
            }

            try
            {
                BingSearch bingSearch = new BingSearch();

                // retrieve and format the search template, or if one doesn't exist, use $(Intent)

                string searchTemplate = null;
                if (InputParameters.TryGetValue(ActivityParameters.SearchTemplate, out searchTemplate) == false)
                    searchTemplate = String.Format("$({0})", ActivityVariables.Intent);
                string query = ExpandVariables(workflowInstance, searchTemplate);

                if (String.IsNullOrWhiteSpace(query))
                {
                    TraceLog.TraceInfo("No query to issue Bing");
                    return Status.Complete;
                }

                // make a synchronous webservice call to bing
                //
                // Async has the problem that the caller of this method assumes that a
                // populated suggestionList will come out.  If it doesn't, the state will execute
                // again and trigger a fresh set of suggestions to be generated.  Eventually all
                // queries will return and populate the suggestions DB with duplicate data.
                // This can be fixed once we move to a "real" workflow system such as WF.
                var results = bingSearch.Query(query);
                foreach (var r in results)
                {
                    WebResult result = r as WebResult;
                    if (result != null)
                        suggestionList[result.Title] = result.Url;
                }
            }
            catch (Exception ex)
            {
                TraceLog.TraceException("Bing query failed", ex);
                return Status.Error;
            }

            // this activity is typically last and once links have been generated, no need
            // to keep the workflow instance around
            return Status.Complete;
        }
Exemple #18
0
        public static int IntegratedResult(string queryterms)
        {
            NLPHelper nlp        = new NLPHelper();
            int       finalPoint = 0;
            //string text = File.ReadAllText(_filePath + "sample.txt");
            KeyValuePair <string, int> resultFromNLP = nlp.POSIndirectResult(queryterms);

            if (resultFromNLP.Value >= 80)          //  this is news
            {
                string newterms = RemoveFakeTerm(queryterms);
                finalPoint = BingSearch.BingNewsSearch(newterms);
            }
            return(finalPoint);
        }
        public void TestGetJson()
        {
            search = new BingSearch(ht, apiKey);
            JObject data = search.GetJson();

            Assert.AreEqual(data["search_metadata"]["status"], "Success");

            JArray coffeeShops = (JArray)data["organic_results"];

            Assert.IsNotNull(coffeeShops);
            foreach (JObject coffeeShop in coffeeShops)
            {
                Console.WriteLine("Found: " + coffeeShop["title"]);
                Assert.IsNotNull(coffeeShop["title"]);
            }
        }
        private async Task <IList <Microsoft.Bot.Connector.Attachment> > GetCarousel(List <string> recomendacion)
        {
            List <Microsoft.Bot.Connector.Attachment> attachments = new List <Microsoft.Bot.Connector.Attachment>();

            for (int i = 1; i < recomendacion.Count; i++)
            {
                using (BingSearch videoSearch = new BingSearch())
                {
                    string video = await videoSearch.BuscarVideo($"{recomendacion[i]} trailer");

                    string image = await videoSearch.BuscarImagen($"{recomendacion[i]}");

                    attachments.Add(GetVideoCard(recomendacion[i], string.Empty, string.Empty, image, video));
                }
            }
            return(attachments);
        }
Exemple #21
0
        static void Main(string[] args)
        {
            //if (args.Length == 0)
            //{
            //    Console.WriteLine("Correct Usage : KeywordSuggestor.exe filename.txt");
            //}
            
            //var fileName = args[0];
            const string Filename = @"C:\newsitem1.txt";
            const long totalNumberOfdocs = 50000000000; // Fifty Billion
            var searchEngine = new BingSearch();
            //var result = searchEngine.Search("google");
            var contents = File.ReadAllText(Filename);
            contents = contents.Replace("\r", "").Replace("\n", "");
            var exludedWords = File.ReadAllText("ExcludedWords.txt")
                .Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            var allwords = contents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var distinctWords = allwords.Distinct().Select(x => x.ToLower());
            var filteredWords = distinctWords.Where(x => !exludedWords.Contains(x.ToLower())).ToList();
            var dictionaryHits = new Dictionary<string, long>();
            var options = new ParallelOptions { MaxDegreeOfParallelism = 5 };
            Parallel.ForEach(filteredWords, options,
                word =>
                {
                    var result = searchEngine.Search(word);
                    dictionaryHits.Add(result.SearchTerm, result.Total);
                });

            var dictTFIDF = new Dictionary<string, double>();
            Parallel.ForEach(dictionaryHits, options,
                element =>
                {
                    var tf = allwords.Count(x => x.ToLower() == element.Key);
                    var idf = Math.Log((totalNumberOfdocs / element.Value), 2);
                    var tf_idf = tf * idf;
                    dictTFIDF.Add(element.Key, tf_idf);
                });

            foreach (var element in dictTFIDF)
            {
                Console.WriteLine(string.Format("{0:25}{1}", element.Key, element.Value));
            }

            Console.ReadKey();
        }
Exemple #22
0
        public async Task Bing([Remainder] string search)
        {
            if (string.IsNullOrEmpty(bingSearchEndpoint) || string.IsNullOrEmpty(bingSearchKey))
            {
                await ReplyAsync("Bing hasn't been setup.");

                return;
            }

            string escapedSearch = Uri.EscapeDataString(search);
            string safeSearch    = Context.Channel is ITextChannel text && text.IsNsfw ? "Off" : "Strict";

            HttpRequestMessage request = new HttpRequestMessage()
            {
                RequestUri = new Uri(bingSearchEndpoint + $"/search?count=5&q={escapedSearch}&safeSearch={safeSearch}"),
                Method     = HttpMethod.Get,
                Headers    =
                {
                    { "Ocp-Apim-Subscription-Key", bingSearchKey }
                }
            };

            BingSearch response = await _http.GetObjectAsync <BingSearch>(request, TimeSpan.FromMinutes(30));

            if (response.WebPages == null)
            {
                await ReplyAsync("I couldn't find anything.");

                return;
            }

            EmbedBuilder embedBuilder = new EmbedBuilder()
                                        .WithTitle($"For more results go to the Bing page.")
                                        .WithUrl(response.WebPages.WebSearchURL)
                                        .WithAuthor("Bing Results", "https://i.ibb.co/f94KyMB/bing.png")
                                        .WithFooter($"SafeSearch is set to {safeSearch} because your channel {(safeSearch == "Strict" ? "isn't" : "is")} NSFW.");

            foreach (WebPage q in response.WebPages.Value)
            {
                embedBuilder.Description += $"**[{q.Name}]({q.URL})**\n{q.Snippet}\n";
            }

            await ReplyAsync(embed : embedBuilder.Build());
        }
        public async Task WhoIsQuestion(IDialogContext context, IAwaitable <IMessageActivity> activity,
                                        LuisResult result)
        {
            QureyController qc = new QureyController();

            qc.PostQuestionOne(result.Query, result.TopScoringIntent.Intent, result.TopScoringIntent.Score.ToString(), "0");

            if (result.TopScoringIntent.Score > 0.5)
            {
                string entity = result.Query;

                await context.PostAsync("I think it is : ");

                try
                {
                    BingSearch bingSearch = new BingSearch();

                    bingSearch = BingSearchData.getSearchResult(entity);

                    if (bingSearch != null)
                    {
                        CardUtil.showBingWikiHeroCard((IMessageActivity)context.Activity, bingSearch);
                    }
                    else
                    {
                        await context.PostAsync($"I couldn't find any results :( You can try again.");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"I couldn't find any results :( You can try again.");
                    Console.WriteLine(e);
                }
            }
            else
            {
                string ans = "";
                ans = qc.GetTrainedAnswer(result.Query);
                qc.PostAnswerOne(ans, result.TopScoringIntent.Intent);
                await context.PostAsync(ans);

                context.Wait(MessageReceived);
            }
        }
Exemple #24
0
        public async Task Positive(IDialogContext context, LuisResult result)
        {
            //Register Message
            if (msg.Text != "!users" && msg.Text != "!stats")
            {
                await ConversationState.RegisterMessage(msg.From.Name, msg.Text);
            }

            dynamic res = await BingSearch.CallBingImageSearch(result.Query);


            Activity replyToConversation = msg.CreateReply();

            replyToConversation.Type        = "message";
            replyToConversation.Attachments = new List <Attachment>();
            List <CardImage> cardImages = new List <CardImage>();
            var imgUrl = res.contentUrl.ToString();

            cardImages.Add(new CardImage(imgUrl.ToString(), "img", null));
            List <CardAction> cardButtons = new List <CardAction>();
            CardAction        plButton    = new CardAction()
            {
                Value = res.contentUrl,
                Type  = "openUrl",
                Title = ""
            };

            cardButtons.Add(plButton);
            ThumbnailCard plCard = new ThumbnailCard()
            {
                Title    = "",
                Subtitle = "",
                Images   = cardImages
            };
            Attachment plAttachment = plCard.ToAttachment();

            replyToConversation.Attachments.Add(plAttachment);

            await context.PostAsync(replyToConversation);

            context.Wait(MessageReceived);
        }
Exemple #25
0
        public async Task ResumeAfterEnteringQuery(IDialogContext context, IAwaitable <string> result)
        {
            query = (await result)as string; //gets the user querry
            switch (searchType)
            {
            case searchWeb:
            {
                await BingSearch.SearchUlsterAsync(context, BING_KEY, query + " site:ulster.ac.uk");       //passes query to BingSearch Class

                break;
            }

            case searchImage:
            {
                await BingSearch.SearchImageAsync(context, BING_KEY, query);

                break;
            }
            }
        }
        /// <summary>
        /// LuisViewModel constructor.
        /// Creates vision client, luis client, speech-to-text and text-to-speech clients, as well as ICommand objects
        /// </summary>
        public LuisViewModel()
        {
            _bingSearch = new BingSearch();

            _visionClient = new VisionServiceClient("FACE_API_KEY", "ROOT_URI");

            _luis = new Luis(new LuisClient("LUIS_APP_ID", "LUIS_API_KEY"));
            _luis.OnLuisUtteranceResultUpdated += OnLuisUtteranceResultUpdated;

            _sttClient = new SpeechToText(_bingApiKey);
            _sttClient.OnSttStatusUpdated += OnSttStatusUpdated;

            _ttsClient = new TextToSpeech();
            _ttsClient.OnAudioAvailable += OnTtsAudioAvailable;
            _ttsClient.OnError          += OnTtsError;
            GenerateHeaders();

            RecordUtteranceCommand  = new DelegateCommand(RecordUtterance);
            ExecuteUtteranceCommand = new DelegateCommand(ExecuteUtterance, CanExecuteUtterance);
        }
        public static BingSearch BingWebResult(string req)
        {
            string         search  = $"https://api.cognitive.microsoft.com/bing/v7.0/search?q= {req}";
            string         key     = "2818789504e041e2816cf6cabf15ab56";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);

            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var json = reader.ReadToEnd();
                        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                        {
                            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BingSearch));
                            BingSearch result = (BingSearch)deserializer.ReadObject(ms);

                            return(result);
                        }
                    }
        }
Exemple #28
0
        public ArPageViewModel(INavigationService navigationService)
        {
            this.navigationService = navigationService;
            repository             = new HappenedHereRepository();
            geowatcher             = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
            nearbyCoordinates      = new Stack <GeoCoordinate>();
            nearbyStreets          = new List <string>();
            searcher = new BingSearch(this);

            isHeadingIndicatorVisible = false;
            isMapVisible                   = false;
            isWorldViewVisible             = true;
            isProgressBarIndeterminate     = true;
            overheadMapRotationSource      = RotationSource.North;
            headingIndicatorRotationSource = RotationSource.AttitudeHeading;

            toggleHeadingText   = AppResources.ToggleHeading;
            toggleHeadingIcon   = new Uri("/Assets/ArPage/AppBar/heading.png", UriKind.Relative);
            showMapText         = AppResources.ShowMap;
            showMapIcon         = new Uri("/Assets/ArPage/AppBar/map.png", UriKind.Relative);
            refreshArticlesText = AppResources.RefreshArticles;
            articleItems        = new ObservableCollection <ARItem>();
        }
Exemple #29
0
        private int ExecuteThirdPass(AnalyseVideo analyseVideo, ParallelLoopState loopState, int currentPass)
        {
            if (analyseVideo.Candidates.Count == 0 || analyseVideo.MatchPercentage < Constants.GREAT_MATCH_FOUND_TRESHOLD)
            {
                analyseVideo.AddTitleGuesses(VideoTitleExtractor.GetTitleGuessesFromPath(analyseVideo.Video.Files[0].Path));
                //TODO 004 optimize this --> also gets done in pass1 --> remember somehow
                UniqueList <string> titleGuesses = analyseVideo.GetTitleGuesses();

                string fileNameGuess   = analyseVideo.GetMainFileNameGuess();
                string folderNameGuess = analyseVideo.GetMainFolderNameGuess();

                titleGuesses.Clear();
                foreach (string searchResult in BingSearch.Search(fileNameGuess))
                {
                    analyseVideo.AddTitleGuesses(VideoTitleExtractor.CleanTitle(searchResult));
                }

                if (folderNameGuess != null)
                {
                    foreach (string searchResult in BingSearch.Search(folderNameGuess))
                    {
                        analyseVideo.AddTitleGuesses(VideoTitleExtractor.CleanTitle(searchResult));
                    }
                }

                FillCandidates(analyseVideo, fileNameGuess, folderNameGuess);
            }

            analyseVideo.HandledTitleGuesses();
            ExecuteAfterPass(currentPass);
            //if (CancellationPending)
            //{
            //	e.Cancel = true;
            //	return;
            //}
            return(currentPass);
        }
Exemple #30
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var message = await result;

            string entity = "";

            if (message.Text.Length > 0)
            {
                entity = message.Text;
            }

            await context.PostAsync("Here are results i found : ");

            try
            {
                BingSearch bingSearch = new BingSearch();

                bingSearch = BingSearchData.getSearchResult(entity);

                if (bingSearch != null)
                {
                    CardUtil.showBingWikiHeroCard((IMessageActivity)context.Activity, bingSearch);
                    QureyController qc = new QureyController();
                    qc.PostAnswerOne(bingSearch.entities.readLink, "BingSearch");
                }
                else
                {
                    await context.PostAsync($"I couldn't find what you asked, you can always try again..");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error when filtering by genre: {e}");
            }

            context.Done <object>(null);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            //NounCollection coll = NounCollection.Instance;
            //String [] related = null;
            //Console.WriteLine(coll.Nouns["hello"].GetDescription(0, out related));

            //using (StreamWriter writer = new StreamWriter(File.Create(@"\1.txt")))
            //{
            //    for (int index = 0; index < 256; index++)
            //        writer.WriteLine(String.Concat(index, " ", (char)index));
            //}
            //Console.WriteLine((int)'e');//'é');

            //BingSearch search = new BingSearch();
            //search.SearchWeb("apj kalam");

            //Wikipedia wClass = new Wikipedia(new WikiQueryEngine());
            //Console.WriteLine(wClass.IsArticleAvailable("Plain white T's"));
            //SearchSuggestion searchSuggest = wClass.SearchArticles("Plain white T's", 10);
            //foreach (SearchSuggestionItem sItem in searchSuggest.Section)
            //{
            //    Console.WriteLine(sItem.Text + "\n\t" + sItem.Description + "\n" + sItem.Url);
            //}
            //Console.WriteLine(wClass.GetArticle("Seattle", false).Introduction);

            OmukSemantics semantics = new OmukSemantics();
            //YSearch search = new YSearch();
            //YSearchResultCollection resCollection = search.SearchWeb("me genera serotonina listening to Viva la Vida by Coldplay", 0, 10, ref semantics);
            BingSearch bsearch = new BingSearch();

            bsearch.SearchWeb("Am I Dreaming by Xscape", 0, 10, ref semantics);
            semantics.PostSearch();
            semantics.FormContext();

            LyricWiki    wiki   = new LyricWiki();
            LyricsResult lyrics = wiki.getSong("Rihanna", "Umbrella");

            Console.WriteLine(lyrics.lyrics);
            //Console.WriteLine("");
            LastFmService service = new LastFmService();
            //service.GetArtistInfo(

            //MusicBrainz mb = new MusicBrainz();
            // mb.GetAlbums

            //Grooveshark gshark = new Grooveshark();
            //GSSong[] song = gshark.SearchSong("Sugar", 2);

            //LyricWiki wiki = new LyricWiki();
            //LyricsResult lyrics = wiki.getSong("R.e.m", "Moon river");
            //lyrics.GetLyricsHtml();
            //SongResult songs = wiki.searchSongs("R.e.m", "Moon river");


            //String artist = "Flo rida";
            //String album = "Sugar";
            //int year = 2009;
            //String[] albums = null;
            //String res = wiki.getAlbum(ref artist, ref album, ref year, out albums);

            //AlbumData[] album = (AlbumData[])wiki.getArtist(ref artist);
            //LWLyrics lyrics = wiki.GetLyricsForSong("Flo rida", "sugar");
            //Console.WriteLine(wiki.IsArtist("rihanna"));
            //String[] albums = wiki.GetAlbums("rihanna");


            //LastFmService service = new LastFmService();
            //LFMArtist artist = service.GetArtistInfo("Rihanna");
            //List<LFMArtist> albums = service.SearchArtist("Kid Cudi", 0);

            //Immem immem = new Immem();
            //List<ImmemSearchItem> items = immem.SearchMedia("Rihanna good girl gone bad", "music", 0, 10);

            MusicBrainz    mb     = new MusicBrainz();
            List <MBAlbum> albums = mb.GetAlbums(String.Empty, "Rihanna", "73e5e69d-3554-40d8-8516-00cb38737a1c", 0, 10);
            List <MBSong>  songs  = mb.GetSongs("oh Carol", "Neil", "", "", "", 0, 2);

            //YouTube yt = new YouTube();
            //List<YTVideo> videos = yt.SearchVideos("oh carol", 0, 3);

            //RottenTomatoes rt = new RottenTomatoes();
            //String val = rt.GetTomatometerScore("http://www.rottentomatoes.com/m/1009437-heidi/");

            /*
             * Twitter twitter = new Twitter();
             * ////twitter.SearchTwitter("i gotta feeling", 0, 10);
             * TMovieTrendsClass mTrends = new TMovieTrendsClass();
             * twitter.GetMovieTrends("The Martian", ref mTrends);
             * Console.WriteLine("");
             */

            //twitter.GetMovieTrends("\"the proposal\"",ref mTrends);
            //twitter.GetMovieTrends("\"year one\"", ref mTrends);
            //twitter.GetMovieTrends("\"Terminator Salvation\"", ref mTrends);
            //twitter.GetMovieTrends("\"Next day air\"", ref mTrends);
            //twitter.GetMovieTrends("\"Imagine That\"", ref mTrends);
            //twitter.GetMovieTrends("\"Taking of Pelham 1 2 3", ref mTrends);
            //twitter.GetMovieTrends("Wolverine", ref mTrends);
            //using (StreamWriter writer = new StreamWriter(File.Create("trend.txt")))
            //{
            //    foreach (KeyValuePair<String, int> keyval in mTrends.Trend)
            //    {
            //        if (keyval.Value > 3)
            //            writer.WriteLine(String.Format("{0} {1}", keyval.Key, keyval.Value));
            //    }
            //}

            //TSearchResultCollection twRes = twitter.SearchTwitter("palm pre", 0, 15);


            //Eventful evntful = new Eventful ();
            //EventCollection coll = evntful.SearchEvents("San Jose", 0, 10);
            //Digg digg = new Digg();
            //List<DiggResult> res = digg.SearchDigg("Hello", 0, 10);
            return;
        }
Exemple #32
0
 private void bingSearchToolStripMenuItem_Click(object sender, EventArgs e)
 {
     BingSearch b = new BingSearch(ActiveEditor.codebox.Text, Common.SearchMethod.Startinbrowser);
 }
Exemple #33
0
        /// <summary>
        /// BingSearchViewModel constructor.
        /// Creates a new <see cref="BingSearch"/> object and an ICommand object to execute the search
        /// </summary>
        public BingSearchViewModel()
        {
            _bingSearch = new BingSearch();

            SearchCommand = new DelegateCommand(Search, CanSearch);
        }