示例#1
0
    private List <Link> procuraBing(string query, uint nLinks, bool flagTodosTermos)
    {
        List <Link> list = new List <Link>();

        BingService service = new BingService();

        SearchRequest request = new SearchRequest();

        // Usar a AppID do Bing
        request.AppId = "FC90D229624ED0C50F60665F288516BD9FF1F40A";
        request.Query = query;

        //Conteudo Adulto Off
        request.Adult          = AdultOption.Off;
        request.AdultSpecified = true;

        // Pesquisar fontes na web
        request.Sources = new SourceType[] { SourceType.Web };

        //Limitar numero de links
        request.Web                = new WebRequest();
        request.Web.Count          = nLinks;
        request.Web.CountSpecified = true;

        SearchResponse response = service.Search(request);

        foreach (WebResult result in response.Web.Results)
        {
            list.Add(new Link(result.Title, result.Url, result.Description));
        }
        return(list);
    }
示例#2
0
        public static string Translate(string fromLang, string toLang, string query)
        {
            // BingService implements IDisposable.
            using (BingService service = new BingService())
            {
                try
                {
                    SearchRequest request = BuildRequest(fromLang, toLang, query);

                    // Send the request; display the response.
                    SearchResponse response = service.Search(request);
                    return(ParseTranslation(response));
                }
                catch (System.Web.Services.Protocols.SoapException ex)
                {
                    // A SOAP Exception was thrown. Display error details.
                    DisplayErrors(ex.Detail);
                }
                catch (System.Net.WebException ex)
                {
                    // An exception occurred while accessing the network.
                    Console.WriteLine(ex.Message);
                }
            }
            return("|ERROR - no translation");
        }
示例#3
0
 public ImageListPage()
 {
     InitializeComponent();
     IsLoading    = true;
     bingServices = new BingService();
     Images       = new IncrementalCollection <ImageInfo>(LoadAsync);
 }
示例#4
0
    private List<Link> procuraBing(string query, uint nLinks, bool flagTodosTermos)
    {
        List<Link> list = new List<Link>();

        BingService service = new BingService();

        SearchRequest request = new SearchRequest();

        // Usar a AppID do Bing
        request.AppId = "FC90D229624ED0C50F60665F288516BD9FF1F40A";
        request.Query = query;

        //Conteudo Adulto Off
        request.Adult = AdultOption.Off;
        request.AdultSpecified = true;

        // Pesquisar fontes na web
        request.Sources = new SourceType[] { SourceType.Web };

        //Limitar numero de links
        request.Web = new WebRequest();
        request.Web.Count = nLinks;
        request.Web.CountSpecified = true;

        SearchResponse response = service.Search(request);

        foreach (WebResult result in response.Web.Results)
        {
            list.Add(new Link(result.Title, result.Url, result.Description));
        }
        return list;
    }
示例#5
0
 public VMAjouterCompte()
 {
     _bingService          = new BingService();
     _wsService            = new WSService();
     AddedCompte           = new Compte();
     BtnClearCompteCommand = new RelayCommand(ClearCompte);
     BtnAddCompteCommand   = new RelayCommand(AddCompte);
 }
示例#6
0
        public async Task BadResponse()
        {
            MockHttp.When(BaseUrl)
            .Respond(System.Net.HttpStatusCode.BadRequest);

            var service = new BingService("SOME_KEY", MockHttp.ToHttpClient());

            await Assert.ThrowsAsync <GCException>(() => service.GetCoordinate("Good address"));
        }
示例#7
0
        public static IEnumerable <BingResult> GetNewsItems(string query)
        {
            var searchConfig = new BingSearchConfig
            {
                Query     = query,
                QueryType = BingQueryType.Search
            };

            return(BingService.GetAsIncrementalLoading(searchConfig, 50));
        }
示例#8
0
        public async Task MissingJsonParams(string jsonPath)
        {
            var missingParamResponse = await File.OpenText(jsonPath).ReadToEndAsync();

            MockHttp.When(BaseUrl)
            .Respond("application/json", missingParamResponse);

            var service = new BingService("SOME_KEY", MockHttp.ToHttpClient());

            await Assert.ThrowsAsync <GCException>(() => service.GetCoordinate("Good address"));
        }
示例#9
0
        public string Translate(string src, Language src_lang, Language dest_lang)
        {
            String result = null;

            BingService   bs = new BingService();
            SearchRequest sr = new SearchRequest();

            sr.AppId   = _apikey;
            sr.Sources = new SourceType[] { SourceType.Translation };

            sr.Translation = new TranslationRequest();
            sr.Translation.SourceLanguage = LangToString(src_lang);
            sr.Translation.TargetLanguage = LangToString(dest_lang);
            sr.Query   = src;
            sr.Version = "2.2";

            src = Unformat(src);

            SearchResponse response = bs.Search(sr);

            if (response != null)
            {
                if (response.Translation != null)
                {
                    if (response.Translation.Results != null)
                    {
                        if (response.Translation.Results.Length > 0)
                        {
                            result = response.Translation.Results[0].TranslatedTerm;

                            if (result.CompareTo(src) == 0)
                            {
                                result = null;
                            }
                            else if (result.Length == 0)
                            {
                                result = null;
                            }
                        }
                    }
                }
            }

            if (result != null)
            {
                result = Format(result);
            }

            return(result);
        }
示例#10
0
        private async void Search(string query)
        {
            //foreach(BingImage image in Images)
            //{
            //    image.IsLoading = true;
            //        await LoadImage(image.MediaFilePath, image.Image);
            //    image.IsLoading = false;
            //}

            Images.Clear();
            IsLoading = true;

            Images = await BingService.SearchImagesAsync(query, 10);

            IsLoading = false;
        }
示例#11
0
        private async void Search(string query)
        {
            //// Get the app's installation folder.
            //var appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            //// Get the subfolders in the current folder.
            //var subfoldersPromise = appFolder.GetFoldersAsync();
            //subfoldersPromise.(Function getFoldersSuccess(subfolders) {

            //    // Iterate over the results and print the list of folders
            //    // and files to the Visual Studio Output window.
            //    subfolders.forEach(function forEachSubfolder(folder) {
            //        console.log(folder.name);

            //        // To iterate over the files in each folder,
            //        // uncomment the following lines.
            //        // var getFilesPromise = folder.getFilesAsync();
            //        // getFilesPromise.done(function getFilesSuccess(files) {
            //        //     console.log(folder.name);
            //        //     files.forEach(function forEachFile(file) {
            //        //         console.log(".", file.name);
            //        //     });
            //        // });
            //    });
            //});

            //ObservableItemCollection<Album> list = new ObservableItemCollection<Album>();
            //IReadOnlyList<StorageFolder> var = Windows.Storage.ApplicationData.Current.LocalFolder.GetFoldersAsync()

            IsLoading = true;
            ObservableItemCollection <BingImage> images = await BingService.SearchImagesAsync(query, 10);

            //BingImageSearchService serv = new BingImageSearchService();
            //ObservableCollection<BingImage> images = await serv.SearchImagesAsync(query);
            if (images != null)
            {
                foreach (BingImage image in images)
                {
                    PresentationItemCollection.Add(new TeamItemViewModel()
                    {
                        BingImage = image
                    });
                }
            }
            IsLoading = false;
        }
示例#12
0
        private async void SearchButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (!await Tools.CheckInternetConnectionAsync())
            {
                return;
            }

            if (string.IsNullOrEmpty(SearchText.Text))
            {
                return;
            }

            BingCountry  country  = (BingCountry)(CntryList?.SelectedItem ?? BingCountry.UnitedStates);
            BingLanguage language = (BingLanguage)(Languages?.SelectedItem ?? BingLanguage.English);

            BingQueryType queryType;

            switch (QueryType.SelectedIndex)
            {
            case 1:
                queryType = BingQueryType.News;
                break;

            default:
                queryType = BingQueryType.Search;
                break;
            }

            var searchConfig = new BingSearchConfig
            {
                Country   = country,
                Language  = language,
                Query     = SearchText.Text,
                QueryType = queryType
            };

            // Gets an instance of BingService that is able to load search results incrementally.
#pragma warning disable CS0618 // Type or member is obsolete
            var collection = BingService.GetAsIncrementalLoading(searchConfig, 50);
#pragma warning restore CS0618 // Type or member is obsolete
            collection.OnStartLoading = async() => await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SampleController.Current.DisplayWaitRing = true; });

            collection.OnEndLoading = async() => await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SampleController.Current.DisplayWaitRing = false; });

            ListView.ItemsSource = collection;
        }
        public void TestMultipleTermsCase()
        {
            BingService       service        = new BingService();
            string            searchCriteria = "internet information server";
            SearchEngineQuery result;

            try
            {
                System.Threading.Thread.Sleep(2000);
                result = service.Search(searchCriteria).GetAwaiter().GetResult();
                Assert.IsTrue(result != null && result.TotalResults > 0);
            }
            catch (Exception)
            {
                Assert.Fail("Exception was thrown");
            }
        }
        public void TestOneTermCase()
        {
            BingService       service_one        = new BingService();
            string            searchCriteria_one = "kubernetes";
            SearchEngineQuery result_one;

            try
            {
                System.Threading.Thread.Sleep(2000);
                result_one = service_one.Search(searchCriteria_one).GetAwaiter().GetResult();
                Assert.IsTrue(result_one != null && result_one.TotalResults > 0);
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception was thrown" + ex.Message);
            }
        }
        public void TestEmptyCriteriaCase()
        {
            BingService       service        = new BingService();
            string            searchCriteria = " ";
            SearchEngineQuery result;

            try
            {
                result = service.Search(searchCriteria).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                StringAssert.Contains(ex.Message, "Search criteria is empty or null");
                return;
            }
            Assert.Fail("Exception was not thrown");
        }
示例#16
0
        public async Task HappyFlow(string jsonPath, AccuracyLevel expectedAccuracy)
        {
            var goodResponse = await File.OpenText(jsonPath).ReadToEndAsync();

            MockHttp.When(BaseUrl)
            .Respond("application/json", goodResponse);

            var service = new BingService("SOME_KEY", MockHttp.ToHttpClient());

            var coordinates = await service.GetCoordinate("Good address");

            var vals = Generic.ParseCoordinatesFromBingJson(goodResponse);

            Assert.Equal(vals.Item1, coordinates.Latitude);
            Assert.Equal(vals.Item2, coordinates.Longitude);
            Assert.Equal(expectedAccuracy, coordinates.Accuracy);
        }
示例#17
0
        public static string Translate(string sourceLanguageCode, string targetLanguageCode, string text)
        {
            using (BingService service = new BingService())
            {
                try
                {
                    SearchRequest request = BuildRequest(text, sourceLanguageCode, targetLanguageCode);

                    // Send the request; display the response.
                    SearchResponse response = service.Search(request);
                    return(Response(response));
                }
                catch (System.Web.Services.Protocols.SoapException)
                {
                    // A SOAP Exception was thrown. Display error details.
                    return(null);
                }
                catch (System.Net.WebException)
                {
                    // An exception occurred while accessing the network.
                    return(null);
                }
            }
        }
示例#18
0
        public async static Task <List <LiveSession> > SendSOSNotifications(List <LiveSession> sessions)
        {
            //List<LiveSession> processedSessions = new List<LiveSession>();

            Parallel.ForEach(sessions, session =>
            {
                if (!string.IsNullOrEmpty(session.SMSRecipientsList) || !string.IsNullOrEmpty(session.EmailRecipientsList) || !string.IsNullOrEmpty(session.FBGroupID) || !string.IsNullOrEmpty(session.FBAuthID))
                {
                    string tinyUri = string.Empty, mobileNumber = string.Empty;
                    string address = string.Empty;
                    try
                    {
                        if (!string.IsNullOrEmpty(session.Lat) && !string.IsNullOrEmpty(session.Long))
                        {
                            try
                            {
                                address = BingService.GetAddressByPointAsync(session.Lat, session.Long).Result;
                            }
                            catch (Exception ex)
                            {
                                address = string.Format("Latitude : {0} , Longitude : {1}", session.Lat, session.Long);
                                System.Diagnostics.Trace.TraceError(String.Format("Error while retreiving Bing Address for Profile: {0}, ErrorMessage: {1}", session.ProfileID, ex.Message));
                            }
                        }

                        if (string.IsNullOrWhiteSpace(session.TinyUri))
                        {
                            session.TinyUri = GetTinyUri(session.ProfileID.ToString(), session.SessionID);
                        }

                        tinyUri      = session.TinyUri;
                        mobileNumber = Security.Decrypt(session.MobileNumber);

                        //Send SMS notifications to Buddies
                        if (Config.SendSms && !string.IsNullOrEmpty(session.SMSRecipientsList) && (!session.LastSMSPostTime.HasValue || session.LastSMSPostTime.Value.AddMinutes(Config.SMSPostGap) <= DateTime.UtcNow))//DATEADD(minute,@SMSInterval,LastSMSPostTime) <= GETDATE()
                        {
                            try
                            {
                                if (!session.SMSRecipientsList.StartsWith("DM"))
                                {
                                    session.SMSRecipientsList = "DM" + DecryptMobileNumbers(session.SMSRecipientsList);
                                }

                                SMS.SendSMS(session.SMSRecipientsList.Substring(2), Utility.GetSMSBody(tinyUri, session.Name, address, mobileNumber));
                                session.LastSMSPostTime = System.DateTime.UtcNow;
                                session.NoOfSMSSent++;
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Trace.TraceError(String.Format("Error while sending SMS for user with Mobile Number : {0}, ErrorMessage: {1}", mobileNumber, ex.Message));
                            }
                        }

                        //Send Email to buddies
                        if (!string.IsNullOrEmpty(session.EmailRecipientsList) && (!session.LastEmailPostTime.HasValue || session.LastEmailPostTime.Value.AddMinutes(Config.EmailPostGap) <= DateTime.UtcNow))
                        {
                            try
                            {
                                Email.SendEmail(session.EmailRecipientsList.Split(',').ToList(),
                                                Utility.GetEmailBody(tinyUri, session.Name, address, mobileNumber, session.LastCapturedDate.Value),
                                                Utility.GetEmailSubject(session.Name));
                                session.LastEmailPostTime = System.DateTime.UtcNow;
                                session.NoOfEmailsSent++;
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Trace.TraceError(String.Format("Error while sending email for Profile: {0}, ErrorMessage: {1}", session.ProfileID, ex.Message));
                            }
                        }

                        ////Post on FB account
                        //if (!String.IsNullOrEmpty(session.FBGroupID) && !String.IsNullOrEmpty(session.FBAuthID) && (!session.LastFacebookPostTime.HasValue || session.LastFacebookPostTime.Value.AddMinutes(Config.FacebookPostGap) <= DateTime.UtcNow))
                        //{
                        //    try
                        //    {
                        //        FaceBookPosting.FBPosting(session.FBAuthID,
                        //            Utility.GetFacebookMessage(tinyUri, session.Name, address, mobileNumber, session.LastCapturedDate.Value),
                        //            Utility.GetFacebookCaption(session.Name), tinyUri, session.FBGroupID);
                        //        session.LastFacebookPostTime = System.DateTime.UtcNow;
                        //        session.NoOfFBPostsSent++;
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        System.Diagnostics.Trace.TraceError(String.Format("Error while posting on FB Group for the Profile: {0}, ErrorMessage: {1}", session.ProfileID, ex.Message));
                        //    }
                        //}
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.TraceError(String.Format("Error while posting to friends for GeoTag with Identifier: {0}, ErrorMessage: {1}", session.SessionID, ex.Message));
                    }
                    finally
                    {
                    }
                }
            });
            return(sessions);
        }
示例#19
0
 public ImageDetailPage()
 {
     InitializeComponent();
     bingService = new BingService();
 }
示例#20
0
 public TTSManager(IAsyncPlayer player) 
 {
     this.player = player;
     bingService = new BingService();
 }
示例#21
0
 public BingServiceTests(AutoMockerFixture mocker, TemporalFilesFixture temporalFiles)
 {
     _mocker        = mocker;
     _temporalFiles = temporalFiles;
     _service       = _mocker.CreateInstance <BingService>();
 }
示例#22
0
        static void IntoUnknown()
        {
            StreamWriter streamWriter = new StreamWriter("log.txt", true);

            streamWriter.WriteLine(DateTime.Now.ToString() + "启用服务");
            streamWriter.Close();
            streamWriter.Dispose();
            Bing             bing          = null;
            List <Spotlight> spotlights    = null;
            DateTime         startDataTime = new DateTime();
            Random           random        = new Random();

            while (true)
            {
                Config.IsChangedFromUser = false;
                Config config = Config.Load();
                Config.IsChangedFromUser = true;
                imgPaths.Clear();
                //找出全部符合文件
                foreach (var temp in config.EnableFunctions)
                {
                    switch (temp)
                    {
                    case 0:    //我的
                    {
                        foreach (var temp2 in config.Wallpapers)
                        {
                            if (temp2.IsFloder)
                            {
                                SearchImg(config, temp2.Path);
                            }
                            else
                            {
                                imgPaths.Add(temp2.Path);
                            }
                        }
                    }
                    break;

                    case 1:    //必应
                    {
                        TimeSpan sp = DateTime.Now.Subtract(startDataTime);
                        if (bing == null || sp.Hours > 3)
                        {
                            bing = BingService.GetWallInfo(config).Result;
                        }
                        if (bing != null)
                        {
                            foreach (var temp2 in bing.Images)
                            {
                                imgPaths.Add(temp2.UrlWithHost);
                            }
                        }
                    }
                    break;

                    case 2:
                    {
                        TimeSpan sp = DateTime.Now.Subtract(startDataTime);
                        if (spotlights == null || sp.Hours > 3)
                        {
                            spotlights = GetSpotlight();
                        }
                        if (spotlights != null)
                        {
                            foreach (var temp2 in spotlights)
                            {
                                imgPaths.Add(temp2.Path);
                            }
                        }
                    }
                    break;
                    }
                }

                if (imgHistory.Count == imgPaths.Count)//已全部出现过,重置
                {
                    imgHistory.Clear();
                }
                if (config.Type == 0)
                {
                    int index = 0;
                    if (imgHistory.Count != 0)
                    {
                        index = imgPaths.IndexOf(imgHistory.Last()) + 1;
                    }
                    SetDestPicture(imgPaths[index]);
                    imgHistory.Add(imgPaths[index]);
                }
                else if (config.Type == 1)
                {
                    int index = -1;
                    do
                    {
                        index = random.Next(0, imgPaths.Count - 1);
                    }while (imgHistory.Contains(imgPaths[index]));
                    SetDestPicture(imgPaths[index]);
                    imgHistory.Add(imgPaths[index]);
                }
                //await Task.Delay((int)(config.Duration * 60 * 1000));
                GC.Collect();
                //GC.WaitForFullGCComplete();
                Thread.Sleep((int)(config.Duration * 60 * 1000));
            }
        }
示例#23
0
 public DownloadListPage()
 {
     InitializeComponent();
     Files       = new ObservableCollection <string>();
     bingService = new BingService();
 }
示例#24
0
        /// <summary>
        /// Searches Bing.com API
        /// </summary>
        /// <param name="query">The QueryString to search against</param>
        /// <param name="urlmatch">Only return URLs containing the following match</param>
        /// <param name="threadID">The thread MovieUniqueId.</param>
        /// <returns>First successful match.</returns>
        public static BindingList <QueryResult> SearchBing(string query, string urlmatch, int threadID, string regexTitle, string regexYear, string regexID, ScraperList scraperList)
        {
            var logCatagory = "Scrape > Bing Search > " + query;

            try
            {
                var queryResults = new BindingList <QueryResult>();

                query = query.Replace("%20", " ");

                using (var service = new BingService())
                {
                    var searchRequest = new SearchRequest
                    {
                        Query   = query,
                        Sources = new[] { SourceType.Web },
                        AppId   = "9A2F2F47CF77629DA4E35E912F4B696217DCFC3C"
                    };

                    var webRequest = new WebRequest
                    {
                        Count           = 10,
                        Offset          = 0,
                        OffsetSpecified = true
                    };
                    searchRequest.Web = webRequest;

                    var response = service.Search(searchRequest);

                    if (response.Web.Results != null)
                    {
                        foreach (var result in response.Web.Results)
                        {
                            if (string.IsNullOrEmpty(result.Url) || result.Url.Contains(urlmatch))
                            {
                                var queryResult = new QueryResult();

                                if (Regex.IsMatch(result.Title, regexTitle))
                                {
                                    if (Regex.IsMatch(result.Url, regexID))
                                    {
                                        switch (scraperList)
                                        {
                                        case ScraperList.Imdb:
                                            queryResult.ImdbID = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.TheMovieDB:
                                            queryResult.TmdbID = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.Allocine:
                                            queryResult.AllocineId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.FilmAffinity:
                                            queryResult.FilmAffinityId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.FilmDelta:
                                            queryResult.FilmDeltaId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.FilmUp:
                                            queryResult.FilmUpId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.FilmWeb:
                                            queryResult.FilmWebId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.Impawards:
                                            queryResult.ImpawardsId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.Kinopoisk:
                                            queryResult.KinopoiskId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.OFDB:
                                            queryResult.OfdbId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.MovieMeter:
                                            queryResult.MovieMeterId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;

                                        case ScraperList.Sratim:
                                            queryResult.SratimId = Regex.Match(result.Url, regexID).Groups["id"].Value;
                                            break;
                                        }
                                    }

                                    queryResult.Title = Regex.Match(result.Title, regexTitle).Groups["title"].Value;
                                    queryResult.Year  = Regex.Match(result.Title, regexYear).Groups["year"].Value.ToInt();
                                }
                                else
                                {
                                    queryResult.Title = result.Title;
                                }

                                queryResult.AdditionalInfo = result.Description;
                                queryResult.URL            = result.Url;

                                queryResults.Add(queryResult);
                            }
                        }
                    }

                    Log.WriteToLog(LogSeverity.Info, 0, string.Format("Bing search complete ({0} results)", queryResults.Count), query);

                    return(queryResults);
                }
            }
            catch (Exception ex)
            {
                Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, logCatagory, ex.Message);
                return(null);
            }
        }
 public SEOSearchController(ILogger <SEOSearchController> logger, GoogleService googleService, BingService bingService)
 {
     _logger        = logger;
     _googleService = googleService;
     _bingService   = bingService;
 }