Skip to content

Commit 33ca7fb

Browse files
authored
Merge pull request #4 from Microsoft/peaky
Adding all Auth Samples
2 parents a36a87a + 926db96 commit 33ca7fb

File tree

69 files changed

+918
-7
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+918
-7
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<configuration>
3+
<startup>
4+
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
5+
</startup>
6+
<runtime>
7+
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
8+
<dependentAssembly>
9+
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
10+
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
11+
</dependentAssembly>
12+
</assemblyBinding>
13+
</runtime>
14+
<system.serviceModel>
15+
<extensions>
16+
<!-- In this extension section we are introducing all known service bus extensions. User can remove the ones they don't need. -->
17+
<behaviorExtensions>
18+
<add name="connectionStatusBehavior" type="Microsoft.ServiceBus.Configuration.ConnectionStatusElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
19+
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
20+
<add name="serviceRegistrySettings" type="Microsoft.ServiceBus.Configuration.ServiceRegistrySettingsElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
21+
</behaviorExtensions>
22+
<bindingElementExtensions>
23+
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
24+
<add name="tcpRelayTransport" type="Microsoft.ServiceBus.Configuration.TcpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
25+
<add name="httpRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
26+
<add name="httpsRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpsRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
27+
<add name="onewayRelayTransport" type="Microsoft.ServiceBus.Configuration.RelayedOnewayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
28+
</bindingElementExtensions>
29+
<bindingExtensions>
30+
<add name="basicHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.BasicHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
31+
<add name="webHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WebHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
32+
<add name="ws2007HttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WS2007HttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
33+
<add name="netTcpRelayBinding" type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
34+
<add name="netOnewayRelayBinding" type="Microsoft.ServiceBus.Configuration.NetOnewayRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
35+
<add name="netEventRelayBinding" type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
36+
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
37+
</bindingExtensions>
38+
</extensions>
39+
</system.serviceModel>
40+
<appSettings>
41+
<!-- Service Bus specific app setings for messaging connections -->
42+
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[your secret]" />
43+
</appSettings>
44+
</configuration>

ClientLibraryConsoleAppSample/ClientLibraryConsoleAppSample.csproj

Lines changed: 209 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 15
4+
VisualStudioVersion = 15.0.26228.9
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientLibraryConsoleAppSample", "ClientLibraryConsoleAppSample.csproj", "{F7AC99CF-0972-4727-AC95-F537EF4EB4EA}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{F7AC99CF-0972-4727-AC95-F537EF4EB4EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{F7AC99CF-0972-4727-AC95-F537EF4EB4EA}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{F7AC99CF-0972-4727-AC95-F537EF4EB4EA}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{F7AC99CF-0972-4727-AC95-F537EF4EB4EA}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
EndGlobal
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
7+
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
8+
using Microsoft.VisualStudio.Services.Client;
9+
using Microsoft.VisualStudio.Services.Common;
10+
using Microsoft.VisualStudio.Services.WebApi;
11+
12+
namespace ClientLibraryConsoleAppSample
13+
{
14+
class Program
15+
{
16+
//Console application to execute a user defined work item query
17+
static void Main(string[] args)
18+
{
19+
//=========== Config [edit these] ===================
20+
string collectionUri = "https://fabrikam-fiber-inc.visualstudio.com";
21+
Wiql query = new Wiql() { Query = "Select [State], [Title] from WorkItems where [Work Item Type] = 'Bug' And [Tags] Contains 'findMe'" };
22+
//===================================================
23+
24+
//Prompt user for credential for collection specified above
25+
VssCredentials cred = new VssClientCredentials(false);
26+
cred.PromptType = CredentialPromptType.PromptIfNeeded;
27+
VssConnection connection = new VssConnection(new Uri(collectionUri), cred);
28+
29+
//create http client and query for resutls
30+
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
31+
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;
32+
33+
//Display reults in console
34+
if (queryResults == null || queryResults.WorkItems.Count() == 0)
35+
{
36+
Console.WriteLine("Query did not find any results");
37+
}
38+
else
39+
{
40+
foreach (var item in queryResults.WorkItems)
41+
{
42+
Console.WriteLine(item.Id);
43+
}
44+
}
45+
46+
//prevetns console from closing
47+
while (true)
48+
{
49+
50+
}
51+
52+
}
53+
}
54+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// General Information about an assembly is controlled through the following
6+
// set of attributes. Change these attribute values to modify the information
7+
// associated with an assembly.
8+
[assembly: AssemblyTitle("ConsoleApp1")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("ConsoleApp1")]
13+
[assembly: AssemblyCopyright("Copyright © 2017")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// Setting ComVisible to false makes the types in this assembly not visible
18+
// to COM components. If you need to access a type in this assembly from
19+
// COM, set the ComVisible attribute to true on that type.
20+
[assembly: ComVisible(false)]
21+
22+
// The following GUID is for the ID of the typelib if this project is exposed to COM
23+
[assembly: Guid("f7ac99cf-0972-4727-ac95-f537ef4eb4ea")]
24+
25+
// Version information for an assembly consists of the following four values:
26+
//
27+
// Major Version
28+
// Minor Version
29+
// Build Number
30+
// Revision
31+
//
32+
// You can specify all the values or you can default the Build and Revision Numbers
33+
// by using the '*' as shown below:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Client Libraries Sample
2+
3+
The [Client Libraries](https://www.visualstudio.com/en-us/docs/integrate/get-started/client-libraries/dotnet) are .NET libraries made to simplify integration with Visual Studio Team Services and Team Foundation Server (2015 and later). They allow access to both the Traditional Client Object Model and [new REST APIs](https://www.visualstudio.com/en-us/docs/integrate/api/overview).
4+
5+
## Sample Application
6+
7+
This buildable sample will walk you through the steps to create an application which uses the [Client Libraries](https://www.visualstudio.com/en-us/docs/integrate/get-started/client-libraries/dotnet) to open an interactive login prompt and use that authentication state to execute a user pre-defined query written in [Work Item Query Language](https://msdn.microsoft.com/en-us/library/bb130198(v=vs.90).aspx). Query results are output into the console.
8+
9+
## Step 1: Clone or download vsts-auth-samples repository
10+
11+
From a shell or command line:
12+
```no-highlight
13+
git clone https://github.com/Microsoft/vsts-auth-samples.git
14+
```
15+
16+
## Step 2: Run the sample
17+
18+
1. Navigate to the sample in cloned repo `vsts-auth-samples/ClientLibraryConsoleAppSample/`
19+
2. Use [Nuget package restore](https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore) to ensure you have all dependencies installed
20+
3. Open the solution file `ClientLibraryConsoleAppSample.sln` in [Visual Studio IDE 2017](https://www.visualstudio.com/downloads/)
21+
4. Open CS file `Program.cs` and there will be 2 input fields:
22+
* `collectionUri` - Mutable value. This is the url to your VSTS/TFS account.
23+
* `query` - Mutable value. This is the WIQL query you want to execute. Replace this with any query you want to execute.
24+
5. Build and run solution. After running you should see a list of the IDs all work items which match your query restrictions.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<packages>
3+
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net452" />
4+
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net452" />
5+
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.13.5" targetFramework="net452" />
6+
<package id="Microsoft.TeamFoundation.DistributedTask.Common.Contracts" version="15.118.0-preview" targetFramework="net452" />
7+
<package id="Microsoft.TeamFoundationServer.Client" version="15.118.0-preview" targetFramework="net452" />
8+
<package id="Microsoft.TeamFoundationServer.ExtendedClient" version="15.118.0-preview" targetFramework="net452" />
9+
<package id="Microsoft.Tpl.Dataflow" version="4.5.24" targetFramework="net452" />
10+
<package id="Microsoft.VisualStudio.Services.Client" version="15.118.0-preview" targetFramework="net452" />
11+
<package id="Microsoft.VisualStudio.Services.InteractiveClient" version="15.118.0-preview" targetFramework="net452" />
12+
<package id="Newtonsoft.Json" version="8.0.3" targetFramework="net452" />
13+
<package id="System.IdentityModel.Tokens.Jwt" version="4.0.2.206221351" targetFramework="net452" />
14+
<package id="WindowsAzure.ServiceBus" version="3.3.2" targetFramework="net452" />
15+
</packages>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup Label="Configuration" Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
4+
<OutputType>exe</OutputType>
5+
</PropertyGroup>
6+
7+
<PropertyGroup>
8+
<Description>DirSearcherClient Console Application</Description>
9+
<Authors>Vittorio</Authors>
10+
<TargetFramework>netcoreapp1.0</TargetFramework>
11+
<AssemblyName>DeviceProfileSample</AssemblyName>
12+
<PackageId>DirSearcherClient</PackageId>
13+
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
14+
<GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
15+
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
16+
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
17+
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
18+
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
19+
<ApplicationIcon />
20+
<OutputTypeEx>exe</OutputTypeEx>
21+
<StartupObject />
22+
</PropertyGroup>
23+
24+
<ItemGroup>
25+
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="3.13.8" />
26+
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
27+
</ItemGroup>
28+
29+
<ItemGroup Condition=" '$(TargetFramework)' == 'dnxcore50' ">
30+
<PackageReference Include="Microsoft.CSharp" Version="4.0.1" />
31+
<PackageReference Include="System.Collections" Version="4.0.11" />
32+
<PackageReference Include="System.Console" Version="4.0.0" />
33+
<PackageReference Include="System.Linq" Version="4.1.0" />
34+
<PackageReference Include="System.Threading" Version="4.0.11" />
35+
<PackageReference Include="System.Net.Http" Version="4.1.1" />
36+
</ItemGroup>
37+
38+
</Project>

DeviceProfileSample/Program.cs

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
using Microsoft.IdentityModel.Clients.ActiveDirectory;
2+
using Newtonsoft.Json.Linq;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Globalization;
6+
using System.Linq;
7+
using System.Net.Http;
8+
using System.Net.Http.Headers;
9+
using System.Text;
10+
using System.Threading.Tasks;
11+
12+
namespace DeviceProfileSample
13+
{
14+
public class Program
15+
{
16+
public const string resource_vsts = "499b84ac-1321-427f-aa17-267ca6975798";
17+
public const string clientId_vs = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1";
18+
public static void Main(string[] args)
19+
{
20+
//============= Config [Edit these with your settings] =====================
21+
var vstsAccountUri = "https://mseng.VisualStudio.com";
22+
var restEndpoint = "_apis/projects?api-version=2.0";
23+
//==========================================================================
24+
25+
UserData(vstsAccountUri,restEndpoint);
26+
27+
//prevents console from closing immediately at the end of output
28+
Console.ReadLine();
29+
}
30+
31+
static void UserData(string vstsAccountUri, string restEndpoint)
32+
{
33+
//get auth token
34+
AuthenticationResult result = GetToken(null);
35+
var authHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
36+
37+
//call VSTS REST API
38+
using (var client = new HttpClient())
39+
{
40+
client.BaseAddress = new Uri(vstsAccountUri);
41+
client.DefaultRequestHeaders.Accept.Clear();
42+
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
43+
client.DefaultRequestHeaders.Add("User-Agent", "VstsRestApiSamples");
44+
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
45+
client.DefaultRequestHeaders.Authorization = authHeader;
46+
47+
//connect to REST endpoint
48+
HttpResponseMessage response = client.GetAsync(restEndpoint).Result;
49+
50+
if (response.IsSuccessStatusCode)
51+
{
52+
Console.WriteLine("\tSuccessful REST call\n");
53+
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
54+
}
55+
else
56+
{
57+
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
58+
}
59+
}
60+
}
61+
62+
static AuthenticationResult GetToken(string tenant)
63+
{
64+
AuthenticationContext ctx = null;
65+
if (tenant != null)
66+
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
67+
else
68+
{
69+
ctx = new AuthenticationContext("https://login.microsoftonline.com/common");
70+
if (ctx.TokenCache.Count > 0)
71+
{
72+
string homeTenant = ctx.TokenCache.ReadItems().First().TenantId;
73+
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant);
74+
}
75+
}
76+
AuthenticationResult result = null;
77+
try
78+
{
79+
result = ctx.AcquireTokenSilentAsync(resource_vsts, clientId_vs).Result;
80+
}
81+
catch (Exception exc)
82+
{
83+
var adalEx = exc.InnerException as AdalException;
84+
if ((adalEx != null) && (adalEx.ErrorCode == "failed_to_acquire_token_silently"))
85+
{
86+
result = GetTokenViaCode(ctx);
87+
}
88+
else
89+
{
90+
Console.ForegroundColor = ConsoleColor.Red;
91+
Console.WriteLine("Something went wrong.");
92+
Console.WriteLine("Message: " + exc.InnerException.Message + "\n");
93+
}
94+
}
95+
return result;
96+
}
97+
98+
static AuthenticationResult GetTokenViaCode(AuthenticationContext ctx)
99+
{
100+
AuthenticationResult result = null;
101+
try
102+
{
103+
DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync(resource_vsts, clientId_vs).Result;
104+
Console.ResetColor();
105+
Console.WriteLine("You need to sign in.");
106+
Console.WriteLine("Message: " + codeResult.Message + "\n");
107+
result = ctx.AcquireTokenByDeviceCodeAsync(codeResult).Result;
108+
}
109+
catch (Exception exc)
110+
{
111+
Console.ForegroundColor = ConsoleColor.Red;
112+
Console.WriteLine("Something went wrong.");
113+
Console.WriteLine("Message: " + exc.Message + "\n");
114+
}
115+
return result;
116+
}
117+
}
118+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// General Information about an assembly is controlled through the following
6+
// set of attributes. Change these attribute values to modify the information
7+
// associated with an assembly.
8+
[assembly: AssemblyTitle("DirSearcherClient")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("DirSearcherClient")]
13+
[assembly: AssemblyCopyright("Copyright © 2015")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// Setting ComVisible to false makes the types in this assembly not visible
18+
// to COM components. If you need to access a type in this assembly from
19+
// COM, set the ComVisible attribute to true on that type.
20+
[assembly: ComVisible(false)]
21+
22+
// The following GUID is for the ID of the typelib if this project is exposed to COM
23+
[assembly: Guid("cf4aa24b-620d-4bb0-a89b-830e8b304b3a")]

0 commit comments

Comments
 (0)