/// <summary>
        ///     Searches Bing using official Microsoft Bing C# API.
        /// </summary>
        /// <param name="query">Search query</param>
        private void BingSearch(string query)
        {
            // new container object
            var bingContainer = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));

            // the next line configures the bingContainer to use your credentials.
            bingContainer.Credentials = new NetworkCredential(AccountKey, AccountKey);

            // now we can build the query
            var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);

            LogWrite("\r\nStarting search...");

            // Run the search
            var imageResults = imageQuery.Execute();

            LogWriteLine("Done.\r\n");

            LogWriteLine("Starting download:\r\n");

            // Go through list and download everything
            foreach (var result in imageResults)
            {
                Thread thread =
                    new Thread(() => SaveImage(new ImageObject(result.Title, DownloadBitmap(result.MediaUrl))));
                thread.Start();
            }

            // LogWriteLine("\r\nDone!\r\n");
        }
예제 #2
0
        public static Collection <PartialMatche> Search(string strSearch)
        {
            if (string.IsNullOrWhiteSpace(strSearch))
            {
                return(null);
            }

            BingSearchContainer objService = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));

            objService.Credentials = new NetworkCredential(AppId, AppId);
            DataServiceQuery <ImageResult> imagequery = objService.Image(strSearch, "DisableLocationDetection",
                                                                         CultureInfo.CurrentCulture.Name, "Off", null, null, null);

            IEnumerable <ImageResult> imagesList = imagequery.Execute();

            if (imagesList != null)
            {
                List <ImageResult> images = imagesList.ToList();
                return(CreatePartialMatch(images));
            }
            else
            {
                return(null);
            }
        }
 public BingSearchService(string apiKey)
 {
     _bingContainer = new BingSearchContainer(new Uri(ServiceUrl))
     {
         Credentials = new NetworkCredential(apiKey, apiKey)
     };
 }
예제 #4
0
        public async Task <IHttpActionResult> getCar(idClass id)
        {
            HttpResponseMessage response;
            string content = "";
            var    Car     = db.Cars.Find(id.id);
            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));
                }
            }

            dynamic Recalls = JsonConvert.DeserializeObject(content);

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

            image.Credentials = new NetworkCredential("accountKey", "s8cUIpKPWJ609E7VqtBbx9HNdRp9Z2NbUne/HyPgxbQ");

            var marketData = image.Composite(
                "image",
                Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim + " " + "NOT ebay",
                null, null, null, null, null, null, null, null, null, null, null, null, null).Execute();

            var Images = marketData.FirstOrDefault().Image;

            foreach (var Img in Images)
            {
                if (UrlCtrl.isUrl(Img.MediaUrl))
                {
                    Image = Img.MediaUrl;
                    break;
                }
                else
                {
                    continue;
                }
            }

            if (string.IsNullOrWhiteSpace(Image))
            {
                Image = "/images/no-image.png";
            }

            return(Ok(new { car = Car, recalls = Recalls, image = Image }));
        }
예제 #5
0
        public void backgroundWorkerBing_DoWork(object sender, DoWorkEventArgs e)
        {
            string targetImageClass = MatchingHelper.matchedClass;

            //check if it is a reranking
            if (toRerank)
            {
                double[] rerankedImages = MatchingHelper.SearchSimilar(MatchingHelper.rerankingImageName, numberOfImagesToRetrieve);
                backgroundWorkerBing.ReportProgress(50, rerankedImages);
                return;
            }

            //check if the class of the image is covered by our similarity matching, then retrieve from our own database
            for (int catNum = 0; catNum < 20; catNum++)
            {
                string command = VoiceControlHelper.voiceCommands[catNum];
                if (targetImageClass == command)
                {
                    toRerank = true;
                    List <double> randomChosedImages = new List <double>();
                    Random        randomGen          = new Random();
                    for (int k = 0; k < numberOfImagesToRetrieve; k++)
                    {
                        double imageNum = 0;
                        do
                        {
                            imageNum = catNum * 25 + randomGen.Next(1, 26);
                        } while (randomChosedImages.Contains(imageNum));
                        randomChosedImages.Add(imageNum);
                    }
                    backgroundWorkerBing.ReportProgress(50, randomChosedImages.ToArray());
                    return;
                }
            }

            //to retrieve images from the network if the target image class is not covered by our similarity matrix
            toRerank = false;
            // this is the service root uri for the Bing search service
            var serviceRootUri = new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1");

            // this is the Account Key generated for this app
            var accountKey = "TG4vg/aL3DjSYJVl25mmyPVHhCCLCuObnR26ggQZhWc=";

            // the BingSearchContainer gives us access to the Bing services
            BingSearchContainer bsc = new BingSearchContainer(serviceRootUri);

            // Give the BingSearchContainer access to the subscription
            bsc.Credentials = new NetworkCredential(accountKey, accountKey);

            // building the query
            var imageQuery = bsc.Image(targetImageClass, null, null, "Strict", null, null, "Size:Medium");

            IEnumerable <ImageResult> imageResults = imageQuery.Execute();

            backgroundWorkerBing.ReportProgress(99, imageResults);
        }
예제 #6
0
        //public IEnumerable<Car> GetAllProducts()
        //{
        //    return products;
        //}

        public async Task <IHttpActionResult> GetProduct(int?id)
        {
            //var idParam = new SqlParameter("@id", id);

            //var retval = db.Database.SqlQuery<Car>(
            //"EXEC GetCar @id", idParam
            //).ToList();
            if (id == null)
            {
                return(BadRequest());
            }
            HttpResponseMessage response;
            string  content = "";
            Car     car     = new Car();
            dynamic Recalls = "";
            string  Image   = "";

            car = db.Cars.Find(id);
            if (car == null)
            {
                return(NotFound());
            }

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://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 = content;
            //Recalls = JsonConvert.DeserializeObject(content);
            var image = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));

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

            var marketData = image.Composite(
                "image",                                                                       // type of search
                car.model_year + " " + car.make + " " + car.model_name + " " + car.model_trim, // query
                null, null, null, null, null, null, null, null, null, null, null, null, null).Execute();

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

            return(Ok(new { Car = car, Recalls = Recalls, Image = Image }));
        }
예제 #7
0
        /// <summary>
        /// Returns car details including recall data and an image url for the given id.
        /// </summary>
        /// <param name="Id">Id of the Car</param>
        /// <returns>Returns an object(car,recalls,image) that contains car details, recall info and image url</returns>

        public async Task <IHttpActionResult> GetInfo(int id)
        {
            HttpResponseMessage response;
            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
                {
                    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));
                }
            }
            dynamic Recalls = JsonConvert.DeserializeObject(content);

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

            image.Credentials = new NetworkCredential("accountKey", "qZQohZcFCgVtaM/LA7T+zQyJiQiio4LDnVrIbRl04No=");
            var marketData = image.Composite(
                "image",
                Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim,
                //$"{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 ImageList = marketData.FirstOrDefault()?.Image;

            Image = ImageList.FirstOrDefault()?.MediaUrl;
            return(Ok(new { car = Car, recalls = Recalls, image = Image }));
        }
예제 #8
0
        /// <summary>
        /// Event Handler for the Search Button
        /// </summary>
        private async void Search_Click(object sender, RoutedEventArgs e)
        {
            string accountKey = "<Account Key>";

            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();
        }
예제 #9
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.First().Image.First().MediaUrl;

            var t = marketData.FirstOrDefault();
            var x = t != null?t.Image.FirstOrDefault() : null;

            var q = x != null ? x.MediaUrl : null;

            return(Ok(new { car, image = q, recalls }));
        }
예제 #10
0
        // GET: Cars/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            CarsViewModels carVM = new CarsViewModels();

            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", "5u/0CzVmYrTKDOjlxPePfPkh/G8llMIfVJ7QC/oNEvQ");

            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));
        }
예제 #11
0
        public async Task<IHttpActionResult> Cars_by_Id(int id) {

            var car = db.Car.Find(id);

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

            var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));
            client.Credentials = new NetworkCredential("accountKey", "o+nYHPyZpmhku+bXtDn0AFRZ79Jnxd4KS/QkoHd3B3E");
            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 imageUrl = firstImage != null ? firstImage.MediaUrl : "~/Images/img_not_found.jpg";

            dynamic recalls;

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

                try {
                    var 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 });
        }
예제 #12
0
 private static void InitBingSearch()
 {
     if (CurrentBingId < bingAppIds.Count)
     {
         bingSearch =
             new Bing.BingSearchContainer(
                 new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1"));
         var appId = bingAppIds[CurrentBingId];
         bingSearch.Credentials = new NetworkCredential(appId, appId);
     }
     else
     {
         bingSearch = null;
         Logger.Exception(new Exception("bingSearch == null"), "bingSearch");
     }
 }
예제 #13
0
        public static Hashtable SearchPortrait(string strSearch, bool usePartialMatche)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(strSearch))
                {
                    return(null);
                }

                Task.Factory.StartNew(() => Util.NotifyEvent("Provider: Bing Portrait : " + strSearch));

                BingSearchContainer objService = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));
                objService.Credentials = new NetworkCredential(AppId, AppId);
                DataServiceQuery <ImageResult> imagequery = objService.Image(strSearch, "DisableLocationDetection",
                                                                             null, "Off", null, null, @"Style:Photo+Face:Face+Aspect:Tall");

                if (imagequery != null)
                {
                    List <ImageResult> images = imagequery.Execute().ToList();

                    if (usePartialMatche == true)
                    {
                        return(ShowPartialMatch(images));
                    }
                    else if (images.Any())
                    {
                        Hashtable objResults = new Hashtable();
                        objResults.Add("Image", images[0].MediaUrl);
                        return(objResults);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Util.LogException(ex, strSearch);
                return(null);
            }
        }
예제 #14
0
파일: Program.cs 프로젝트: 9nick9/MRPCode
        static void FindWebsites(string connectionString, string accountKey, int findTwitter)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;

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

                string getCompaniesFromDB = "SELECT ID, Name from Company";
                cmd.CommandText = getCompaniesFromDB;

                SqlDataReader            reader           = cmd.ExecuteReader();
                Dictionary <string, int> nameIDDictionary = new Dictionary <string, int>();

                while (reader.Read())
                {
                    nameIDDictionary.Add((string)reader["Name"], (int)reader["ID"]);
                }

                reader.Close();

                string column = "Website";
                if (findTwitter == 1)
                {
                    column = "Twitter";
                }

                foreach (KeyValuePair <string, int> kvp in nameIDDictionary)
                {
                    string url = SearchBing(kvp.Key, container, findTwitter == 1);
                    Console.Out.WriteLine($"The value for {kvp.Key} is {url}");
                    if (url.Length > 150)
                    {
                        continue;
                    }

                    string updateWebsiteSQL = $"UPDATE Company SET {column} = '{url}' Where ID = {kvp.Value}";
                    cmd.CommandText = updateWebsiteSQL;

                    cmd.ExecuteNonQuery();
                }
            }
        }
예제 #15
0
파일: Program.cs 프로젝트: 9nick9/MRPCode
        static string SearchBing(string company, BingSearchContainer bingSearch, bool needTwitter = false)
        {
            if (needTwitter)
            {
                company = "twitter: " + company;
            }

            DataServiceQuery <WebResult> result = bingSearch.Web(company, "DisableLocationDetection", null, "en-US", null, null, null, null);
            WebResult firstResult = result.FirstOrDefault();

            if (needTwitter)
            {
                return(ParseOutTwitterHandle(firstResult));
            }

            if (firstResult != null)
            {
                return(firstResult.Url);
            }

            return("");
        }
예제 #16
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);
        }
예제 #17
0
    static async Task MainAsync()
    {
        var accountKey = Environment.GetEnvironmentVariable("CUSTOMCONNSTR_BingSearchAccountKey");

        if (accountKey == null)
        {
            var arg = Environment.GetCommandLineArgs().Where(a => a.StartsWith("/bing:")).FirstOrDefault();
            if (arg != null)
            {
                accountKey = arg.Substring(6).Trim("'\"".ToCharArray());
            }
        }

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

        bing.Credentials = new NetworkCredential("accountKey", accountKey);
        var q = bing
                .Image("big noses", null, null, null, null, null, "Size:Width:1000")
                .AddQueryOption("$top", 10);
        var r = await Task.Run(() => q.Execute());

        Process.Start(r.First().MediaUrl);
    }
예제 #18
0
        private async Task <ActionResult> InternalSearch(string q)
        {
            IEnumerable <SearchResult> viewModel = new List <SearchResult>();

            if (String.IsNullOrWhiteSpace(q))
            {
                return(View(viewModel));
            }

            string query = HttpUtility.UrlDecode(q);

            int queryId = 0;
            IEnumerable <SearchResult> boosts = new List <SearchResult>();

            // Lookup the query cache in the database.
            var querySql        = @"
select coalesce(PrimaryQueryId, Id) as QueryId from dbo.resQueries where Query = @Query;
";
            var boostsSql       = @"
select Domain, Boost as UserBoost, 0 as GlobalBoost from dbo.resSourceBoosts where UserId = @UserId
union all
select Domain, 0 as UserBoost, Boost as GlobalBoost from dbo.resSourceBoosts where UserId = 0;
";
            var globalBoostsSql = @"
select Domain, 0 as UserBoost, Boost as GlobalBoost from dbo.resSourceBoosts where UserId = 0;
";
            var isAuthenticated = User.Identity.IsAuthenticated;

            using (var connection = await DapperHelper.GetOpenConnectionAsync())
            {
                queryId = (await connection.QueryAsync <int>(querySql, new { Query = query })).SingleOrDefault();

                if (queryId != 0)
                {
                    // We have found a cached copy of the query.
                }

                boosts = await connection.QueryAsync <SearchResult>(
                    isAuthenticated?boostsSql : globalBoostsSql,
                    isAuthenticated?new { UserId = this.GetUserId() } : null);
            }

            // Hit Bing
            if (queryId == 0)
            {
                var client = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/"));
                client.Credentials = new NetworkCredential("accountKey", "5YaDOM5e+yVu5m0YTagnldui36VI5px9STCbUrpZJCI");

                // API Reference +http://msdn.microsoft.com/en-us/library/dd250882.aspx
                // Bing Query Language +http://msdn.microsoft.com/en-us/library/ff795667.aspx
                var bingQuery = client.Composite(
                    "web",                      //"web+video+relatedsearch+spell", // Sources
                    query,                      //	"ireglr veb (site:englishpage.com OR site:esl.about.com)", // Query
                    "DisableLocationDetection", // Options
                    null,                       //"DisableHostCollapsing", // WebSearchOptions
                    "en-US",                    // Market
                    "Strict",                   // Adult
                    null,                       // Latitude
                    null,                       // Longitude
                    null,                       // WebFileType
                    null,                       // ImageFilters
                    null,                       // VideoFilters
                    "Relevance",                // VideoSortBy
                    null,                       // NewsLocationOverride
                    null,                       // NewsCategory
                    null                        // NewsSortBy
                    );

                //var bingResults = bingQuery.Execute();
                // TPL and Traditional .NET Framework Asynchronous Programming +http://msdn.microsoft.com/en-us/library/dd997423(v=vs.110).aspx
                var bingResults = await Task <IEnumerable <ExpandableSearchResult> > .Factory.FromAsync(bingQuery.BeginExecute, bingQuery.EndExecute, null);

                var webResults = (bingResults as QueryOperationResponse <ExpandableSearchResult>).First().Web;

                // Simplify DisplayUrl. Keep only the main domain part.
                var results = webResults
                              .Select((i, idx) =>
                {
                    var url = i.DisplayUrl;
                    var ix  = url.IndexOf("://");    // DisplayUrl can contain an "https://".
                    url     = ix > 0 ? url.Substring(ix + 3) : url;
                    url     = url.StartsWith("www.") ? url.Substring(4) : url;
                    ix      = url.IndexOf('/');
                    url     = ix > 0 ? url.Substring(0, ix) : url;
                    return(new SearchResult {
                        Domain = url, Url = i.Url, OriginalPosition = idx
                    });
                });

                // Sort the results according to the boost value. Some results may have a boost counterpart, some not.
                // And vice versa, some boosts may have no result to apply to. We filter out such groups, where there is no Url, i.e. no result.
                viewModel = results
                            .Concat(boosts)
                            .GroupBy(i => i.Domain)
                            //.Where(i => i.Any(j => !String.IsNullOrEmpty(j.Url)))
                            .Select(i =>
                {
                    var res = i.FirstOrDefault(j => !String.IsNullOrEmpty(j.Url));
                    return(res != null
                                ? new SearchResult
                    {
                        Domain = i.Key,
                        //Url = i.Select(j => j.Url).FirstOrDefault(j => !String.IsNullOrEmpty(j)),
                        Url = res.Url,
                        //OriginalPosition = i.Sum(j => j.OriginalPosition),
                        OriginalPosition = res.OriginalPosition,
                        UserBoost = i.Sum(j => j.UserBoost),
                        GlobalBoost = i.Sum(j => j.GlobalBoost),
                    }
                                : null);
                })
                            .Where(i => i != null)
                            .OrderByDescending(i => i.UserBoost)
                            .ThenByDescending(i => i.GlobalBoost)
                            .ThenBy(i => i.OriginalPosition);
            }

            return(View(viewModel));
        }
예제 #19
0
        public async Task<IHttpActionResult> getCar(idClass id)
        {
            HttpResponseMessage response;
            string content = "";
            var Car = db.Cars.Find(id.id);
            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);
                }
            }

            dynamic Recalls = JsonConvert.DeserializeObject(content);

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

            image.Credentials = new NetworkCredential("accountKey", "s8cUIpKPWJ609E7VqtBbx9HNdRp9Z2NbUne/HyPgxbQ");

            var marketData = image.Composite(
               "image",
               Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim + " " + "NOT ebay",
               null, null, null, null, null, null, null, null, null, null, null, null, null).Execute();

              var Images = marketData.FirstOrDefault().Image;

            foreach(var Img in Images)
            {
                if(UrlCtrl.isUrl(Img.MediaUrl))
                {
                    Image = Img.MediaUrl;
                    break;
                }
                else
                {
                    continue;
                }
            }

            if(string.IsNullOrWhiteSpace (Image))
            {
                Image = "/images/no-image.png";
            }

            return Ok(new { car = Car, recalls = Recalls, image = Image });
        }
예제 #20
0
        public async Task<IHttpActionResult> GetCar(IdParam id) //(Selected selected)
        {
            HttpResponseMessage response;
            string content = "";
            var Car = db.Cars.Find(id.id); //(Selected selected) passes in model, make, 
            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);

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

            image.Credentials = new NetworkCredential("accountKey", "/8RvXOXJ4fcq5pAnNMdOtiueBjVHcWUUFAr8ZhHPJsI");
            var marketData = image.Composite(
                "image",
                Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim + " " + "NOT ebay",
                null,
                null,
                null,
                "Moderate",
                null,
                null,
                null,
                "Size:Large+Style:Photo",
                null,
                null,
                null,
                null,
                null
                ).Execute();

            var Images = marketData.FirstOrDefault()?.Image;
            foreach (var Img in Images)
            {
                
                if (UrlCtrl.IsUrl(Img.MediaUrl))
                {
                    Image = Img.MediaUrl;
                    break;
                } else
                {
                    continue;
                }

            }

            if (string.IsNullOrWhiteSpace(Image))
            {
                Image = "../img/car404.jpg";
            }

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

        }
예제 #21
0
    public static List <mySearch.SearchResult> GetSearchResult(string keyword, string knowledgeid, string course)
    {
        string rootUrl = "https://api.datamarket.azure.com/Bing/Search";
        BingSearchContainer bingContainer = new BingSearchContainer(new Uri(rootUrl));
        string market = "zh-cn";

        bingContainer.Credentials = new NetworkCredential(AccountKey, AccountKey);
        if (course == "math1")
        {
            keyword = keyword + " 小学";
        }
        if (course == "math2")
        {
            keyword = keyword + " 初中";
        }
        var webQuery = bingContainer.Web(keyword, null, null, market, "Strict", null, null, null);

        webQuery = webQuery.AddQueryOption("$top", 50);
        var webResults = webQuery.Execute();

        List <SearchResult> myresults = new List <SearchResult>();

        foreach (var result in webResults)
        {
            SearchResult sr = new SearchResult();
            sr.Title       = result.Title;
            sr.URL         = result.Url;
            sr.URLID       = "0";
            sr.Description = result.Description;
            sr.isRemove    = false;
            myresults.Add(sr);
        }
        myresults = FillterSearchResult(myresults);

        List <MF_URL>     URLs  = new List <MF_URL>();
        ORMQuery <MF_URL> Query = new ORMQuery <MF_URL>();

        URLs = Query.Query(MF_URL.M_KnowledgeID + " = ('" + knowledgeid + "')").ToList();
        URLs = URLs.OrderByDescending(p => p.Count).ToList();

        List <SearchResult> results = new List <SearchResult>();

        foreach (MF_URL item in URLs)
        {
            if (results.Count < 5)
            {
                SearchResult sr = new SearchResult();
                sr.URLID       = item.URLID.ToString();
                sr.URL         = item.URL;
                sr.Title       = item.Title;
                sr.Description = item.Description;
                results.Add(sr);
            }
        }
        foreach (SearchResult item in myresults)
        {
            if (results.Count == 10)
            {
                break;
            }
            if (results.Where(p => p.URL == item.URL).ToList().Count == 0)
            {
                results.Add(item);
            }
        }
        return(results);
    }
예제 #22
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.First().Image.First().MediaUrl;

            return Ok(new { car, image, recalls });
        }
예제 #23
0
        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
        }
예제 #24
0
        public async Task<IHttpActionResult> getCar(idClass id)
        {
            HttpResponseMessage response;
            string content = "";
            var Car = db.Cars.Find(id.id);

            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);
                }
            }

            dynamic Recalls = JsonConvert.DeserializeObject(content);


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

            image.Credentials = new NetworkCredential("accountKey", "9DVmvKlSSAnTU1On117Lu4rMsXdLgjDI+sUWSdxdzIc");   //"dwmFt1J2rM45AQXkGTk4ebfcVLNcytTxGMHK6dgMreg"
            var marketData = image.Composite(
                "image",
                Car.model_year + " " + Car.make + " " + Car.model_name + " " + Car.model_trim + " " + "NOT ebay",
                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 });
            //return JSON.parse(new { car = Car, recalls = Recalls, image = Image });
            // return Ok(Recalls);
            var Images = marketData.FirstOrDefault()?.Image;
            //int imgCnt = Images.Count();
            foreach (var Img in Images)
            {

                if (UrlCtrl.IsUrl(Img.MediaUrl))
                {
                    Image = Img.MediaUrl;
                    break;
                }
                else
                {
                    continue;
                }


            }
            if (string.IsNullOrWhiteSpace(Image))
            {
                Image = "images/carnotfound.jpg";
            }
            return Ok(new { car = Car, recalls = Recalls, image = Image });
        }
예제 #25
0
 public async Task<IHttpActionResult> getCar(int Id)
 {
     HttpResponseMessage response;
     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
         {
             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 = content;
     ​
     var image = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/search/"));​
     image.Credentials = new NetworkCredential("accountKey", "9DVmvKlSSAnTU1On117Lu4rMsXdLgjDI+sUWSdxdzIc");   //"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 });​
 }
예제 #26
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", "p378hNjOm0HKvheOJd/KFybFEM8wmO0orgleQPGPz9s");
            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;

            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 });
        }
예제 #27
0
        public async Task<IHttpActionResult> GetCar(IdParm id)
        {
            // Getting car images through Bing Search 
            var car = db.Cars.Find(id.id);
            if (car == null)
                return await Task.FromResult(NotFound());

            HttpResponseMessage response;
            // Get Credentials for Bing from Web Config File
            string searchApiServiceRootUri = ConfigurationManager.AppSettings["searchApiServiceRootUri"];
            string accountKeyPass = ConfigurationManager.AppSettings["searchApiAccountKey"];

            var client = new BingSearchContainer(new Uri(searchApiServiceRootUri));
            client.Credentials = new NetworkCredential("accountKey", accountKeyPass);
            
            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 imgUrl = firstImage != null ? firstImage.MediaUrl : null;

            // Getting recalls from NHTSA
            dynamic recalls;
            string recallBaseAddress = ConfigurationManager.AppSettings["recallBaseAddress"];
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(recallBaseAddress);

                try
                {
                    response = await httpClient.GetAsync("webapi/api/Recalls/vehicle/modelyear/"+car.model_year+"/make/"
                        +car.make+"/model/"+car.model_name +"? FormatException=json");
                    
                    // JSON returns a string so deserialize it before sending it
                    recalls = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                }
                catch (Exception e)
                {
                    return InternalServerError(e);
                }
            }

            return Ok(new { car, imgUrl, recalls });
        }
예제 #28
0
 public SecService(StardogConnector _context)
 {
     bingContainer = new BingSearchContainer(new Uri(rootUrl));
     Context       = _context;
 }
예제 #29
0
        public List <ImageQueryResult> GetImageUrlList(ImageQueryConfig config, bool isDebug = false)
        {
            //set the debug state
            _debugFlag = isDebug;

            _debug_OpenFileDebug();

            // create the bing search container
            var bingContainer = new BingSearchContainer(new Uri(GlobalConfig._search_baseUrl));

            bingContainer.Credentials = new NetworkCredential(GlobalConfig._search_accountKey, GlobalConfig._search_accountKey);

            var executionFlowObject = QueryFlowConfig.Build(config.Count);

            var total_requested = 0;

            var images = new List <ImageQueryResult>();

            for (int i = 0; i < executionFlowObject.NumberOfFullExecutions + 1; i++)
            {
                // crate a new query for each request as for now I dont know how to actually
                // modify query parameters
                var query = bingContainer.Image(config.Query, null, null, config.SearchOptions.Adult, null, null, config.SearchOptions.ImageFilter);

                // i will be checked to determine $top. if its reqced the total number of executions
                // we will set $top to the remainder
                if (i == executionFlowObject.NumberOfFullExecutions)
                {
                    query = query.AddQueryOption("$top", executionFlowObject.PartialExecutionCount);
                }
                else
                {
                    query = query.AddQueryOption("$top", GlobalConfig._search_maxQueryCount + (i * GlobalConfig._search_maxQueryCount));
                }

                query = query.AddQueryOption("$skip", total_requested);

                _debug_PrintConsoleQuery(query);

                var results = query.Execute();

                // if we got nothing in this query we will just
                // return what we have so far
                if (results == null)
                {
                    return(images);
                }

                var listResults = results.ToList();

                _debug_WriteImageResults(listResults, total_requested);

                total_requested += listResults.Count();

                images.AddRange(listResults.Select(ImageResultMappings.MapImageQueryResultFromImageResult));
            }

            _debug_CloseFileDebug();

            return(images);
        }
예제 #30
0
        public async Task<IHttpActionResult> GetCarDetails(IdParam Id)
        {
            // ---- get Recall Information -----

            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);


            // ---------  Get Image --------

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

            image.Credentials = new NetworkCredential("accountKey", "ih3uuQpD5VI9IrIcovu/1dEIjaJXkB6eFMgSg9CCxGY");
            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();

            var Images = marketData?.FirstOrDefault()?.Image;

            foreach (var Img in Images)
            {
                if (UrlCtrl.IsUrl(Img.MediaUrl))
                {
                    Image = Img.MediaUrl;
                    break;
                }
                else
                {
                    continue;
                }
            }

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