This commit is contained in:
unknown 2020-12-06 18:28:38 +02:00
Родитель 3c2c44044f
Коммит 0bf8d1151a
95 изменённых файлов: 6907 добавлений и 10 удалений

Просмотреть файл

@ -7,7 +7,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.8" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.10" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
@ -16,7 +16,7 @@
<None Remove="Samples\TestImages\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.10" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<ItemGroup>

Просмотреть файл

@ -1,8 +1,18 @@
namespace bing_search_dotnet.Samples
{
using System;
using Microsoft.Azure.CognitiveServices.Search.AutoSuggest;
using Microsoft.Azure.CognitiveServices.Search.AutoSuggest.Models;
using Microsoft.Bing.AutoSuggest;
using Microsoft.Bing.AutoSuggest.Models;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using global::Credentials;
[SampleCollection("AutoSuggestSearch")]
public class AutoSuggestSearchSamples
@ -10,7 +20,7 @@
[Example("This will request suggestions (Satya Nadella) and print out content about them")]
public static void AutoSuggestLookup(string subscriptionKey)
{
var client = new AutoSuggestSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
var client = new AutoSuggestClient(new ClientCredentials(subscriptionKey));
try
{
@ -44,7 +54,7 @@
[Example("This triggers a bad request and shows how to read the error response")]
public static void Error(string subscriptionKey)
{
var client = new AutoSuggestSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey + "1"));
var client = new AutoSuggestClient(new ClientCredentials(subscriptionKey + "1"));
try
{

Просмотреть файл

@ -6,8 +6,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.11" />
<PackageReference Include="Microsoft.Azure.CognitiveServices.Search.AutoSuggest" Version="1.0.0" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\AutoSuggest\src\Microsoft.Bing.Search.AutoSuggest.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,10 +1,14 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.12
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{F1EE2403-0C93-467D-8075-47C9C94D03A3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.AutoSuggest", "..\..\..\sdk\AutoSuggest\src\Microsoft.Bing.Search.AutoSuggest.csproj", "{9F9DF7C4-01BF-467F-8EEA-6020160D4A1A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -15,6 +19,14 @@ Global
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{F1EE2403-0C93-467D-8075-47C9C94D03A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F1EE2403-0C93-467D-8075-47C9C94D03A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1EE2403-0C93-467D-8075-47C9C94D03A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1EE2403-0C93-467D-8075-47C9C94D03A3}.Release|Any CPU.Build.0 = Release|Any CPU
{9F9DF7C4-01BF-467F-8EEA-6020160D4A1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9F9DF7C4-01BF-467F-8EEA-6020160D4A1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9F9DF7C4-01BF-467F-8EEA-6020160D4A1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9F9DF7C4-01BF-467F-8EEA-6020160D4A1A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

288
samples/BingSearchSamples/BingCustomImageSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,76 @@
# Contributing to [project-title]
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
- [Code of Conduct](#coc)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
## <a name="coc"></a> Code of Conduct
Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
## <a name="issue"></a> Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help us by
[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Want a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue.
Help us to maximize the effort we can spend fixing issues and adding new
features, by not reporting duplicate issues. Providing the following information will increase the
chances of your issue being dealt with quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
* **Version** - what version is affected (e.g. 0.1.2)
* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
* **Browsers and Operating System** - is this a problem with all browsers?
* **Reproduce the Error** - provide a live example or a unambiguous set of steps
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git fork:
* Commit your changes using a descriptive commit message
* Push your fork to GitHub:
* In GitHub, create a pull request
* If we suggest changes then:
* Make the required updates.
* Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
git push -f
```
That's it! Thank you for your contribution!

Просмотреть файл

@ -0,0 +1,51 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Linq;
using Microsoft.Bing.CustomImageSearch;
using Credentials;
[SampleCollection("CustomImageSearch")]
public class CustomImageSearchSamples
{
[Example("This will look up a single query (Xbox) and print out number of results, insights token, thumbnail url, content url for first image result")]
public static void CustomImageSearchResultLookup(string subscriptionKey, string customConfig)
{
var client = new CustomImageSearchClient(new ClientCredentials(subscriptionKey));
try
{
var imageResults = client.CustomInstance.ImageSearchAsync(query: "Xbox", customConfig: customConfig).Result;
Console.WriteLine("Searched for Query# \" Xbox \"");
//WebPages
if (imageResults?.Value?.Count > 0)
{
// find the first web page
var firstImageResult = imageResults.Value.First();
if (firstImageResult != null)
{
Console.WriteLine($"Image result count: {imageResults.Value.Count}");
Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}");
Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find image results!");
}
}
else
{
Console.WriteLine("Couldn't find image results!");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,71 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodInfo.DeclaringType != typeof(Samples.CustomImageSearchSamples)) && (methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
if ((methodInfo.DeclaringType == typeof(Samples.CustomImageSearchSamples)) && (methodParams == null || methodParams.Length != 2 || methodParams[0].ParameterType != typeof(string) || methodParams[1].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("CustomImageSearch Method with description \"{0}\" needs to have one string parameter for the subscription key and one int parameter for the customConfig", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(params object[] parameters)
{
this.method.Invoke(null, parameters);
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

Просмотреть файл

@ -0,0 +1,102 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Custom Image Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "CustomImageSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
var subscriptionKey = Console.ReadLine();
Console.WriteLine("Ok, now please enter your custom config number:");
var customConfig = long.Parse(Console.ReadLine());
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\" and customConfig \"{2}\"", exampleIndex, subscriptionKey, customConfig);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(subscriptionKey, customConfig);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
# The Bing Custom Search SDK Sample
This sample will show you how to get up and running using the Bing Custom Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Custom Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-custom-search-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is CustomImageSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Custom Image Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Custom Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/)
* Using the **Bing Custom Image Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomImageSearch/
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-custom-search) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingCustomImageSearch. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/bing-custom-search/).
- Custom Config Id. This is a unique Id of your search instance configuration that you will create from customsearch.ai. Here is a step-by-step information on how to create search instance: https://blogs.bing.com/search-quality-insights/2017-12/build-your-ads-free-search-engine-with-bing-custom-search.
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Custom Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingCustomImageSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomImageSearch/ from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.CustomImageSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingCustomImageSearch\CustomImageSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Custom Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/)
- [Bing Custom Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-custom-search-api-v7-reference)
- [Bing Custom Image Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomImageSearch/)
- [Bing Custom Image Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingCustomImageSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\CustomImageSearch\src\Microsoft.Bing.Search.CustomImageSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{0707F55E-59BC-4DBF-B859-5E7C20EEB65F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.CustomImageSearch", "..\..\..\sdk\CustomImageSearch\src\Microsoft.Bing.Search.CustomImageSearch.csproj", "{76ECD20E-2A6E-4367-917E-02C15099DFDB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{0707F55E-59BC-4DBF-B859-5E7C20EEB65F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0707F55E-59BC-4DBF-B859-5E7C20EEB65F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0707F55E-59BC-4DBF-B859-5E7C20EEB65F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0707F55E-59BC-4DBF-B859-5E7C20EEB65F}.Release|Any CPU.Build.0 = Release|Any CPU
{76ECD20E-2A6E-4367-917E-02C15099DFDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76ECD20E-2A6E-4367-917E-02C15099DFDB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76ECD20E-2A6E-4367-917E-02C15099DFDB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76ECD20E-2A6E-4367-917E-02C15099DFDB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

288
samples/BingSearchSamples/BingCustomWebSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,76 @@
# Contributing to [project-title]
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
- [Code of Conduct](#coc)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
## <a name="coc"></a> Code of Conduct
Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
## <a name="issue"></a> Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help us by
[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Want a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue.
Help us to maximize the effort we can spend fixing issues and adding new
features, by not reporting duplicate issues. Providing the following information will increase the
chances of your issue being dealt with quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
* **Version** - what version is affected (e.g. 0.1.2)
* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
* **Browsers and Operating System** - is this a problem with all browsers?
* **Reproduce the Error** - provide a live example or a unambiguous set of steps
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git fork:
* Commit your changes using a descriptive commit message
* Push your fork to GitHub:
* In GitHub, create a pull request
* If we suggest changes then:
* Make the required updates.
* Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
git push -f
```
That's it! Thank you for your contribution!

Просмотреть файл

@ -0,0 +1,61 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Linq;
using System.Text;
using Microsoft.Bing.CustomSearch;
using Microsoft.Bing.CustomSearch.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using System.Collections;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Credentials;
[SampleCollection("CustomSearch")]
public class CustomSearchSamples
{
[Example("This will look up a single query (Xbox) and print out name and url for first web result")]
public static void CustomSearchWebPageResultLookup(string subscriptionKey, string customConfig)
{
var client = new CustomSearchClient(new ClientCredentials(subscriptionKey));
try
{
var webData = client.CustomInstance.SearchWithHttpMessagesAsync(query: "Xbox", customConfig: customConfig).Result;
Console.WriteLine("Searched for Query# \" Xbox \"");
//WebPages
if (webData?.Body.WebPages?.Value?.Count > 0)
{
// find the first web page
var firstWebPagesResult = webData.Body.WebPages.Value.FirstOrDefault();
if (firstWebPagesResult != null)
{
Console.WriteLine("Webpage Results#{0}", webData.Body.WebPages.Value.Count);
Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
}
else
{
Console.WriteLine("Couldn't find web results!");
}
}
else
{
Console.WriteLine("Didn't see any Web data..");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,71 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodInfo.DeclaringType != typeof(Samples.CustomSearchSamples)) && (methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
if ((methodInfo.DeclaringType == typeof(Samples.CustomSearchSamples)) && (methodParams == null || methodParams.Length != 2 || methodParams[0].ParameterType != typeof(string) || methodParams[1].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("CustomSearch Method with description \"{0}\" needs to have one string parameter for the subscription key and one int parameter for the customConfig", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(params object[] parameters)
{
this.method.Invoke(null, parameters);
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

Просмотреть файл

@ -0,0 +1,102 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Custom Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "CustomSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
var subscriptionKey = Console.ReadLine();
Console.WriteLine("Ok, now please enter your custom config number:");
var customConfig = Int32.Parse(Console.ReadLine());
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\" and customConfig \"{2}\"", exampleIndex, subscriptionKey, customConfig);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(subscriptionKey, customConfig);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
# The Bing Custom Search SDK Sample
This sample will show you how to get up and running using the Bing Custom Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Custom Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-custom-search-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is CustomSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Custom Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Custom Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/)
* Using the **Bing Custom Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomSearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-custom-search) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingCustomSearch. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/bing-custom-search/).
- Custom Config Id. This is a unique Id of your search instance configuration that you will create from customsearch.ai. Here is a step-by-step information on how to create search instance: https://blogs.bing.com/search-quality-insights/2017-12/build-your-ads-free-search-engine-with-bing-custom-search.
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Custom Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingCustomSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomSearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.CustomSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingCustomSearch\CustomSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Custom Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search/)
- [Bing Custom Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-custom-search-api-v7-reference)
- [Bing Custom Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.CustomSearch/1.2.0)
- [Bing Custom Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingCustomSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\CustomWebSearch\src\Microsoft.Bing.Search.CustomWebSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{FF58592A-305C-4B74-8BA3-4E2DFAB81B07}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.CustomWebSearch", "..\..\..\sdk\CustomWebSearch\src\Microsoft.Bing.Search.CustomWebSearch.csproj", "{BB76FFA1-EFAA-4ECB-AC66-8EC0214485E7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{FF58592A-305C-4B74-8BA3-4E2DFAB81B07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF58592A-305C-4B74-8BA3-4E2DFAB81B07}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF58592A-305C-4B74-8BA3-4E2DFAB81B07}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF58592A-305C-4B74-8BA3-4E2DFAB81B07}.Release|Any CPU.Build.0 = Release|Any CPU
{BB76FFA1-EFAA-4ECB-AC66-8EC0214485E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB76FFA1-EFAA-4ECB-AC66-8EC0214485E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB76FFA1-EFAA-4ECB-AC66-8EC0214485E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB76FFA1-EFAA-4ECB-AC66-8EC0214485E7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

288
samples/BingSearchSamples/BingEntitySearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,217 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Linq;
using System.Text;
using Microsoft.Bing.EntitySearch;
using Microsoft.Bing.EntitySearch.Models;
using Newtonsoft.Json;
using Credentials;
[SampleCollection("EntitySearch")]
public class EntitySearchSamples
{
[Example("This will look up a single entity (tom cruise) and print out a short description about them")]
public static void DominantEntityLookup(string subscriptionKey)
{
var client = new EntitySearchClient(new ClientCredentials(subscriptionKey));
try
{
var entityData = client.Entities.Search(query:"tom cruise");
if (entityData?.Entities?.Value?.Count > 0)
{
// find the entity that represents the dominant one
var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();
if (mainEntity != null)
{
Console.WriteLine("Searched for \"Tom Cruise\" and found a dominant entity with this description:");
Console.WriteLine(mainEntity.Description);
}
else
{
Console.WriteLine("Couldn't find main entity tom cruise!");
}
}
else
{
Console.WriteLine("Didn't see any data..");
}
}
catch (ErrorResponseException ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will handle disambiguation results for an ambiguous query (harry potter)")]
public static void HandlingDisambiguation(string subscriptionKey)
{
var client = new EntitySearchClient(new ClientCredentials(subscriptionKey));
try
{
var entityData = client.Entities.Search(query: "harry potter");
if (entityData?.Entities?.Value?.Count > 0)
{
// find the entity that represents the dominant one
var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();
var disambigEntities = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DisambiguationItem).ToList();
if (mainEntity != null)
{
Console.WriteLine("Searched for \"harry potter\" and found a dominant entity with type hint \"{0}\" with this description:", mainEntity.EntityPresentationInfo.EntityTypeDisplayHint);
Console.WriteLine(mainEntity.Description);
}
else
{
Console.WriteLine("Couldn't find a reliable dominant entity for harry potter!");
}
if (disambigEntities?.Count > 0)
{
Console.WriteLine();
Console.WriteLine("This query is pretty ambiguous and can be referring to multiple things. Did you mean one of these: ");
var sb = new StringBuilder();
foreach (var disambig in disambigEntities)
{
sb.AppendFormat(", or {0} the {1}", disambig.Name, disambig.EntityPresentationInfo.EntityTypeDisplayHint);
}
Console.WriteLine(sb.ToString().Substring(5) + "?");
}
else
{
Console.WriteLine("We didn't find any disambiguation items for harry potter, so we must be certain what you're talking about!");
}
}
else
{
Console.WriteLine("Didn't see any data..");
}
}
catch (ErrorResponseException ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will look up a single restaurant (john howie bellevue) and print out its phone number")]
public static void RestaurantLookup(string subscriptionKey)
{
var client = new EntitySearchClient(new ClientCredentials(subscriptionKey));
try
{
var entityData = client.Entities.Search(query: "john howie bellevue");
if (entityData?.Places?.Value?.Count > 0)
{
// Some local entities will be places, others won't be. Depending on the data you want, try to cast to the appropriate schema
// In this case, the item being returned is technically a Restaurant, but the Place schema has the data we want (telephone)
var restaurant = entityData.Places.Value.FirstOrDefault() as Place;
if (restaurant != null)
{
Console.WriteLine("Searched for \"John Howie Bellevue\" and found a restaurant with this phone number:");
Console.WriteLine(restaurant.Telephone);
}
else
{
Console.WriteLine("Couldn't find a place!");
}
}
else
{
Console.WriteLine("Didn't see any data..");
}
}
catch (ErrorResponseException ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will look up a list of restaurants (seattle restaurants) and present their names and phone numbers")]
public static void MultipleRestaurantLookup(string subscriptionKey)
{
var client = new EntitySearchClient(new ClientCredentials(subscriptionKey));
try
{
var restaurants = client.Entities.Search(query: "seattle restaurants");
if (restaurants?.Places?.Value?.Count > 0)
{
// get all the list items that relate to this query
var listItems = restaurants.Places.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.ListItem).ToList();
if (listItems?.Count > 0)
{
var sb = new StringBuilder();
foreach (var item in listItems)
{
var place = item as Place;
if (place == null)
{
Console.WriteLine("Unexpectedly found something that isn't a place named \"{0}\"", item.Name);
continue;
}
sb.AppendFormat(",{0} ({1}) ", place.Name, place.Telephone);
}
Console.WriteLine("Ok, we found these places: ");
Console.WriteLine(sb.ToString().Substring(1));
}
else
{
Console.WriteLine("Couldn't find any relevant results for \"seattle restaurants\"");
}
}
else
{
Console.WriteLine("Didn't see any data..");
}
}
catch (ErrorResponseException ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This triggers a bad request and shows how to read the error response")]
public static void Error(string subscriptionKey)
{
var client = new EntitySearchClient(new ClientCredentials(subscriptionKey));
try
{
var entityData = client.Entities.Search(query: "tom cruise", market: "no-ty");
}
catch (ErrorResponseException ex)
{
// The status code of the error should be a good indication of what occurred. However, if you'd like more details, you can dig into the response.
// Please note that depending on the type of error, the response schema might be different, so you aren't guaranteed a specific error response schema.
Console.WriteLine("Exception occurred, status code {0} with reason {1}.", ex.Response.StatusCode, ex.Response.ReasonPhrase);
// if you'd like more descriptive information (if available), attempt to parse the content as an ErrorResponse
var issue = JsonConvert.DeserializeObject<ErrorResponse>(ex.Response.Content);
if (issue != null && issue.Errors?.Count > 0)
{
if (issue.Errors[0].SubCode == ErrorSubCode.ParameterInvalidValue)
{
Console.WriteLine("Turns out the issue is parameter \"{0}\" has an invalid value \"{1}\". Detailed message is \"{2}\"", issue.Errors[0].Parameter, issue.Errors[0].Value, issue.Errors[0].Message);
}
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey, string inputEndpoint)
{
this.method.Invoke(null, new object[] { subscriptionKey, inputEndpoint });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,102 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Entity Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "EntitySearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, now please enter your endpoint:");
var inputEndpoint = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input, inputEndpoint);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
# The Bing Entity Search SDK Sample
This sample will show you how to get up and running using the Bing Entity Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Entity Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-entity-search-api/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-entities-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is EntitySearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Entity Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Entity Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-entity-search-api/)
* Using the **Bing Entity Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.EntitySearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-entity-search-api) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/web/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Entity Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingEntitySearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.EntitySearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.EntitySearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingEntitySearch\EntitySearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Entity Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-entity-search-api/)
- [Bing Entity Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-entities-api-v7-reference)
- [Bing Entity Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.EntitySearch/1.2.0)
- [Bing Entity Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingEntitySearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\EntitySearch\src\Microsoft.Bing.Search.EntitySearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{D6CBC160-EA05-446B-A1FA-47978ABD5C2B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.EntitySearch", "..\..\..\sdk\EntitySearch\src\Microsoft.Bing.Search.EntitySearch.csproj", "{5EFF4D3E-B3B1-4935-889B-064BC942CC55}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{D6CBC160-EA05-446B-A1FA-47978ABD5C2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6CBC160-EA05-446B-A1FA-47978ABD5C2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6CBC160-EA05-446B-A1FA-47978ABD5C2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6CBC160-EA05-446B-A1FA-47978ABD5C2B}.Release|Any CPU.Build.0 = Release|Any CPU
{5EFF4D3E-B3B1-4935-889B-064BC942CC55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5EFF4D3E-B3B1-4935-889B-064BC942CC55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5EFF4D3E-B3B1-4935-889B-064BC942CC55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5EFF4D3E-B3B1-4935-889B-064BC942CC55}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,300 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Collections.Generic;
using System.Linq;
using Credentials;
using Microsoft.Bing.ImageSearch;
using Microsoft.Bing.ImageSearch.Models;
[SampleCollection("ImageSearch")]
public class ImageSearchSamples
{
[Example("This will search images for (canadian rockies) then verify number of results and print out first image result, pivot suggestion, and query expansion")]
public static void ImageSearch(string subscriptionKey)
{
var client = new ImageSearchClient(new ClientCredentials(subscriptionKey));
try
{
var imageResults = client.Images.SearchAsync(query: "canadian rockies").Result;
Console.WriteLine("Search images for query \"canadian rockies\"");
if (imageResults == null)
{
Console.WriteLine("No image result data.");
}
else
{
// Image results
if (imageResults.Value.Count > 0)
{
var firstImageResult = imageResults.Value.First();
Console.WriteLine($"Image result count: {imageResults.Value.Count}");
Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}");
Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find image results!");
}
Console.WriteLine($"Image result total estimated matches: {imageResults.TotalEstimatedMatches}");
Console.WriteLine($"Image result next offset: {imageResults.NextOffset}");
// Pivot suggestions
if (imageResults.PivotSuggestions != null && imageResults.PivotSuggestions.Count > 0)
{
var firstPivot = imageResults.PivotSuggestions.First();
Console.WriteLine($"Pivot suggestion count: {imageResults.PivotSuggestions.Count}");
Console.WriteLine($"First pivot: {firstPivot.Pivot}");
if (firstPivot.Suggestions.Count > 0)
{
var firstSuggestion = firstPivot.Suggestions.First();
Console.WriteLine($"Suggestion count: {firstPivot.Suggestions.Count}");
Console.WriteLine($"First suggestion text: {firstSuggestion.Text}");
Console.WriteLine($"First suggestion web search url: {firstSuggestion.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find suggestions!");
}
}
else
{
Console.WriteLine("Couldn't find pivot suggestions!");
}
// Query expansions
if (imageResults.QueryExpansions != null && imageResults.QueryExpansions.Count > 0)
{
var firstQueryExpansion = imageResults.QueryExpansions.First();
Console.WriteLine($"Query expansion count: {imageResults.QueryExpansions.Count}");
Console.WriteLine($"First query expansion text: {firstQueryExpansion.Text}");
Console.WriteLine($"First query expansion search link: {firstQueryExpansion.SearchLink}");
}
else
{
Console.WriteLine("Couldn't find query expansions!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search images for (studio ghibli), filtered for animated gifs and wide aspect, then verify number of results and print out insightsToken, thumbnail url and web url of first result")]
public static void ImageSearchWithFilters(string subscriptionKey)
{
var client = new ImageSearchClient(new ClientCredentials(subscriptionKey));
try
{
var imageResults = client.Images.SearchAsync(query: "studio ghibli", imageType: ImageType.AnimatedGif, aspect: ImageAspect.Wide).Result;
Console.WriteLine("Search images for \"studio ghibli\" results that are animated gifs and wide aspect");
if (imageResults == null)
{
Console.WriteLine("Didn't see any image result data.");
}
else
{
// First image result
if (imageResults.Value.Count > 0)
{
var firstImageResult = imageResults.Value.First();
Console.WriteLine($"Image result count: {imageResults.Value.Count}");
Console.WriteLine($"First image insightsToken: {firstImageResult.ImageInsightsToken}");
Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
Console.WriteLine($"First image web search url: {firstImageResult.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find image results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search for trending images then verify categories and tiles")]
public static void ImageTrending(string subscriptionKey)
{
var client = new ImageSearchClient(new ClientCredentials(subscriptionKey));
try
{
var trendingResults = client.Images.TrendingAsync().Result;
Console.WriteLine("Search trending images");
if (trendingResults == null)
{
Console.WriteLine("Didn't see any trending image data.");
}
else
{
// Categories
if (trendingResults.Categories?.Count > 0)
{
var firstCategory = trendingResults.Categories[0];
Console.WriteLine($"Category count: {trendingResults.Categories.Count}");
Console.WriteLine($"First category title: {firstCategory.Title}");
// Tiles
if (firstCategory.Tiles?.Count > 0)
{
var firstTile = firstCategory.Tiles[0];
Console.WriteLine($"Tile count: {firstCategory.Tiles.Count}");
Console.WriteLine($"First tile text: {firstTile.Query.Text}");
Console.WriteLine($"First tile url: {firstTile.Query.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find tiles!");
}
}
else
{
Console.WriteLine("Couldn't find categories!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search images for (degas) and then search for image details of the first image")]
public static void ImageDetail(string subscriptionKey)
{
var client = new ImageSearchClient(new ClientCredentials(subscriptionKey));
try
{
var imageResults = client.Images.SearchAsync(query: "degas").Result;
var firstImage = imageResults?.Value?.FirstOrDefault();
if (firstImage != null)
{
var modules = new List<string>() { ImageInsightModule.All };
var imageDetail = client.Images.DetailsAsync(query: "degas", insightsToken: firstImage.ImageInsightsToken, modules: modules).Result;
Console.WriteLine($"Search detail for image insightsToken={firstImage.ImageInsightsToken}");
if (imageDetail != null)
{
// Insights token
Console.WriteLine($"Expected image insights token: {imageDetail.ImageInsightsToken}");
// Best representative query
if (imageDetail.BestRepresentativeQuery != null)
{
Console.WriteLine($"Best representative query text: {imageDetail.BestRepresentativeQuery.Text}");
Console.WriteLine($"Best representative query web search url: {imageDetail.BestRepresentativeQuery.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find best representative query!");
}
// Caption
if (imageDetail.ImageCaption != null)
{
Console.WriteLine($"Image caption: {imageDetail.ImageCaption.Caption}");
Console.WriteLine($"Image caption data source url: {imageDetail.ImageCaption.DataSourceUrl}");
}
else
{
Console.WriteLine("Couldn't find image caption!");
}
// Pages including the image
if (imageDetail.PagesIncluding?.Value?.Count > 0)
{
var firstPage = imageDetail.PagesIncluding.Value[0];
Console.WriteLine($"Pages including count: {imageDetail.PagesIncluding.Value.Count}");
Console.WriteLine($"First page content url: {firstPage.ContentUrl}");
Console.WriteLine($"First page name: {firstPage.Name}");
Console.WriteLine($"First page date published: {firstPage.DatePublished}");
}
else
{
Console.WriteLine("Couldn't find any pages including this image!");
}
// Related searches
if (imageDetail.RelatedSearches?.Value?.Count > 0)
{
var firstRelatedSearch = imageDetail.RelatedSearches.Value[0];
Console.WriteLine($"Related searches count: {imageDetail.RelatedSearches.Value.Count}");
Console.WriteLine($"First related search text: {firstRelatedSearch.Text}");
Console.WriteLine($"First related search web search url: {firstRelatedSearch.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find any related searches!");
}
// Visually similar images
if (imageDetail.VisuallySimilarImages?.Value?.Count > 0 && imageDetail.RelatedSearches!=null)
{
var firstVisuallySimilarImage = imageDetail.VisuallySimilarImages.Value[0];
Console.WriteLine($"Visually similar images count: {imageDetail.RelatedSearches.Value.Count}");
Console.WriteLine($"First visually similar image name: {firstVisuallySimilarImage.Name}");
Console.WriteLine($"First visually similar image content url: {firstVisuallySimilarImage.ContentUrl}");
Console.WriteLine($"First visually similar image size: {firstVisuallySimilarImage.ContentSize}");
}
else
{
Console.WriteLine("Couldn't find any related searches!");
}
// Image tags
if (imageDetail.ImageTags?.Value?.Count > 0 && imageDetail.ImageTags !=null)
{
var firstTag = imageDetail.ImageTags.Value[0];
Console.WriteLine($"Image tags count: {imageDetail.ImageTags.Value.Count}");
Console.WriteLine($"First tag name: {firstTag.Name}");
}
else
{
Console.WriteLine("Couldn't find any related searches!");
}
}
else
{
Console.WriteLine("Couldn't find detail about the image!");
}
}
else
{
Console.WriteLine("Couldn't find image results!");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,99 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Image Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "ImageSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
# The Bing Image Search SDK Sample
This sample will show you how to get up and running using the Bing Image Search SDK. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Image Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-image-search-api/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is ImageSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Image Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Image Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-image-search-api/)
* Using the **Bing Image Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.ImageSearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-image-search-api) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/image/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Image Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingImageSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.ImageSearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.ImageSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingImageSearch\ImageSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Image Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-image-search-api/)
- [Bing Image Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference)
- [Bing Image Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.ImageSearch/1.2.0)
- [Bing Image Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingImageSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\sdk\ImageSearch\src\Microsoft.Bing.Search.ImageSearch.csproj" />
<ProjectReference Include="..\..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\..\common\Common\Common.csproj", "{532EC77A-56C2-4F11-9B51-A0D2183E706C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.ImageSearch", "..\..\..\..\sdk\ImageSearch\src\Microsoft.Bing.Search.ImageSearch.csproj", "{D1B5A7A4-4759-449B-8FAD-66ABC48FF4B1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{532EC77A-56C2-4F11-9B51-A0D2183E706C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{532EC77A-56C2-4F11-9B51-A0D2183E706C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{532EC77A-56C2-4F11-9B51-A0D2183E706C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{532EC77A-56C2-4F11-9B51-A0D2183E706C}.Release|Any CPU.Build.0 = Release|Any CPU
{D1B5A7A4-4759-449B-8FAD-66ABC48FF4B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1B5A7A4-4759-449B-8FAD-66ABC48FF4B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1B5A7A4-4759-449B-8FAD-66ABC48FF4B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1B5A7A4-4759-449B-8FAD-66ABC48FF4B1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,54 @@
using System;
using System.Linq;
using Microsoft.Azure.CognitiveServices.Search.ImageSearch;
using Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models;
namespace bing_search_dotnet
{
public class BingImageSearchSample
{
static void Main(string[] args)
{
//IMPORTANT: replace this variable with your Cognitive Services subscription key.
string subscriptionKey = "ENTER YOUR KEY HERE";
// the image search term used in the query
string searchTerm = "canadian rockies";
//initialize the client
//NOTE: If you're using version 1.2.0 or below for the Bing Image Search client library,
// use ImageSearchAPI() instead of ImageSearchClient() to initialize your search client.
var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey));
Console.WriteLine("This application will send an HTTP request to the Bing Image Search API for {0} and print the response.", searchTerm);
//images to be returned by the Bing Image Search API
Images imageResults = null;
//try to send the request, and get the results.
Console.WriteLine("Search results for the image query: {0}", searchTerm);
try
{
imageResults = client.Images.SearchAsync(query: searchTerm).Result; //search query
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
if (imageResults != null)
{
//display the details for the first image result. After running the application,
//you can copy the resulting URLs from the console into your browser to view the image.
var firstImageResult = imageResults.Value.First();
Console.WriteLine($"\nTotal number of returned images: {imageResults.Value.Count}\n");
Console.WriteLine($"Copy the following URLs to view these images on your browser.\n");
Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n");
Console.WriteLine($"Thumbnail URL for the first image:\n\n {firstImageResult.ThumbnailUrl}");
Console.Write("\nPress Enter to exit ");
Console.ReadKey();
}
}
}
}

288
samples/BingSearchSamples/BingNewsSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,176 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Collections.Generic;
using System.Linq;
using Credentials;
using Microsoft.microsoft.Bing.NewsSearch;
using Microsoft.microsoft.Bing.NewsSearch.Models;
[SampleCollection("NewsSearch")]
public class NewsSearchSamples
{
[Example("This will search news for (Quantum Computing) with market and count parameters then verify number of results and print out totalEstimatedMatches, name, url, description, published time and name of provider of the first news result")]
public static void NewsSearch(string subscriptionKey)
{
var client = new NewsSearchClient(new ClientCredentials(subscriptionKey));
try
{
var newsResults = client.News.SearchAsync(query: "Quantum Computing", market: "en-us", count: 10).Result;
Console.WriteLine("Search news for query \"Quantum Computing\" with market and count");
if (newsResults == null)
{
Console.WriteLine("Didn't see any news result data..");
}
else
{
if (newsResults.Value.Count > 0)
{
var firstNewsResult = newsResults.Value.First();
Console.WriteLine($"TotalEstimatedMatches value: {newsResults.TotalEstimatedMatches}");
Console.WriteLine($"News result count: {newsResults.Value.Count}");
Console.WriteLine($"First news name: {firstNewsResult.Name}");
Console.WriteLine($"First news url: {firstNewsResult.Url}");
Console.WriteLine($"First news description: {firstNewsResult.Description}");
Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}");
Console.WriteLine($"First news provider: {firstNewsResult.Provider.First().Name}");
}
else
{
Console.WriteLine("Couldn't find news results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search most recent news for (Artificial Intelligence) with freshness and sortBy parameters then verify number of results and print out totalEstimatedMatches, name, url, description, published time and name of provider of the first news result")]
public static void NewsSearchWithFilters(string subscriptionKey)
{
var client = new NewsSearchClient(new ClientCredentials(subscriptionKey));
try
{
var newsResults = client.News.SearchAsync(query: "Artificial Intelligence", market: "en-us", freshness: "Week", sortBy: "Date").Result;
Console.WriteLine("Search most recent news for query \"Artificial Intelligence\" with freshness and sortBy");
if (newsResults == null)
{
Console.WriteLine("Didn't see any news result data..");
}
else
{
if (newsResults.Value.Count > 0)
{
var firstNewsResult = newsResults.Value.First();
Console.WriteLine($"TotalEstimatedMatches value: {newsResults.TotalEstimatedMatches}");
Console.WriteLine($"News result count: {newsResults.Value.Count}");
Console.WriteLine($"First news name: {firstNewsResult.Name}");
Console.WriteLine($"First news url: {firstNewsResult.Url}");
Console.WriteLine($"First news description: {firstNewsResult.Description}");
Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}");
Console.WriteLine($"First news provider: {firstNewsResult.Provider.First().Name}");
}
else
{
Console.WriteLine("Couldn't find news results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search category news for movie and TV entertainment with safe search then verify number of results and print out category, name, url, description, published time and name of provider of the first news result")]
public static void NewsCategory(string subscriptionKey)
{
var client = new NewsSearchClient(new ClientCredentials(subscriptionKey));
try
{
var newsResults = client.News.CategoryAsync(category: "Entertainment_MovieAndTV", market: "en-us", safeSearch: "strict").Result;
Console.WriteLine("Search category news for movie and TV entertainment with safe search");
if (newsResults == null)
{
Console.WriteLine("Didn't see any news result data..");
}
else
{
if (newsResults.Value.Count > 0)
{
var firstNewsResult = newsResults.Value.First();
Console.WriteLine($"News result count: {newsResults.Value.Count}");
Console.WriteLine($"First news category: {firstNewsResult.Category}");
Console.WriteLine($"First news name: {firstNewsResult.Name}");
Console.WriteLine($"First news url: {firstNewsResult.Url}");
Console.WriteLine($"First news description: {firstNewsResult.Description}");
Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}");
Console.WriteLine($"First news provider: {firstNewsResult.Provider.First().Name}");
}
else
{
Console.WriteLine("Couldn't find news results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search news trending topics in Bing then verify number of results and print out name, text of query, webSearchUrl, newsSearchUrl and image Url of the first news result")]
public static void TrendingTopics(string subscriptionKey)
{
var client = new NewsSearchClient(new ClientCredentials(subscriptionKey));
try
{
var trendingTopics = client.News.TrendingAsync(market: "en-us").Result;
Console.WriteLine("Search news trending topics in Bing");
if (trendingTopics == null)
{
Console.WriteLine("Didn't see any news trending topics..");
}
else
{
if (trendingTopics.Value.Count > 0)
{
var firstTopic = trendingTopics.Value.First();
Console.WriteLine($"Trending topics count: {trendingTopics.Value.Count}");
Console.WriteLine($"First topic name: {firstTopic.Name}");
Console.WriteLine($"First topic query: {firstTopic.Query.Text}");
Console.WriteLine($"First topic image url: {firstTopic.Image.Url}");
Console.WriteLine($"First topic webSearchUrl: {firstTopic.WebSearchUrl}");
Console.WriteLine($"First topic newsSearchUrl: {firstTopic.NewsSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find news trending topics!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,99 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to News Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "NewsSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
# The Bing News Search SDK Sample
This sample will show you how to get up and running using the Bing News Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing News Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-news-search-api/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is NewsSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing News Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing News Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-news-search-api/)
* Using the **Bing News Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.NewsSearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-news-search-api) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/news/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing News Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingNewsSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.NewsSearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.NewsSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingNewsSearch\NewsSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing News Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-news-search-api/)
- [Bing News Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-news-api-v7-reference)
- [Bing News Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.NewsSearch/1.2.0)
- [Bing News Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingNewsSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\NewsSearch\src\Microsoft.Bing.Search.NewsSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{051759B6-B397-4782-8106-D78E41CD14AB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.NewsSearch", "..\..\..\sdk\NewsSearch\src\Microsoft.Bing.Search.NewsSearch.csproj", "{38E48055-341A-4423-87CA-4CE6831443F6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{051759B6-B397-4782-8106-D78E41CD14AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{051759B6-B397-4782-8106-D78E41CD14AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{051759B6-B397-4782-8106-D78E41CD14AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{051759B6-B397-4782-8106-D78E41CD14AB}.Release|Any CPU.Build.0 = Release|Any CPU
{38E48055-341A-4423-87CA-4CE6831443F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{38E48055-341A-4423-87CA-4CE6831443F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{38E48055-341A-4423-87CA-4CE6831443F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{38E48055-341A-4423-87CA-4CE6831443F6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

288
samples/BingSearchSamples/BingVideoSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,99 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Video Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "VideoSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
# The Bing Video Search SDK Sample
This sample will show you how to get up and running using the Bing Video Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Video Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-video-search-api/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is VideoSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Video Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Video Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-video-search-api/)
* Using the **Bing Video Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VideoSearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-video-search-api) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/video/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Video Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingVideoSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VideoSearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.VideoSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingVideoSearch\VideoSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Video Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-video-search-api/)
- [Bing Video Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-video-api-v7-reference)
- [Bing Video Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VideoSearch/1.2.0)
- [Bing Video Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingVideoSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,224 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Collections.Generic;
using System.Linq;
using Credentials;
using Microsoft.Bing.VideoSearch;
using Microsoft.Bing.VideoSearch.Models;
[SampleCollection("VideoSearch")]
public class VideoSearchSamples
{
[Example("This will search videos for (Nasa CubeSat) then verify number of results and print out id, name and url of first video result")]
public static void VideoSearch(string subscriptionKey)
{
var client = new VideoSearchClient(new ClientCredentials(subscriptionKey));
try
{
var videoResults = client.Videos.SearchAsync(query: "Nasa CubeSat").Result;
Console.WriteLine("Search videos for query \"Nasa CubeSat\"");
if (videoResults == null)
{
Console.WriteLine("Didn't see any video result data..");
}
else
{
if (videoResults.Value.Count > 0)
{
var firstVideoResult = videoResults.Value.First();
Console.WriteLine($"Video result count: {videoResults.Value.Count}");
Console.WriteLine($"First video id: {firstVideoResult.VideoId}");
Console.WriteLine($"First video name: {firstVideoResult.Name}");
Console.WriteLine($"First video url: {firstVideoResult.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find video results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search videos for (Interstellar Trailer) that is free, short and 1080p resolution then verify number of results and print out id, name and url of first video result")]
public static void VideoSearchWithFilters(string subscriptionKey)
{
var client = new VideoSearchClient(new ClientCredentials(subscriptionKey));
try
{
var videoResults = client.Videos.SearchAsync(query: "Interstellar Trailer", pricing: VideoPricing.Free, length: VideoLength.Short, resolution: VideoResolution.HD1080p).Result;
Console.WriteLine("Search videos for query \"Interstellar Trailer\" that is free, short and 1080p resolution");
if (videoResults == null)
{
Console.WriteLine("Didn't see any video result data..");
}
else
{
if (videoResults.Value.Count > 0)
{
var firstVideoResult = videoResults.Value.First();
Console.WriteLine($"Video result count: {videoResults.Value.Count}");
Console.WriteLine($"First video id: {firstVideoResult.VideoId}");
Console.WriteLine($"First video name: {firstVideoResult.Name}");
Console.WriteLine($"First video url: {firstVideoResult.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find video results!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will trending videos then verify banner tiles and categories")]
public static void VideoTrending(string subscriptionKey)
{
var client = new VideoSearchClient(new ClientCredentials(subscriptionKey));
try
{
var trendingResults = client.Videos.TrendingAsync().Result;
Console.WriteLine("Search trending videos");
if (trendingResults == null)
{
Console.WriteLine("Didn't see any trending video data..");
}
else
{
// Banner Tiles
if (trendingResults.BannerTiles?.Count > 0)
{
var firstBannerTile = trendingResults.BannerTiles[0];
Console.WriteLine($"Banner tile count: {trendingResults.BannerTiles.Count}");
Console.WriteLine($"First banner tile text: {firstBannerTile.Query.Text}");
Console.WriteLine($"First banner tile url: {firstBannerTile.Query.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find banner tiles!");
}
// Categories
if (trendingResults.Categories?.Count > 0)
{
var firstCategory = trendingResults.Categories[0];
Console.WriteLine($"Category count: {trendingResults.Categories.Count}");
Console.WriteLine($"First category title: {firstCategory.Title}");
if (firstCategory.Subcategories?.Count > 0)
{
var firstSubCategory = firstCategory.Subcategories[0];
Console.WriteLine($"SubCategory count: {firstCategory.Subcategories.Count}");
Console.WriteLine($"First sub category title: {firstSubCategory.Title}");
if (firstSubCategory.Tiles?.Count > 0)
{
var firstTile = firstSubCategory.Tiles[0];
Console.WriteLine($"Tile count: {firstSubCategory.Tiles.Count}");
Console.WriteLine($"First tile text: {firstTile.Query.Text}");
Console.WriteLine($"First tile url: {firstTile.Query.WebSearchUrl}");
}
else
{
Console.WriteLine("Couldn't find tiles!");
}
}
else
{
Console.WriteLine("Couldn't find subcategories!");
}
}
else
{
Console.WriteLine("Couldn't find categories!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search videos for (Interstellar Trailer) and then search for detail information of the first video")]
public static void VideoDetail(string subscriptionKey)
{
var client = new VideoSearchClient(new ClientCredentials(subscriptionKey));
try
{
var videoResults = client.Videos.SearchAsync(query: "Interstellar Trailer").Result;
var firstVideo = videoResults?.Value?.FirstOrDefault();
if (firstVideo != null)
{
var modules = new List<VideoInsightModule?>() { VideoInsightModule.All };
var videoDetail = client.Videos.DetailsAsync(query: "Interstellar Trailer", id: firstVideo.VideoId, modules: modules).Result;
Console.WriteLine($"Search detail for video id={firstVideo.VideoId}, name={firstVideo.Name}");
if (videoDetail != null)
{
if (videoDetail.VideoResult != null)
{
Console.WriteLine($"Expected video id: {videoDetail.VideoResult.VideoId}");
Console.WriteLine($"Expected video name: {videoDetail.VideoResult.Name}");
Console.WriteLine($"Expected video url: {videoDetail.VideoResult.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find expected video!");
}
if (videoDetail?.RelatedVideos?.Value?.Count > 0)
{
var firstRelatedVideo = videoDetail.RelatedVideos.Value[0];
Console.WriteLine($"Related video count: {videoDetail.RelatedVideos.Value.Count}");
Console.WriteLine($"First related video id: {firstRelatedVideo.VideoId}");
Console.WriteLine($"First related video name: {firstRelatedVideo.Name}");
Console.WriteLine($"First related video url: {firstRelatedVideo.ContentUrl}");
}
else
{
Console.WriteLine("Couldn't find any related video!");
}
}
else
{
Console.WriteLine("Couldn't find detail about the video!");
}
}
else
{
Console.WriteLine("Couldn't find video results!");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\VideoSearch\src\Microsoft.Bing.Search.VideoSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{CF213DD1-A306-4B8A-A4BF-4DD92ACD8566}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.VideoSearch", "..\..\..\sdk\VideoSearch\src\Microsoft.Bing.Search.VideoSearch.csproj", "{09221457-51AF-4CD0-B352-8C2427FEDEF3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{CF213DD1-A306-4B8A-A4BF-4DD92ACD8566}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF213DD1-A306-4B8A-A4BF-4DD92ACD8566}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF213DD1-A306-4B8A-A4BF-4DD92ACD8566}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF213DD1-A306-4B8A-A4BF-4DD92ACD8566}.Release|Any CPU.Build.0 = Release|Any CPU
{09221457-51AF-4CD0-B352-8C2427FEDEF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09221457-51AF-4CD0-B352-8C2427FEDEF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09221457-51AF-4CD0-B352-8C2427FEDEF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09221457-51AF-4CD0-B352-8C2427FEDEF3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

288
samples/BingSearchSamples/BingVisualSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2018-04-24)
*Features*
* Initial release with VisualSearch samples

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,99 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Visual Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "VisualSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
# The Bing Visual Search SDK Sample
This sample will show you how to get up and running using the Bing Visual Search Nuget package. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Visual Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-visual-search/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bingvisualsearch/images/visualsearch).
If you are looking for amending samples to suit your needs, the single, most important file is VisualSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Visual Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Visual Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-visual-search/)
* Using the **Bing Visual Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VisualSearch/0.18.0-preview
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=search-api-v7) for the **free** trial key. This trial key is good for 7 days with 1 call per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/visual/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Visual Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingVisualSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VisualSearch/0.18.0-preview from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.VisualSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingVisualSearch\VisualSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Visual Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-visual-search/)
- [Bing Visual Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bingvisualsearch/images/visualsearch)
- [Bing Visual Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.VisualSearch/0.18.0-preview)
- [Bing Visual Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingVisualSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Двоичные данные
samples/BingSearchSamples/BingVisualSearch/TestImages/image.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 590 KiB

Просмотреть файл

@ -0,0 +1,360 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Credentials;
using Microsoft.Bing.VisualSearch;
using Microsoft.Bing.VisualSearch.Models;
using Newtonsoft.Json;
[SampleCollection("VisualSearch")]
public class VisualSearchSamples
{
[Example("This will send an image binary in the body of the post request and print out the imageInsightsToken, the number of tags, the number of actions, and the first actionType")]
public static void VisualSearchImageBinary(string subscriptionKey)
{
var client = new VisualSearchClient(new ClientCredentials(subscriptionKey));
try
{
using (FileStream stream = new FileStream(Path.Combine("TestImages", "image.jpg"), FileMode.Open))
{
// The knowledgeRequest parameter is not required if an image binary is passed in the request body
var visualSearchResults = client.Images.VisualSearchMethodAsync(image: stream, knowledgeRequest: (string)null).Result;
Console.WriteLine("Search visual search request with binary of eiffel tower image");
if (visualSearchResults == null)
{
Console.WriteLine("No visual search result data.");
}
else
{
// Visual Search results
if (visualSearchResults.Image?.ImageInsightsToken != null)
{
Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}");
}
else
{
Console.WriteLine("Couldn't find image insights token!");
}
// List of tags
if (visualSearchResults.Tags.Count > 0)
{
var firstTagResult = visualSearchResults.Tags.First();
Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}");
// List of actions in first tag
if (firstTagResult.Actions.Count > 0)
{
var firstActionResult = firstTagResult.Actions.First();
Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}");
Console.WriteLine($"First tag action type: {firstActionResult.ActionType}");
}
else
{
Console.WriteLine("Couldn't find tag actions!");
}
}
else
{
Console.WriteLine("Couldn't find image tags!");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will send an image binary in the body of the post request, along with a cropArea object, and print out the imageInsightsToken, the number of tags, the number of actions, and the first actionType")]
public static void VisualSearchImageBinaryWithCropArea(string subscriptionKey)
{
var client = new VisualSearchClient(new ClientCredentials(subscriptionKey));
try
{
using (FileStream stream = new FileStream(Path.Combine("TestImages", "image.jpg"), FileMode.Open))
{
// The ImageInfo struct contains a crop area specifying a region to crop in the uploaded image
CropArea CropArea = new CropArea(top: (float)0.1, bottom: (float)0.5, left: (float)0.1, right: (float)0.9);
ImageInfo ImageInfo = new ImageInfo(cropArea: CropArea);
VisualSearchRequest VisualSearchRequest = new VisualSearchRequest(imageInfo: ImageInfo);
// The knowledgeRequest here holds additional information about the image, which is passed in in binary form
var visualSearchResults = client.Images.VisualSearchMethodAsync(image: stream, knowledgeRequest: VisualSearchRequest.ToString()).Result;
Console.WriteLine("Search visual search request with binary of eiffel tower image");
if (visualSearchResults == null)
{
Console.WriteLine("No visual search result data.");
}
else
{
// Visual Search results
if (visualSearchResults.Image?.ImageInsightsToken != null)
{
Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}");
}
else
{
Console.WriteLine("Couldn't find image insights token!");
}
// List of tags
if (visualSearchResults.Tags.Count > 0)
{
var firstTagResult = visualSearchResults.Tags.First();
Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}");
// List of actions in first tag
if (firstTagResult.Actions.Count > 0)
{
var firstActionResult = firstTagResult.Actions.First();
Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}");
Console.WriteLine($"First tag action type: {firstActionResult.ActionType}");
}
else
{
Console.WriteLine("Couldn't find tag actions!");
}
}
else
{
Console.WriteLine("Couldn't find image tags!");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will send an image url in the knowledgeRequest parameter, along with a \"site:www.pinterest.com\" filter, and print out the imageInsightsToken, the number of tags, the number of actions, and the first actionType")]
public static void VisualSearchUrlWithFilters(string subscriptionKey)
{
var client = new VisualSearchClient(new ClientCredentials(subscriptionKey));
try
{
// The image can be specified via URL, in the ImageInfo object
var ImageUrl = "https://www.publicdomainpictures.net/pictures/80000/velka/paris-eiffel-tower-1393127408EHt.jpg";
ImageInfo ImageInfo = new ImageInfo(url: ImageUrl);
// Optional filters inside the knowledgeRequest will restrict similar products and images to certain domains
Filters Filters = new Filters(site: "www.pinterest.com");
KnowledgeRequest KnowledgeRequest = new KnowledgeRequest(filters: Filters);
// An image binary is not necessary here, as the image is specified via URL
VisualSearchRequest VisualSearchRequest = new VisualSearchRequest(imageInfo: ImageInfo, knowledgeRequest: KnowledgeRequest);
var visualSearchResults = client.Images.VisualSearchMethodAsync(knowledgeRequest: VisualSearchRequest.ToString()).Result;
Console.WriteLine("Search visual search request with url of eiffel tower image");
if (visualSearchResults == null)
{
Console.WriteLine("No visual search result data.");
}
else
{
// Visual Search results
if (visualSearchResults.Image?.ImageInsightsToken != null)
{
Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}");
}
else
{
Console.WriteLine("Couldn't find image insights token!");
}
// List of tags
if (visualSearchResults.Tags.Count > 0)
{
var firstTagResult = visualSearchResults.Tags.First();
Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}");
// List of actions in first tag
if (firstTagResult.Actions.Count > 0)
{
var firstActionResult = firstTagResult.Actions.First();
Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}");
Console.WriteLine($"First tag action type: {firstActionResult.ActionType}");
}
else
{
Console.WriteLine("Couldn't find tag actions!");
}
}
else
{
Console.WriteLine("Couldn't find image tags!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will send an image insights token in the knowledgeRequest parameter, along with a cropArea object, and print out the imageInsightsToken, the number of tags, the number of actions, and the first actionType")]
public static void VisualSearchInsightsTokenWithCropArea(string subscriptionKey)
{
var client = new VisualSearchClient(new ClientCredentials(subscriptionKey));
try
{
// The image can be specified via an insights token, in the ImageInfo object
var ImageInsightsToken = "bcid_CA6BDBEA28D57D52E0B9D4B254F1DF0D*ccid_6J+8V1zi*thid_R.CA6BDBEA28D57D52E0B9D4B254F1DF0D";
// An optional crop area can be passed in to define a region of interest in the image
CropArea CropArea = new CropArea(top: (float)0.1, bottom: (float)0.5, left: (float)0.1, right: (float)0.9);
ImageInfo ImageInfo = new ImageInfo(imageInsightsToken: ImageInsightsToken, cropArea: CropArea);
// An image binary is not necessary here, as the image is specified via insights token
VisualSearchRequest VisualSearchRequest = new VisualSearchRequest(imageInfo: ImageInfo);
var visualSearchResults = client.Images.VisualSearchMethodAsync(knowledgeRequest: VisualSearchRequest.ToString()).Result;
Console.WriteLine("Search visual search request with url of eiffel tower image");
if (visualSearchResults == null)
{
Console.WriteLine("No visual search result data.");
}
else
{
// Visual Search results
if (visualSearchResults.Image?.ImageInsightsToken != null)
{
Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}");
}
else
{
Console.WriteLine("Couldn't find image insights token!");
}
// List of tags
if (visualSearchResults.Tags.Count > 0)
{
var firstTagResult = visualSearchResults.Tags.First();
Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}");
// List of actions in first tag
if (firstTagResult.Actions.Count > 0)
{
var firstActionResult = firstTagResult.Actions.First();
Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}");
Console.WriteLine($"First tag action type: {firstActionResult.ActionType}");
}
else
{
Console.WriteLine("Couldn't find tag actions!");
}
}
else
{
Console.WriteLine("Couldn't find image tags!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will send an image url in the knowledgeRequest parameter, along with a crop area, and print out the imageInsightsToken, the number of tags, the number of actions, and the first actionType")]
public static void VisualSearchUrlWithJson(string subscriptionKey)
{
var client = new VisualSearchClient(new ClientCredentials(subscriptionKey));
try
{
/*
* The visual search request can be passed in as a JSON string
* The image is specified via URL in the ImageInfo object, along with a crop area as shown below:
* {
* "imageInfo": {
* "url": "https://www.publicdomainpictures.net/pictures/80000/velka/paris-eiffel-tower-1393127408EHt.jpg",
* "cropArea": {
* "top": 0.1,
* "bottom": 0.5,
* "left": 0.1,
* "right": 0.9
* }
* },
* "knowledgeRequest": {
* "filters": {
* "site": "www.pinterest.com"
* }
* }
* }
*/
var VisualSearchRequestJSON = "{\"imageInfo\":{\"url\":\"https://www.publicdomainpictures.net/pictures/80000/velka/paris-eiffel-tower-1393127408EHt.jpg\",\"cropArea\":{\"top\":0.1,\"bottom\":0.5,\"left\":0.1,\"right\":0.9}},\"knowledgeRequest\":{\"filters\":{\"site\":\"www.pinterest.com\"}}}";
// An image binary is not necessary here, as the image is specified via URL
var visualSearchResults = client.Images.VisualSearchMethodAsync(knowledgeRequest: VisualSearchRequestJSON).Result;
Console.WriteLine("Search visual search request with url of eiffel tower image");
if (visualSearchResults == null)
{
Console.WriteLine("No visual search result data.");
}
else
{
// Visual Search results
if (visualSearchResults.Image?.ImageInsightsToken != null)
{
Console.WriteLine($"Uploaded image insights token: {visualSearchResults.Image.ImageInsightsToken}");
}
else
{
Console.WriteLine("Couldn't find image insights token!");
}
// List of tags
if (visualSearchResults.Tags.Count > 0)
{
var firstTagResult = visualSearchResults.Tags.First();
Console.WriteLine($"Visual search tag count: {visualSearchResults.Tags.Count}");
// List of actions in first tag
if (firstTagResult.Actions.Count > 0)
{
var firstActionResult = firstTagResult.Actions.First();
Console.WriteLine($"First tag action count: {firstTagResult.Actions.Count}");
Console.WriteLine($"First tag action type: {firstActionResult.ActionType}");
}
else
{
Console.WriteLine("Couldn't find tag actions!");
}
}
else
{
Console.WriteLine("Couldn't find image tags!");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\VisualSearch\src\Microsoft.Bing.Search.VisualSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="TestImages\*.jpg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{1005D237-A9A8-4B42-AAC4-35D0EF69534D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.VisualSearch", "..\..\..\sdk\VisualSearch\src\Microsoft.Bing.Search.VisualSearch.csproj", "{4FBDA580-C49D-408D-8FA9-F966DA8D9C29}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{1005D237-A9A8-4B42-AAC4-35D0EF69534D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1005D237-A9A8-4B42-AAC4-35D0EF69534D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1005D237-A9A8-4B42-AAC4-35D0EF69534D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1005D237-A9A8-4B42-AAC4-35D0EF69534D}.Release|Any CPU.Build.0 = Release|Any CPU
{4FBDA580-C49D-408D-8FA9-F966DA8D9C29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4FBDA580-C49D-408D-8FA9-F966DA8D9C29}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FBDA580-C49D-408D-8FA9-F966DA8D9C29}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FBDA580-C49D-408D-8FA9-F966DA8D9C29}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

288
samples/BingSearchSamples/BingWebSearch/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,288 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

Просмотреть файл

@ -0,0 +1,7 @@
## bing-search-dotnet Changelog
<a name="1.0.0"></a>
# 1.0.0 (2017-10-31)
*Features*
* Initial release with EntitySearch samples

Просмотреть файл

@ -0,0 +1,76 @@
# Contributing to [project-title]
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
- [Code of Conduct](#coc)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
## <a name="coc"></a> Code of Conduct
Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
## <a name="issue"></a> Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help us by
[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.
## <a name="feature"></a> Want a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## <a name="submit"></a> Submission Guidelines
### <a name="submit-issue"></a> Submitting an Issue
Before you submit an issue, search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue.
Help us to maximize the effort we can spend fixing issues and adding new
features, by not reporting duplicate issues. Providing the following information will increase the
chances of your issue being dealt with quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
* **Version** - what version is affected (e.g. 0.1.2)
* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
* **Browsers and Operating System** - is this a problem with all browsers?
* **Reproduce the Error** - provide a live example or a unambiguous set of steps
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git fork:
* Commit your changes using a descriptive commit message
* Push your fork to GitHub:
* In GitHub, create a pull request
* If we suggest changes then:
* Make the required updates.
* Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
git push -f
```
That's it! Thank you for your contribution!

Просмотреть файл

@ -0,0 +1,66 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Method)]
class ExampleAttribute : Attribute
{
public string ExampleDescription { get; private set; }
public ExampleAttribute(string description)
{
this.ExampleDescription = description;
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

Просмотреть файл

@ -0,0 +1,99 @@
namespace bing_search_dotnet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class Program
{
static IDictionary<string, ExampleAbstraction> SampleMap = null;
const string Separator = "--------------------------------------------------";
static void Main(string[] args)
{
do
{
/*
* Decide which sample to showcase
*/
Console.WriteLine("Hi! Welcome to Web Search Samples");
if (SampleMap == null)
{
LoadSampleOptions();
}
ExampleAbstraction examples;
var input = "WebSearch";
if (!SampleMap.TryGetValue(input, out examples) || examples?.Examples?.Count == 0)
{
Console.WriteLine("Sorry, \"{0}\" doesn't seem to be a valid sample.", input);
continue;
}
/*
* Decide which example from the sample to showcase
*/
Console.WriteLine("Ok. Now, pick the number corresponding to an example you'd like to run: ");
Console.WriteLine(Separator);
for (var i = 0; i < examples.Examples.Count; i++)
{
Console.WriteLine(i + ": " + examples.Examples[i].Description);
}
Console.WriteLine(Separator);
input = Console.ReadLine();
int exampleIndex;
if (!int.TryParse(input, out exampleIndex) || exampleIndex < 0 || exampleIndex >= examples.Examples.Count)
{
Console.WriteLine("Sorry, \"{0}\" is not a valid example number.", input);
continue;
}
Console.WriteLine("Ok, now please enter your subscription key:");
input = Console.ReadLine();
Console.WriteLine("Ok, running example {0} with subscription key \"{1}\"", exampleIndex, input);
Console.WriteLine(Separator);
examples.Examples[exampleIndex].Invoke(input);
} while (DecideRetry());
}
/// <summary>
/// Reflects through the assembly to find which samples can be explored
/// </summary>
private static void LoadSampleOptions()
{
SampleMap = new Dictionary<string, ExampleAbstraction>();
var samples = Assembly.GetEntryAssembly().DefinedTypes.Where(type => type.GetCustomAttribute<SampleCollectionAttribute>() != null);
foreach (var sample in samples)
{
var sampleImpl = new ExampleAbstraction(sample);
sampleImpl.Load();
SampleMap.Add(sample.GetCustomAttribute<SampleCollectionAttribute>().SampleName, sampleImpl);
}
}
/// <summary>
/// Asks the user whether they should continue and look for another sample, or quit
/// </summary>
/// <returns></returns>
private static bool DecideRetry()
{
Console.WriteLine();
Console.WriteLine("Would you like to look at another example (ENTER) or would you like to quit (q or CTRL+C)?");
return Console.ReadKey().KeyChar != 'q';
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
# The Bing Web Search SDK Sample
This sample will show you how to get up and running using the Bing Web Search SDK. This example will cover a few usecases and hopefully express best practices for interacting with the data from this API. For more information on the Bing Web Search API v7, you can navigate to: https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/. Exhaustive reference documentation including description of parameters, their values, and supported markets is [here](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-web-api-v7-reference).
If you are looking for amending samples to suit your needs, the single, most important file is WebSearchSamples.cs. See how you can access this file in the "Quickstart" section below.
## Features
This sample references the Bing Web Search SDK, which is a stand-alone package for the v7 version of this API. All-in-one package including all the Bing Search APIs on Cognitive Services will be available in future.
This example provides sample usecases of the the [Bing Web Search v7](https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/)
* Using the **Bing Web Search Nuget Package** at https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.WebSearch/1.2.0
## Getting Started
### Prerequisites
- Visual Studio 2017. If required, you can download free community version from here: https://www.visualstudio.com/vs/community/.
- A cognitive services API key is required to authenticate SDK calls. You can [sign up here](https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-web-search-api) for the **free** trial key. This trial key is good for 30 days with 3 calls per second. **Alternately**, for production scenario, you can buy access key from here: https://portal.azure.com/#create/Microsoft.CognitiveServicesBingSearch-v7. While buying access key you may want to consider which tier is appropriate for you. More information is [here](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/web/).
- .NET core SDK (ability to run .netcore 1.1 apps). You can get CORE, Framework, and Runtime from here: https://www.microsoft.com/net/download/.
### Quickstart
To get the Bing Web Search sample running locally, follow these steps:
1. git clone https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples.git
2. Open cognitive-services-dotnet-sdk-samples\BingSearchv7\BingWebSearch\bing-search-dotnet.sln from Visual Studio 2017
3. npm install https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.WebSearch/1.2.0 from Tools > Nuget Package Manager > Package Manager Console. **Alternately**, you can go to Project > Manage Nuget Packages and search for "Microsoft.Azure.CognitiveServices.Search.WebSearch" in the "Browse" tab, and click on "Install".
4. Click on "bing-search-dotnet" for debug/release version from the top of Visual Studio. This will run examples from the **BingWebSearch\WebSearchSamples.cs** file. **Alternately** you can build and run solution in separate steps.
### Note:
Change TargetFramework in bing-search-dotnet.csproj to “netcoreapp1.1” if you have .NET Framework version as 2.1.2. [ Older ] as follows:
**Current**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
````
**Revision**
````
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
````
## Resources
- [Bing Web Search API Demo & capabilities](https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/)
- [Bing Web Search Reference Document](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-web-api-v7-reference)
- [Bing Web Search Nuget Package](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Search.WebSearch/1.2.0)
- [Bing Web Search Dotnet SDK (source code)](https://github.com/Azure/azure-sdk-for-net/tree/psSdkJson6/src/SDKs/CognitiveServices/dataPlane/Search/BingWebSearch)
- Support channels: [Stack Overflow](https://stackoverflow.com/questions/tagged/bing-search) or [Azure Support](https://azure.microsoft.com/en-us/support/options/)

Просмотреть файл

@ -0,0 +1,15 @@
namespace bing_search_dotnet
{
using System;
[AttributeUsage(AttributeTargets.Class)]
class SampleCollectionAttribute : Attribute
{
public string SampleName { get; private set; }
public SampleCollectionAttribute(string name)
{
this.SampleName = name;
}
}
}

Просмотреть файл

@ -0,0 +1,235 @@
namespace bing_search_dotnet.Samples
{
using System;
using System.Linq;
using System.Text;
using Microsoft.Bing.WebSearch;
using Microsoft.Bing.WebSearch.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using Credentials;
[SampleCollection("WebSearch")]
public class WebSearchSamples
{
[Example("This will look up a single query (Xbox) and print out name and url for first web, image, news and videos results")]
public static void WebSearchResultTypesLookup(string subscriptionKey)
{
var client = new WebSearchClient(new ClientCredentials(subscriptionKey));
try
{
var webData = client.Web.SearchAsync(query: "Xbox").Result;
Console.WriteLine("Searched for Query# \" Xbox \"");
//WebPages
if (webData?.WebPages?.Value?.Count > 0)
{
// find the first web page
var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
if (firstWebPagesResult != null)
{
Console.WriteLine("Webpage Results#{0}", webData.WebPages.Value.Count);
Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
}
else
{
Console.WriteLine("Couldn't find web results!");
}
}
else
{
Console.WriteLine("Didn't see any Web data..");
}
//Images
if (webData?.Images?.Value?.Count > 0)
{
// find the first image result
var firstImageResult = webData.Images.Value.FirstOrDefault();
if (firstImageResult != null)
{
Console.WriteLine("Image Results#{0}", webData.Images.Value.Count);
Console.WriteLine("First Image result name: {0} ", firstImageResult.Name);
Console.WriteLine("First Image result URL: {0} ", firstImageResult.ContentUrl);
}
else
{
Console.WriteLine("Couldn't find first image results!");
}
}
else
{
Console.WriteLine("Didn't see any image data..");
}
//News
if (webData?.News?.Value?.Count > 0)
{
// find the first news result
var firstNewsResult = webData.News.Value.FirstOrDefault();
if (firstNewsResult != null)
{
Console.WriteLine("News Results#{0}", webData.News.Value.Count);
Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
}
else
{
Console.WriteLine("Couldn't find any News results!");
}
}
else
{
Console.WriteLine("Didn't see first news data..");
}
//Videos
if (webData?.Videos?.Value?.Count > 0)
{
// find the first video result
var firstVideoResult = webData.Videos.Value.FirstOrDefault();
if (firstVideoResult != null)
{
Console.WriteLine("Video Results#{0}", webData.Videos.Value.Count);
Console.WriteLine("First Video result name: {0} ", firstVideoResult.Name);
Console.WriteLine("First Video result URL: {0} ", firstVideoResult.ContentUrl);
}
else
{
Console.WriteLine("Couldn't find first video results!");
}
}
else
{
Console.WriteLine("Didn't see any video data..");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search (Best restaurants in Seattle), verify number of results and print out name and url of first result")]
public static void WebResultsWithCountAndOffset(string subscriptionKey)
{
var client = new WebSearchClient(new ClientCredentials(subscriptionKey));
try
{
var webData = client.Web.SearchAsync(query: "Best restaurants in Seattle", offset:10, count:20).Result;
Console.WriteLine("Searched for Query# \" Best restaurants in Seattle \"");
if (webData?.WebPages?.Value?.Count > 0)
{
// find the first web page
var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
if (firstWebPagesResult != null)
{
Console.WriteLine("Web Results#{0}", webData.WebPages.Value.Count);
Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
}
else
{
Console.WriteLine("Couldn't find first web result!");
}
}
else
{
Console.WriteLine("Didn't see any Web data..");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search (Microsoft) with response filters to news and print details of news")]
public static void WebSearchWithResponseFilter(string subscriptionKey)
{
var client = new WebSearchClient(new ClientCredentials(subscriptionKey));
try
{
IList<string> responseFilterstrings = new List<string>() {"news"};
var webData = client.Web.SearchAsync(query: "Microsoft", responseFilter: responseFilterstrings).Result;
Console.WriteLine("Searched for Query# \" Microsoft \" with response filters \"news\"");
//News
if (webData?.News?.Value?.Count > 0)
{
// find the first news result
var firstNewsResult = webData.News.Value.FirstOrDefault();
if (firstNewsResult != null)
{
Console.WriteLine("News Results#{0}", webData.News.Value.Count);
Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
}
else
{
Console.WriteLine("Couldn't find first News results!");
}
}
else
{
Console.WriteLine("Didn't see any News data..");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
[Example("This will search (Lady Gaga) with answerCount and promote parameters and print details of answers")]
public static void WebSearchWithAnswerCountPromoteAndSafeSearch(string subscriptionKey)
{
var client = new WebSearchClient(new ClientCredentials(subscriptionKey));
try
{
IList<string> promoteAnswertypeStrings = new List<string>() { "videos"};
var webData = client.Web.SearchAsync(query: "Lady Gaga", answerCount: 2, promote: promoteAnswertypeStrings, safeSearch: SafeSearch.Strict).Result;
Console.WriteLine("Searched for Query# \" Lady Gaga \"");
if (webData?.Videos?.Value?.Count > 0)
{
var firstVideosResult = webData.Videos.Value.FirstOrDefault();
if (firstVideosResult != null)
{
Console.WriteLine("Video Results#{0}", webData.Videos.Value.Count);
Console.WriteLine("First Video result name: {0} ", firstVideosResult.Name);
Console.WriteLine("First Video result URL: {0} ", firstVideosResult.ContentUrl);
}
else
{
Console.WriteLine("Couldn't find videos results!");
}
}
else
{
Console.WriteLine("Didn't see any data..");
}
}
catch (Exception ex)
{
Console.WriteLine("Encountered exception. " + ex.Message);
}
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\sdk\WebSearch\src\Microsoft.Bing.Search.WebSearch.csproj" />
<ProjectReference Include="..\common\Common\Common.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bing-search-dotnet", "bing-search-dotnet.csproj", "{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "..\common\Common\Common.csproj", "{2AB26A8C-FABB-4B27-9902-04A0C557084D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bing.Search.WebSearch", "..\..\..\sdk\WebSearch\src\Microsoft.Bing.Search.WebSearch.csproj", "{50E7E82B-03F7-436F-958F-0B460BE12A5E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BAB52EF-578B-44C0-9708-F9E7EFAC3DD5}.Release|Any CPU.Build.0 = Release|Any CPU
{2AB26A8C-FABB-4B27-9902-04A0C557084D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2AB26A8C-FABB-4B27-9902-04A0C557084D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2AB26A8C-FABB-4B27-9902-04A0C557084D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2AB26A8C-FABB-4B27-9902-04A0C557084D}.Release|Any CPU.Build.0 = Release|Any CPU
{50E7E82B-03F7-436F-958F-0B460BE12A5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{50E7E82B-03F7-436F-958F-0B460BE12A5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{50E7E82B-03F7-436F-958F-0B460BE12A5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{50E7E82B-03F7-436F-958F-0B460BE12A5E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {23A7C819-7D1E-4C8E-8863-7190AC370D3E}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Credentials
{
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
public class ClientCredentials : ServiceClientCredentials
{
private readonly string subscriptionKey;
/// <summary>
/// Creates a new instance of the ClientCredentials class
/// </summary>
/// <param name="subscriptionKey">The subscription key to authenticate and authorize as</param>
public ClientCredentials(string subscriptionKey)
{
this.subscriptionKey = subscriptionKey;
}
/// <summary>
/// Add the Basic Authentication Header to each outgoing request
/// </summary>
/// <param name="request">The outgoing request</param>
/// <param name="cancellationToken">A token to cancel the operation</param>
public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
throw new ArgumentNullException("request");
request.Headers.Add("Ocp-Apim-Subscription-Key", this.subscriptionKey);
return Task.FromResult<object>(null);
}
}
}

Просмотреть файл

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.8" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="2.3.22" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common.csproj", "{3097D828-F74F-4301-A142-16330E3BAB01}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3097D828-F74F-4301-A142-16330E3BAB01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3097D828-F74F-4301-A142-16330E3BAB01}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3097D828-F74F-4301-A142-16330E3BAB01}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3097D828-F74F-4301-A142-16330E3BAB01}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0DA104B0-7EA0-41FD-ADA5-2D0329DDAADB}
EndGlobalSection
EndGlobal