Inheritance: System.Data.Services.Client.DataServiceContext
        public List<BingResult> GetBingNewsResult(string parameter)
        {
            //const string bingKey = "9F3eqLyfmNP0PInNOmS13FdSlPoajoJqLvrbvndqZFM";
            const string bingKey = "wHln8JsLTWNIEDHZTxU3mTjnIr9T7HCGZPZ86BPYZKg";
            var bing = new BingSearchContainer(
                new Uri("https://api.datamarket.azure.com/Bing/Search/"))
            { Credentials = new NetworkCredential(bingKey, bingKey) };

            var	query = bing.News(parameter, null, "en-US", null, null, null, null, "rt_Business","Date");
            var results = query.Execute();

            List<BingResult> binglist = new List<BingResult> ();
            foreach (var result in results)
            {
                //if (!string.IsNullOrEmpty (result.Url)) {
                    BingResult bingResult = new BingResult ();
                    bingResult.ID = result.ID;
                    bingResult.Url = result.Url;
                    bingResult.Description = result.Description;
                    bingResult.Date = result.Date;
                    bingResult.Title = result.Title;
                    binglist.Add (bingResult);
                //}
            }
            return binglist;
        }
Example #2
0
        public IEnumerable <Bing.ImageResult> GetImages(string year, string make, string model, string trim)
        {
            string query = "";

            //if (trim == null)
            query = year + " " + make + " " + model;
            //else
            //    query = year + " " + make + " " + model + " " + trim;

            // Create a Bing container.
            string rootUri       = "https://api.datamarket.azure.com/Bing/Search";
            var    bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));

            // Replace this value with your account key.
            var accountKey = "bFrWiOhaXScS2yyTcXpzk2s5+Gc78yRDhp/qjHKYU+8";

            // Configure bingContainer to use your credentials.
            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);

            // Build the query.
            var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);

            imageQuery = imageQuery.AddQueryOption("$top", 4);
            var imageResults = imageQuery.Execute();

            // if response code != 200, skip the image


            // extract the properties needed for the images

            return(imageResults);
        }
Example #3
0
        public IEnumerable<Bing.ImageResult> GetImages(string year, string make, string model, string trim)
        {
            string query = "";

            //if (trim == null)
            query = year + " " + make + " " + model;
            //else
            //    query = year + " " + make + " " + model + " " + trim;

            // Create a Bing container.
            string rootUri = "https://api.datamarket.azure.com/Bing/Search";
            var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));

            // Replace this value with your account key.
            var accountKey = "bFrWiOhaXScS2yyTcXpzk2s5+Gc78yRDhp/qjHKYU+8";

            // Configure bingContainer to use your credentials.
            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);

            // Build the query.
            var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
            imageQuery = imageQuery.AddQueryOption("$top", 4);
            var imageResults = imageQuery.Execute();

            // if response code != 200, skip the image


            // extract the properties needed for the images
            
            return imageResults;
        }
Example #4
0
 public ImageDownloader()
 {
     _webClient = new WebClient();
     _searchContainer = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search"))
     {
         Credentials = new NetworkCredential(ApiKey, ApiKey)
     };
 }
        // GET: CarSearch/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Car car = await db.Cars.FindAsync(id);
            if (car == null)
            {
                return HttpNotFound();
            }

            HttpResponseMessage response;

            var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));
            client.Credentials = new NetworkCredential("accountKey", "bYJ3eVHV+r8dLybppgrXgIetjoLSVumwlpyLDwmbw8w");
            var marketData = client.Composite(
                "image",
                $"{car.model_year} {car.make} {car.model_name} {car.model_trim}",
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null
                ).Execute();
            ViewBag.imageUrl = marketData?.FirstOrDefault()?.Image?.FirstOrDefault()?.MediaUrl;

            

            using (var httpclient = new HttpClient())
            {
                httpclient.BaseAddress = new Uri("Http://www.nhtsa.gov/");

                try
                {
                    response =
                        await httpclient.GetAsync($"webapi/api/Recalls/vehicle/modelyear/{car.model_year}/make/{car.make}/model/{car.model_name}?format=json");
                    ViewBag.recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }




            return View(car);
        }
        private static List<NewsResult> GetNewArticles()
        {
            var client = new BingSearchContainer(
              new Uri("https://api.datamarket.azure.com/Bing/search/")
              );

            client.Credentials = new NetworkCredential("accountKey", "5/397uT61db2oYMqva78buLleEq9XbhFhz9iuOX+c5U");
            return client.News("Trump", null, "en-US", "Moderate", null, null, null, null, "Date").Execute().ToList();
        }
Example #7
0
        private async void Search_Click(object sender, RoutedEventArgs e) {
            string accountKey = "<ApiKey goes here>";

            var context = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search"));
            context.Credentials = new NetworkCredential(accountKey, accountKey);

            var result = await context.Image(this.SearchQuery.Text, "en-US", null, null, null, null).ExecuteAsync();
            ImagesList.ItemsSource = result.ToList();
        }
        public async Task ExecuteSearch(string searchQuery)
        {
            _lastSearch = searchQuery;
            var context = new BingSearchContainer(
                new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search"));
            context.Credentials = new NetworkCredential(BingAzureDataMarket.AccountKey, BingAzureDataMarket.AccountKey);

            var serviceQuery = context.Image(searchQuery, "en-US", null, null, null, null);
            var result = await serviceQuery.ExecuteAsync();

            ImagesList.ItemsSource = result.ToList();
        }
Example #9
0
        public async System.Threading.Tasks.Task<ActionResult> Details(int? id)
        {
            CarViewModel cvm = new CarViewModel();
           
           cvm.car = db.Cars.Find(id);
            if (cvm.car == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            HttpResponseMessage response;
            var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/")
                   );
            client.Credentials = new NetworkCredential("accountKey", "JDNjFEYyxMGlhlX66nh3S6hQ8aQVOLmI8LJO4QQgdVE");
            var marketData = client.Composite(
                "image",
                $"{cvm.car.model_year} {cvm.car.make} {cvm.car.model_name} {cvm.car.model_trim}",
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null
                ).Execute();

              cvm.imageUrl = marketData.FirstOrDefault()?.Image?.FirstOrDefault()?.MediaUrl;
            
            using (var httpclient = new HttpClient())
            {
                httpclient.BaseAddress = new Uri("Http://www.nhtsa.gov/");

                try
                {
                    response = await httpclient.GetAsync($"webapi/api/Recalls/vehicle/modelyear/{cvm.car.model_year}/make/{cvm.car.make}/model/{cvm.car.model_name}?format=json");
                    cvm.recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                }

                catch (Exception e)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
                }
            }

            return View(cvm);

        }
Example #10
0
        public static IEnumerable<WebResult> ResultSet()
        {
            string bingAccountKey = ConfigurationManager.AppSettings["BingKey"].ToString();
            string address = ConfigurationManager.AppSettings["ApiUrl"].ToString();

            var bing = new BingSearchContainer(
                new Uri(address)) { Credentials = new NetworkCredential(bingAccountKey, bingAccountKey) };

            var query = bing.Web("xbox live", null, null, null, null, null, null, null);
            query = query.AddQueryOption("$top",100);
            var results = query.Execute();
            return results;
        }
Example #11
0
        private void button1_Click_1(object sender, System.EventArgs e)
        {
            try
            {
                richTextBox1.Text = "";
                const string        apiKey              = "AIzaSyDIm9ZOWD8Zd-2tHy5r3c0R-_XjdEFaXGE";
                const string        searchEngineId      = "003470263288780838160:ty47piyybua";
                string              query1              = textBox1.Text;
                CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer()
                {
                    ApiKey = apiKey
                });
                Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query1);
                listRequest.Cx = searchEngineId;
                Search search = listRequest.Execute();
                foreach (var item in search.Items)
                {
                    richTextBox1.Text += item.Link;
                    richTextBox1.Text += " \n ";
                }

                richTextBox1.Text += " \n ---------------------- \n ";

                Repeater rptResult = new Repeater();
                string   rootUrl   = "https://api.datamarket.azure.com/Bing/Search";

                string query         = textBox1.Text;
                var    bingContainer = new Bing.BingSearchContainer(new Uri(rootUrl));
                string market        = "en-us";

                bingContainer.Credentials = new NetworkCredential("bucsexiyu8a87Nw1u3mmTJ/BCPAzGOKFQcydlXYn1S8", "bucsexiyu8a87Nw1u3mmTJ/BCPAzGOKFQcydlXYn1S8");


                var webQuery = bingContainer.Web(query, null, null, null, null, null, null, null);
                webQuery = webQuery.AddQueryOption("$top", 10);


                var webResults = webQuery.Execute();
                System.Windows.Forms.Label lblResults = new System.Windows.Forms.Label();
                StringBuilder searchResult            = new StringBuilder();

                foreach (Bing.WebResult wResult in webResults)
                {
                    richTextBox1.Text += wResult.Url;
                }
            }catch (Exception ex) {
                richTextBox1.Text = "404 Not Found";
            }
        }
        // GET: Cars/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            CarViewModel carVM = new CarViewModel();
            carVM.Car = db.Cars.Find(id);

            if (carVM.Car == null)
            {
                return HttpNotFound();
            }

            HttpResponseMessage response;
            string content = "";

            carVM.Recalls = "";
            carVM.Image = "";


            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://nhtsa.gov/");

                try
                {
                    response = await client.GetAsync("webapi/api/Recalls/vehicle/modelyear/" + carVM.Car.model_year
                        + "/make/" + carVM.Car.make + "/model/" + carVM.Car.model_name + "?format=json");
                    content = await response.Content.ReadAsStringAsync();
                }
                catch (Exception e)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
            }
            carVM.Recalls = JsonConvert.DeserializeObject(content);

            var image = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));

            image.Credentials = new NetworkCredential("accountKey", "kz5K3OZBEC4iMUEENmFOEMrosRzd9msMOkZmw6A6YMw");

            var marketData = image.Composite("image", carVM.Car.model_year + " " + carVM.Car.make + " " + carVM.Car.model_name + " " + carVM.Car.model_trim,
                null, null, null, null, null, null, null, null, null, null, null, null, null).Execute();
            carVM.Image = marketData.First().Image.First().MediaUrl;

            return View(carVM);

        }
        public void FindImageUrlsFor(string searchQuery)
        {
            // Create a Bing container.
            string rootUri       = "https://api.datamarket.azure.com/Bing/Search";
            var    bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));
            // Replace this value with your account key.
            var accountKey = "YourAccountKey";

            // Configure bingContainer to use your credentials.
            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);
            // Build the query.
            var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);

            imageQuery.BeginExecute(_onImageQueryComplete, imageQuery);
        }
Example #14
0
        public void searchNewsByAddress(string address)
        {
            string rootUri = "https://api.datamarket.azure.com/Bing/Search";
            var bingContainer = new BingSearchContainer(new Uri(rootUri));

            string accountKey = App.Current.Resources["AzureAccountKey"] as string;
            bingContainer.UseDefaultCredentials = false;
            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);

            string searchTerm = address + " (site:hir24.hu OR site:origo.hu OR site:index.hu) -site:ingatlanapro.origo.hu -site:forum.index.hu -site:cimkezes.origo.hu -site:admin.index.hu";
            /*Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(searchTerm);
            });*/

            var newsQuery = bingContainer.Web(searchTerm, null, "DisableQueryAlterations", null, null, null, null, null);
            newsQuery.AddQueryOption("$top", 20);
            var result = newsQuery.BeginExecute(_onNewsQueryComplete, newsQuery);
        }
Example #15
0
        public async Task<IHttpActionResult> getCar(int Id)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            string content = "";
            var Car = db.Cars.Find(Id);
            var Recalls = "";
            var Image = "";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://www.nhtsa.gov/");
                try
                {
                    content = await response.Content.ReadAsStringAsync();
                    response = await client.GetAsync("webapi/api/recalls/vehicle/modelyear/" + Car.model_year +
                                                                                     "/make/" + Car.make +
                                                                                     "/model/" + Car.model_name + "?format=json");
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }
            Recalls = content;

            var image = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));

            image.Credentials = new NetworkCredential("accountKey", "uSZdhD53NSOfNv3g0J1hzgObRqsxmFK8iZXUQ3Y2My0");   //"dwmFt1J2rM45AQXkGTk4ebfcVLNcytTxGMHK6dgMreg"
            try
            {
                var marketData = image.Composite(
                    "image",
                    Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim,
                    null, null, null, null, null, null, null, null, null, null, null, null, null
                    ).Execute();

                //Image = marketData.First().Image.First().MediaUrl;
                var Images = marketData.FirstOrDefault()?.Image;
                foreach (var Img in Images)
                {
                    if (UrlCtrl.IsUrl(Img.MediaUrl))
                    {
                        Image = Img.MediaUrl;
                        break;
                    }
                    else
                    {
                        continue;
                    }
               }    
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }
            return Ok(new { car = Car, recalls = Recalls, image = Image });
        }
Example #16
0
        public async Task<IHttpActionResult> GetDetails(CarId id)
        {
            HttpResponseMessage response;
            string content = "";
            var Car = db.Cars.Find(id.id);
            dynamic Recalls;
            var Image = "";

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://www.nhtsa.gov/");
                try
                {
                    response = await client.GetAsync("webapi/api/recalls/vehicle/modelyear/" + Car.model_year +
                                                                                    "/make/" + Car.make +
                                                                                    "/model/" + Car.model_name + "?format=json");
                    content = await response.Content.ReadAsStringAsync();
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }
            // Recalls = JsonConvert.DeserializeObject(content);
            Recalls = content;

            var image = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));

            image.Credentials = new NetworkCredential("accountKey", "uSZdhD53NSOfNv3g0J1hzgObRqsxmFK8iZXUQ3Y2My0");   //"dwmFt1J2rM45AQXkGTk4ebfcVLNcytTxGMHK6dgMreg"
            var marketData = image.Composite(
                "image",
                    Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim,
                    null, null, null, null, null, null, null, null, null, null, null, null, null
                    ).Execute();

            Image = marketData.First().Image.First().MediaUrl;
            return Ok(new { car = Car, recalls = Recalls, image = Image });

        }
Example #17
0
        static void GetTotori(string searchWord, int _page, bool isSafeSearch, SearchEngine engine = SearchEngine.Google)
        {
            var page = _page * 20;
            var urlWord = Uri.EscapeUriString(searchWord);
            int done = 0, fail = 0;
            List<string> totori = new List<string>();
            Console.WriteLine("Page "+_page+" GET Start\nSearch Engine: "+engine.ToString());

            if (engine == SearchEngine.Google)
            {
                #region Google画像検索
                WebClient wc = new WebClient();
                wc.Proxy = null;
                //%E3%83%88%E3%83%88%E3%83%AA
                var isSafeStr = "off";
                if (isSafeSearch)
                    isSafeStr = "on";
                byte[] data = wc.DownloadData("https://www.google.co.jp/search?q=" + urlWord + "&hl=ja&safe=" + isSafeStr + "&sout=1&biw=1920&tbm=isch&sa=N&start=" + page);
                //Console.WriteLine("解析中");
                Encoding enc = Encoding.GetEncoding("Shift_JIS");
                string html = enc.GetString(data);
                var links = html.Split(new string[] { "http://www.google.co.jp/imgres?imgurl=", "&amp;imgrefurl=" }, StringSplitOptions.RemoveEmptyEntries);
                //string[] tototi = new string[30];

                foreach (var item in links)
                {
                    if (item.StartsWith("http") && (item.EndsWith("jpg") || item.EndsWith("png") || item.EndsWith("bmp") || item.EndsWith("gif")))
                    {
                        totori.Add(item);
                        //Console.WriteLine(item);
                    }
                }
                #endregion
            }
            else if (engine == SearchEngine.Bing)
            {
                #region Bing画像検索
                var bing = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/")) {
                        Credentials = new NetworkCredential(bingKey, bingKey)
                };

                var isSafeStr = "Off";
                if (isSafeSearch)
                    isSafeStr = "Moderate";

                var query = bing.Image(searchWord, null, null, isSafeStr, null, null, null, 20, page);
                var results = query.Execute();

                foreach (var result in results)
                {
                    totori.Add(result.MediaUrl);
                }
                #endregion
            }

            Parallel.ForEach(totori, (u) =>
            {
                try
                {
                    var url = new Uri(u);

                    var filePath = Path.Combine(savePath, Path.GetFileName(url.LocalPath));
                    new WebClient().DownloadFile(url, filePath);
                    done++;
                    //Console.WriteLine("downloaded: {0} => {1}", url, filePath);
                }
                catch// (Exception e)
                {
                    fail++;
                    //Console.WriteLine("failed: {0}, {1}", url, e);
                }
            });
            //Console.WriteLine("end");
            Console.WriteLine("Page " + _page + " End");
            Console.WriteLine("Done: " + done + " Error: " + fail);
        }
        void BindResults()
        {
            if (queryText.Length == 0) { return; }

            hdnSHC.Value = queryText.GetHashCode().ToInvariantString();

            //Linq2Bing bing = new Linq2Bing(bingApiId);
            //IQueryable<BaseResult> LinqExpression;

            //if (searchDomain.Length > 0)
            //{
            //    LinqExpression =
            //       (from w in bing.Web
            //       where w.Site == searchDomain && w.Text == queryText
            //        select w).Skip(Offset).Take(pageSize);
            //}
            //else
            //{
            //    LinqExpression =
            //       (from w in bing.Web
            //       where w.Text == queryText
            //        select w).Skip(Offset).Take(pageSize);

            //}

            #if !MONO
            BingSearchContainer bingContainer = new BingSearchContainer(new Uri(WebConfigSettings.BingApiUrl));

            bingContainer.Credentials = new NetworkCredential(bingAccountKey, bingAccountKey);
            var webResults = bingContainer.Web("site:" + searchDomain + " " + queryText,
                null,
                null,
                null,
                null,
                null,
                null,
                pageSize,
                Offset);

            try
            {
                //resultCount = LinqExpression.Web().Count<BaseResult>();
                //rptResults.DataSource = LinqExpression.Web();
                rptResults.DataSource = webResults;
                rptResults.DataBind();
                resultCount = rptResults.Items.Count;

            }
            catch (ArgumentNullException) { } //happens when there are no results

            // unfortunately I have not found a way to find the total number of search hits so
            // we can't use traditional paging but can only do next previous first type paging
            // since we don't know how many total pages there are

            btnNext.Visible = (resultCount >= pageSize);

            if (Offset < pageSize)
            {
                btnFirst.Visible = false;
                btnPrevious.Visible = false;
            }
            else
            {
                btnFirst.Visible = true;
                btnPrevious.Visible = true;
            }

            //if (resultCount > 0)
            //{
            //    rptResults.DataSource = LinqExpression.Web();
            //    rptResults.DataBind();
            //}

            pnlNoResults.Visible = (resultCount == 0);

            #endif
        }
        public string GetAdvice(string query)
        {
            var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/searchweb/"));
            var market = "en-us";

            //client.Credentials = new NetworkCredential("accountKey", "lwc+7icqRrPiLk03xLoYzZ7h75GGRPke1HchZpkpKYc");
            client.Credentials = new NetworkCredential("lwc+7icqRrPiLk03xLoYzZ7h75GGRPke1HchZpkpKYc", "lwc+7icqRrPiLk03xLoYzZ7h75GGRPke1HchZpkpKYc");
            //var marketData = client.Web(query, null, null, null, null, null, null, null).Execute();
            //var marketData = client.Web(query, market, "Moderate", 47.603450, -122.329696, "XLX", "EnableHighlighting", "DisableQueryAlterrations").Execute();
            try
            {
                var marketData = client.Web(query, market, "Moderate", null, null, null, null, null);
                marketData = marketData.AddQueryOption("$top", 10);

                // Run the query and display the results.
                var webResults = marketData.Execute();

                //Label lblResults = new Label();
                StringBuilder searchResult = new StringBuilder();

                foreach (Bing.WebResult wResult in webResults)
                {
                    searchResult.Append(string.Format("<a href={2}>{0}</a><br /> {1}<br /> {2}<br /><br />",
                        wResult.Title,
                        wResult.Url,
                        wResult.Description));

                }
                return searchResult.ToString();
            }
            catch
            {
                return "Exception Occured";
            }
        }
Example #20
0
 public ArticleFinder()
 {
     bingSearchContainer = new BingSearchContainer(new Uri(App_Resources.bingNewsServiceUrl));
     bingSearchContainer.IgnoreMissingProperties = true;
     bingSearchContainer.Credentials = new NetworkCredential(App_Resources.bingUserName, App_Resources.bingKey);
 }
Example #21
0
 /// <summary>
 /// Next: 
 /// download images to file
 /// name according to bird type 
 /// delete bad images in explorer
 /// crop
 /// resize
 /// flip
 /// 
 /// 
 /// </summary>
 /// <param name="args"></param>
 static void Main(string[] args)
 {
     var searches = new NameValueCollection
     {
         {"bluetit", "bluetit"},
         {"coaltit", "coaltit"},
         {"greattit", "greattit"},
         {"longtailedtit", "longtailed tit"},
         {"greenfinch", "greenfinch"},
         {"goldfinch", "european goldfinch"},
         {"chaffinch", "chaffinch"},
         {"blackbirdm", "turdus merula male"},
         {"blackbirdf", "turdus merula female"},
         {"thrush", "song thrush"},
         {"robin", "european robin"},
         {"dunnock", "dunnock"},
         {"nuthatch", "eurasian nuthatch"},
         {"greaterspottedwoodpecker", "greater spotted woodpecker"},
         {"greenwoodpecker", "green woodpecker"},
         {"woodpigeon", "columba palumbus"},
         {"collareddove", "collared dove"},
         {"wren", "eurasian wren"},
         {"magpie", "eurasian magpie"},
         {"starling", "european starling"},
     };
     const string apiKey = "px10eK/V0YPxELtEk4t8CIesrDR90AkoauBbx+lh/s4";
     var searchContainer = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search"))
     {
         Credentials = new NetworkCredential(apiKey, apiKey)
     };
     var webClient = new WebClient();
     while (true)
     {
         Console.WriteLine("Enter search term:");
         var searchTerm = Console.ReadLine();
         if (string.IsNullOrEmpty(searchTerm))
             break;
         Console.WriteLine("Enter file prefix:");
         var filePrefix = Console.ReadLine();
         if (string.IsNullOrEmpty(filePrefix))
             filePrefix = searchTerm;
         var query = searchContainer.Image(searchTerm, null, "en-GB", null, null, null, null);
         query.AddQueryOption("$top", 20);
         Console.WriteLine("Starting search");
         var results = query.Execute();
         if (results == null)
         {
             Console.WriteLine("results == null");
             Console.ReadKey();
             break;
         }
         Console.WriteLine("Top 20 results:");
         if (Directory.Exists(filePrefix))
         {
             Directory.Move(filePrefix, string.Format("{0}-{1}", filePrefix, DateTime.Now.ToString("yyyyMMddTHHmmssfff")));
         }
         Directory.CreateDirectory(filePrefix);
         var i = 1;
         foreach (var result in results.Take(20))
         {
             Console.WriteLine("{0} - {1} [{2}x{3}]", result.Title, result.MediaUrl, result.Height, result.Width);
             var ext = Path.GetExtension(result.MediaUrl);
             try
             {
                 webClient.DownloadFile(result.MediaUrl, Path.Combine(filePrefix, string.Format("{0}-{1}{2}", filePrefix, i++, ext)));
             }
             catch (Exception ex)
             {
                 Console.WriteLine("Exception downloading: " + ex.Message);
             }
         }
         Console.WriteLine();
     }
 }
Example #22
0
        public async Task<IHttpActionResult> GetCar(IdParam id)
        {
            var car = db.Cars.Find(id.id);

            if (car == null)
            {
                return await Task.FromResult(NotFound());
            }

            HttpResponseMessage response;

            var client = new BingSearchContainer(
        	new Uri("https://api.datamarket.azure.com/Bing/search/")
            	);
            client.Credentials = new NetworkCredential("accountKey", "baDOTqrNCHJ38GxTzgc8o7rpbstAS9VG5gYE8kfkHro");
            var marketData = client.Composite(
	        "image",
	        car.model_year + " " + car.make + " " + car.model_name + " " + car.model_trim,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null,
	        null
	        ).Execute();

            var result = marketData.FirstOrDefault();
            var image = result != null ? result.Image : null;
            var firstImage = image != null ? image.FirstOrDefault() : null;
            var mediaUrl = firstImage != null ? firstImage.MediaUrl : null;

            dynamic recalls;
            var temp = car.model_name;
            if(temp.Contains('&'))
            {
                var buildit = temp.Split('&');
                var count = buildit.Count();
                temp = "";
                foreach(var item in buildit)
                {
                    if(count > 1)
                    {
                        temp += item + "And";
                    }
                    else
                    {
                        temp += item;
                    }
                    count--;
                }
            }

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("http://www.nhtsa.gov/");

                try
                {
                    response = await httpClient.GetAsync("webapi/api/Recalls/vehicle/modelyear/"+car.model_year+"/make/"+car.make+"/model/"+temp+"?format=json");
                    recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }

            return Ok(new { car, mediaUrl, recalls });
        }
Example #23
0
        public async Task<IHttpActionResult> GetCar([FromBody]int id)
        {
            var car = _db.Cars.Find(id);
            dynamic recalls = "";
            var image = "";

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://www.nhtsa.gov/");
                try
                {
                    var response = await client.GetAsync("webapi/api/Recalls/vehicle/modelyear/" + car.model_year + "/make/" + car.make + "/model/" + car.model_name + "?format=json");
                    recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }

            var images = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));
            images.Credentials = new NetworkCredential("accountKey", 
                ConfigurationManager.AppSettings["bing"]);
            var marketData = images.Composite(
                "image",
                car.model_year + " " + car.make + " " + car.model_name + " " + car.model_trim,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null
                ).Execute();

            image = marketData?.FirstOrDefault()?.Image.FirstOrDefault()?.MediaUrl;

            return Ok(new {car,image,recalls});
        }
    static void updateArticlesForPlayer(string name, string id)
    {
        string topics        = name;
        string playerID      = id;
        int    numOfArticles = 15;

        string[]      topicsArray   = topics.Split('_');
        string        results       = "";
        List <string> resultTitles  = new List <string>();
        List <string> articleBodies = new List <string>();
        List <string> urls          = new List <string>();

        try
        {
            string AccountKey = "W9xfglp9hpPxpxgoSsWqXzu7k6f+bqUA9Z+S7QHwwsg";
            //For each user topic
            foreach (string query in topicsArray)
            {
                // Root URL for bing search API
                string rootUrl = "https://api.datamarket.azure.com/Bing/Search";
                //Create a Bing Container per API specifications
                var bingContainer = new Bing.BingSearchContainer(new Uri(rootUrl));
                // The market location to use.
                string location = "en-us";
                // Add credentials
                bingContainer.Credentials = new NetworkCredential(AccountKey, AccountKey);
                // Create the search, getting top 5 results.
                var newsQuery =
                    bingContainer.News(query, null, location, null, null, null, null, null, null);
                newsQuery = newsQuery.AddQueryOption("$top", numOfArticles);
                // Execute search.
                var newsResults = newsQuery.Execute();
                //Console.WriteLine("Number of articles: " + newsResults.Count());
                //Add results to list.
                foreach (var result in newsResults)
                {
                    string article = getArticleBody(result.Url);
                    if (!article.Equals("ERROR"))
                    {
                        articleBodies.Add(article);
                        resultTitles.Add(result.Title);
                        urls.Add(result.Url);
                    }
                    else
                    {
                        numOfArticles--;
                    }
                }
            }
        }
        //Error running the query.
        catch
        {
            results += "Error Processing Request. Please try again";
        }

        Console.WriteLine("Num of articles: {0}", numOfArticles);
        Console.WriteLine("Num of article bodies: {0}", articleBodies.Count);


        //Gets the unique words from each of the titles and stores them in a list
        //Also get number of words in each title
        List <string> words = new List <string>();

        int[] numOfWords = new int[numOfArticles];
        for (int i = 0; i < numOfArticles; i++)
        {
            string[] sArray = articleBodies[i].Split(' ');
            numOfWords[i] = sArray.Length;
            foreach (string s2 in sArray)
            {
                if (!words.Contains(s2))
                {
                    words.Add(s2);
                    //Console.WriteLine(s2);
                }
            }
        }

        //Stores the frequency of the occurences of each word
        int[,] frequencyArray = new int[numOfArticles, words.Count];
        Array.Clear(frequencyArray, 0, frequencyArray.Length);

        for (int i = 0; i < numOfArticles; i++)
        {
            string[] sArray = articleBodies[i].Split(' ');
            foreach (string s2 in sArray)
            {
                //Location of the word in the array of words
                int j = words.IndexOf(s2);
                frequencyArray[i, j]++;
            }
        }

        //Normalized Frequency Array
        double[,] nFrequencyArray = new double[numOfArticles, words.Count];
        for (int i = 0; i < numOfArticles; i++)
        {
            for (int j = 0; j < words.Count; j++)
            {
                nFrequencyArray[i, j] = ((double)frequencyArray[i, j]) / ((double)numOfWords[i]);
            }
        }

        //Inverse Document Frequency
        double[] idf = new double[words.Count];
        for (int i = 0; i < words.Count; i++)
        {
            //How many documents the current word appears in
            int appearances = 0;
            for (int j = 0; j < numOfArticles; j++)
            {
                if (frequencyArray[j, i] > 0)
                {
                    appearances++;
                }
            }

            idf[i] = (double)(1 + Math.Log((double)numOfArticles / (double)appearances));
        }

        //TF-IDF
        double[,] tfIDF = new double[numOfArticles, words.Count];
        for (int i = 0; i < numOfArticles; i++)
        {
            for (int j = 0; j < words.Count; j++)
            {
                tfIDF[i, j] = idf[j] * nFrequencyArray[i, j];
                //Console.WriteLine(tfIDF[i, j]);
            }
        }

        //The location in the title list of each chosen article. The first one is always 0.
        int[] selectedArticles = { -1, -1, -1, -1 };

        //Calculate cosine similarity between all articles, to see which ones are the least similar
        //int leastSimilarArticle = 0;
        //double smallestAngle = 1;
        double[,] cosineArray = new double[numOfArticles, numOfArticles];
        for (int k = 0; k < numOfArticles; k++)
        {
            for (int i = 0; i < numOfArticles; i++)
            {
                double dotProduct = 0;
                double length1    = 0;
                double length2    = 0;

                for (int j = 0; j < words.Count; j++)
                {
                    dotProduct += (tfIDF[k, j] * tfIDF[i, j]);
                    length1    += Math.Pow(tfIDF[k, j], 2);
                    length2    += Math.Pow(tfIDF[i, j], 2);
                }

                double cosine = dotProduct / (Math.Pow(length1, .5) * Math.Pow(length2, .5));
                cosineArray[k, i] = Math.Round(cosine, 6);
            }
        }

        //Print out cosine array
        System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Sumbhav\\Documents\\Thesis\\cosine.txt");
        for (int i = 0; i < numOfArticles; i++)
        {
            for (int j = 0; j < numOfArticles; j++)
            {
                file.Write(cosineArray[j, i].ToString("0.000000") + "\t\t\t");
            }

            file.WriteLine();
        }

        file.WriteLine("\n");


        //Get the average similarity of each article to the other articles
        double[] averageSimilarity = new double[numOfArticles];
        Array.Clear(averageSimilarity, 0, averageSimilarity.Length);

        for (int i = 0; i < numOfArticles; i++)
        {
            for (int j = 0; j < numOfArticles; j++)
            {
                averageSimilarity[i] += cosineArray[j, i];
            }

            averageSimilarity[i] /= numOfArticles;
            file.WriteLine(averageSimilarity[i]);
        }

        //Find the mean and standard deviation of the average similarities
        double mean  = averageSimilarity.Average();
        double stDev = StandardDeviation(averageSimilarity);

        //Current selected article
        int selectedArticle = -1;

        //Find and select the articles with a similarity score closest to -2, -1, 0, and 1 standard deviation(s) from the mean
        for (int i = -2; i <= 1; i++)
        {
            double compareValue = mean + i * stDev;
            //Distance between the compare value and the similarity score of the article being examined
            double distance = 1.0;
            for (int j = 0; j < numOfArticles; j++)
            {
                if (Math.Abs(averageSimilarity[j] - compareValue) < distance)
                {
                    distance        = Math.Abs(averageSimilarity[j] - compareValue);
                    selectedArticle = j;
                }
            }

            //Add selected article to final selection of articles
            selectedArticles[i + 2] = selectedArticle;
        }

        file.WriteLine();

        foreach (int i in selectedArticles)
        {
            file.WriteLine(resultTitles[i]);
            file.WriteLine(urls[i] + "\n");
        }


        file.WriteLine("\n");

        foreach (string s in resultTitles)
        {
            file.WriteLine(s);
        }
        file.Close();

        //MySql connection set up
        MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();

        conn_string.Server   = "sethia.cosfzwdmywyo.us-west-2.rds.amazonaws.com";
        conn_string.UserID   = "cheetobuv10";
        conn_string.Password = "******";
        conn_string.Database = "NBAbase";
        MySqlConnection l_DBConn = new MySqlConnection();

        l_DBConn.ConnectionString = conn_string.ToString();

        //Open connection to DB (already open based on where it's being called)
        //l_DBConn.Open();

        //Add articles to database
        MySqlCommand command;

        for (int i = 0; i < selectedArticles.Length; i++)
        {
            command             = l_DBConn.CreateCommand();
            command.Connection  = l_DBConn;
            command.CommandText = "replace into Articles SET playerID='" + playerID + "', articleNumber=" + (i + 1) + ", url='" + urls[selectedArticles[i]] + "', title='" + resultTitles[selectedArticles[i]] + "'";
            command.ExecuteNonQuery();
        }

        //Close connection to DB
        l_DBConn.Close();
        Console.WriteLine("Database updated with articles");

        Console.ReadLine();
    }
Example #25
0
        public async Task<IHttpActionResult>GetCar(int id)
        {
            var car = db.Cars.Find(id);
            if (car == null)
            {
                return await Task.FromResult(NotFound());
            }

            HttpResponseMessage response;

            var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/")
       );
            client.Credentials = new NetworkCredential("accountKey", "JDNjFEYyxMGlhlX66nh3S6hQ8aQVOLmI8LJO4QQgdVE");
            var marketData = client.Composite(
                "image",
                $"{car.model_year} {car.make} {car.model_name} {car.model_trim}",
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null
                ).Execute();

            var imageUrl = marketData.FirstOrDefault()?.Image?.FirstOrDefault()?.MediaUrl;

            //var result = marketData.FirstOrDefault();
            //var image = result != null ? result.Image : null;
            //var firstImage = image != null ? image.FirstOrDefault() : null;
            //var imageUrl = firstImage != null ? firstImage.MediaUrl : null;


            dynamic recalls;
            using (var httpclient = new HttpClient())
            {
                httpclient.BaseAddress = new Uri("Http://www.nhtsa.gov/");

                try
                {                                          
                    response = await httpclient.GetAsync($"webapi/api/Recalls/vehicle/modelyear/{car.model_year}/make/{car.make}/model/{car.model_name}?format=json");
                    recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());           
                }

                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }

            return Ok(new { car, imageUrl, recalls });
        } 
 public BingSearchApi()
 {
     Container = new BingSearchContainer(new Uri(rootUrl));
     Container.Credentials = new NetworkCredential(accountKey, accountKey);
 }
Example #27
0
        private async Task<DataFeed> EnrichWithImagesAsync(DataFeed feed)
        {
            const string key = "ZvD71NLFp4EFiActP24HNCNHey1r4m64bwMQPTh8AZg";

            if (!string.IsNullOrEmpty(feed.Image))
            {
                return feed;
            }
                
            if (feed.Concepts == null)
            {
                return null;
            }

            var bingContainer = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/v1/"))
            {
                Credentials = new NetworkCredential(key, key)
            };

            var imagesQuery = bingContainer.Image(string.Join(" ", feed.Concepts), null, null, "Moderate", null, null, "Size:Large");
            IEnumerable<ImageResult> imagesResults = await 
                Task<IEnumerable<ImageResult>>.Factory.FromAsync(imagesQuery.BeginExecute, imagesQuery.EndExecute, null);

            ImageResult image = imagesResults.FirstOrDefault();
            if (image != null)
            {
                feed.Image = image.MediaUrl;
                return feed;
            }

            return null;
        }
Example #28
0
        private static async void Bot_MessagedReceived(object sender, MessageEventArgs e)
        {
            if (e.Message.IsAuthor) return;

            //help cmd
            string[] cmds = {"!help", "!ping", "!yt <search term>", "!img <search term>", "!8ball <question>", "!roll", "!bass" };
            if (e.Message.Text.ToLower().Equals(prefix + "help"))
            {
                string cmdStringer = e.User.Mention + "\n__**Commands:**__";
                foreach (string s in cmds)
                {
                    cmdStringer += "\n\t- " + s;
                }
                await e.Channel.SendMessage(cmdStringer);
            }
            //ping cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "ping"))
            {
                await e.Channel.SendMessage(e.User.Mention + " Pong");
            }
            //yt cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "yt") && e.Message.Text.IndexOf(prefix) == 0)
            {
                ytSearch = e.Message.Text.Remove(0, 3);
                if (String.IsNullOrWhiteSpace(ytSearch))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {
                    new Program().YoutubeMethod().Wait();
                    await e.Channel.SendMessage(e.User.Mention + " " + ytResult);
                }
            }
            //image cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "img") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string searchTerm = e.Message.Text.Remove(0, 5);
                if (String.IsNullOrWhiteSpace(searchTerm))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {

                    var bing = new BingSearchContainer(
                        new Uri("https://api.datamarket.azure.com/Bing/Search/"))
                    { Credentials = new NetworkCredential(bingSearchKey, bingSearchKey) };

                    var query = bing.Image(searchTerm, "EnableHighlighting", "en-US", "Moderate", null, null, null);
                    var results = query.Execute();

                    ImageResult[] aResults = results.ToArray<ImageResult>();

                    int index = r.Next(0, aResults.Length);
                    ImageResult item = aResults[index];

                    await e.Channel.SendMessage(e.User.Mention + " " + item.MediaUrl);
                }
            }
            //8ball cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "8ball") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string question = e.Message.Text.Remove(0, 6);
                if (string.IsNullOrWhiteSpace(question))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a question attached to it! Use \"!help\" for assistance.");
                    return;
                }

                string[] responses = {"Not likely.", "More than likely"};
                int index = r.Next(0, responses.Length);
                await e.Channel.SendMessage(e.User.Mention + " " + responses[index]);
            }
            //roll cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "roll"))
            {
                int face = r.Next(1, 7);
                await e.Channel.SendMessage(e.User.Mention + " Rolled a " + face);
                switch (face)
                {
                    case 1:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                    case 2:
                        await e.Channel.SendFile("Assets/Dice/dice2.png");
                        break;
                    case 3:
                        await e.Channel.SendFile("Assets/Dice/dice3.png");
                        break;
                    case 4:
                        await e.Channel.SendFile("Assets/Dice/dice4.png");
                        break;
                    case 5:
                        await e.Channel.SendFile("Assets/Dice/dice5.png");
                        break;
                    case 6:
                        await e.Channel.SendFile("Assets/Dice/dice6.png");
                        break;
                    default:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                }
            }
            //bass cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "bass"))
            {
                if (e.User.VoiceChannel != null)
                {
                    //set up
                    bot.UsingAudio(x =>
                    {
                        x.Mode = AudioMode.Outgoing;
                    });

                    //joining a channel
                    var voiceChannel = bot.FindServers("Bot Testing Place").FirstOrDefault().VoiceChannels.FirstOrDefault();
                    _vClient = await bot.GetService<AudioService>().Join(voiceChannel);

                    SendAudio("Assets/Audio/bass.mp3");


                }
                else
                {
                    await e.Channel.SendMessage(e.User.Mention + " You must be in a voice room to do this. Use \"!help\" for assistance.");
                }
            }

        }
Example #29
0
 public BingSearch(string root)
 {
     _rootUri = root;
     _bingContainer = new Bing.BingSearchContainer(new Uri(_rootUri));
     _bingContainer.Credentials = new NetworkCredential(_accountKey, _accountKey);
 }
Example #30
-6
        public List<NewsResult> Query(string company)
        {
            string market = "en-us";
            string options = null;
            string adult = null;
            double? lat = null;
            double? lon = null;
            string newLocation = null;
            string newsCategory = "rt_Business";
            string sortBy = "Date";

            Container = new BingSearchContainer(new Uri(rootUrl));
            Container.Credentials = new NetworkCredential(accountKey, accountKey);

            var query = Container.News(company, options, market, adult, lat, lon, newLocation, newsCategory, sortBy);

            List<NewsResult> totalSearchList = new List<NewsResult>();

            for (int i = 0; i < 4; i++)
            {
                int skip = totalSearchList.Count();
                var offsetQuery = query.AddQueryOption("$skip", skip.ToString());
                var result = offsetQuery.Execute().ToList();
                totalSearchList.AddRange(result);
            }

            return totalSearchList;
        }