Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a sample for how to connect to FitBit from a console app. #218

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Fitbit/Fitbit-WithSamples.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{C284DD15-3355-4C6A-9EE0-D0A3BEA4D8A5}"
ProjectSection(SolutionItems) = preProject
Expand All @@ -21,6 +21,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebMVC.Portable", "..
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebMVCOAuth2", "..\SampleWebMVCOAuth2\SampleWebMVCOAuth2.csproj", "{61C8AD29-A128-442E-BF0B-539A990B15C7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleConsole", "..\SampleConsole\SampleConsole\SampleConsole.csproj", "{11886EF6-6527-4061-A859-3191F7E3B192}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -58,6 +60,12 @@ Global
{61C8AD29-A128-442E-BF0B-539A990B15C7}.Release|Any CPU.Build.0 = Release|Any CPU
{61C8AD29-A128-442E-BF0B-539A990B15C7}.TrialRelease|Any CPU.ActiveCfg = Release|Any CPU
{61C8AD29-A128-442E-BF0B-539A990B15C7}.TrialRelease|Any CPU.Build.0 = Release|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.Release|Any CPU.Build.0 = Release|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.TrialRelease|Any CPU.ActiveCfg = Release|Any CPU
{11886EF6-6527-4061-A859-3191F7E3B192}.TrialRelease|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
10 changes: 10 additions & 0 deletions SampleConsole/SampleConsole/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
<add key="FitbitConsumerKey" value="Your_value_here" />
<add key="FitbitConsumerSecret" value="Your_value_here" />
</appSettings>
</configuration>
143 changes: 143 additions & 0 deletions SampleConsole/SampleConsole/AuthorizationHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
using Fitbit.Api.Portable;
using Fitbit.Api.Portable.OAuth2;
using OutputColorizer;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SampleConsole
{
public static class AuthorizationHelper
{
public static FitbitClient GetAuthorizedFitBitClient(params string[] scopes)
{
// try to retrieve the token from disk
OAuth2AccessToken token = GetAccessTokenAsync(scopes).Result;

return new FitbitClient(new FitbitAppCredentials() { ClientId = Options.ClientId, ClientSecret = Options.ClientSecret }, token, true);
}

public static async Task<OAuth2AccessToken> GetAccessTokenAsync(params string[] scopes)
{
var token = ReadTokenFromDisk();
if (token == null || token.UtcExpirationDate < DateTime.Now.ToUniversalTime())
{
// we need admin to retrieve the token automatically
RestartAsElevatedIfNeeded();

token = await AuthorizeToFitBitAsync(scopes.Length == 0 ? Options.AllScopes : scopes);

SaveTokenToFile(token);
}

return token;
}

private static void SaveTokenToFile(OAuth2AccessToken token)
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(OAuth2AccessToken));
using (StreamWriter sw = new StreamWriter("token.dat"))
{
ser.Serialize(sw, token);
}
}
catch
{
}
}

private static OAuth2AccessToken ReadTokenFromDisk()
{
if (!File.Exists("token.dat"))
{
return null;
}

try
{
XmlSerializer ser = new XmlSerializer(typeof(OAuth2AccessToken));
using (StreamReader sr = new StreamReader("token.dat"))
{
return ser.Deserialize(sr) as OAuth2AccessToken;
}
}
catch
{
return null;
}
}

private static async Task<OAuth2AccessToken> AuthorizeToFitBitAsync(string[] scopes)
{
Colorizer.WriteLine("Sending authorization request...");
string scope = string.Join("%20", scopes);
string authorizeUrl = $"https://www.fitbit.com/oauth2/authorize?response_type=code&client_id={Options.ClientId}&scope={scope}&expires_in=86400";
Process.Start(authorizeUrl);

Colorizer.WriteLine("Waiting for callback at [Yellow!http://localhost]");
string code;
using (HttpListener listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost/");
listener.Start();
HttpListenerContext context = listener.GetContext();

Colorizer.WriteLine("Request received, retrieving code");
HttpListenerRequest request = context.Request;

//retrieve the code from the raw request.
code = request.QueryString["code"];
}

Colorizer.WriteLine("Exchanging code for authentication token");
using (HttpClient hc = new HttpClient())
{
HttpRequestMessage requestMsg = new HttpRequestMessage();
requestMsg.Method = HttpMethod.Post;
requestMsg.RequestUri = new Uri("https://api.fitbit.com/oauth2/token");
string authorizationHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{Options.ClientId}:{Options.ClientSecret}"));
requestMsg.Headers.Add("Authorization", "Basic " + authorizationHeader);
requestMsg.Content = new StringContent($"client_id={Options.ClientSecret}&grant_type=authorization_code&code={code}", Encoding.ASCII, "application/x-www-form-urlencoded");

Colorizer.Write("Making request...");
using (var responseMsg = await hc.SendAsync(requestMsg))
{
Colorizer.WriteLine("[Green!done].");
if (responseMsg.IsSuccessStatusCode)
{
var tok = OAuth2Helper.ParseAccessTokenResponse(await responseMsg.Content.ReadAsStringAsync());
tok.UtcExpirationDate = DateTime.Now.ToUniversalTime().AddSeconds(tok.ExpiresIn);

return tok;
}
}
}

return null;
}

private static void RestartAsElevatedIfNeeded()
{
// we can't authorize if we are not admin because we require access to register a listener to http://localhost.
if (!WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
{
// start the same process (as admin)
Process elevatedProcess = new Process();
elevatedProcess.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location;
elevatedProcess.StartInfo.Arguments = string.Join(" ", Environment.GetCommandLineArgs()); // pass whatever arguments were passed before.
elevatedProcess.StartInfo.Verb = "runas"; //run as admin
elevatedProcess.Start();

Environment.Exit(0);
}
}
}
}
15 changes: 15 additions & 0 deletions SampleConsole/SampleConsole/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleConsole
{
public class Options
{
public static string ClientId = System.Configuration.ConfigurationManager.AppSettings["FitbitConsumerKey"];
public static string ClientSecret = System.Configuration.ConfigurationManager.AppSettings["FitbitConsumerSecret"];
public static string[] AllScopes = new string[] { "activity ", "nutrition ", "heartrate ", "location ", "nutrition ", "profile ", "settings ", "sleep ", "social ", "weight" };
}
}
31 changes: 31 additions & 0 deletions SampleConsole/SampleConsole/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Fitbit.Api.Portable;
using Fitbit.Models;
using OutputColorizer;
using System;
using System.Collections.Generic;
using System.IO;

namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
// Authorize with FitBit
FitbitClient fc = AuthorizationHelper.GetAuthorizedFitBitClient("activity ", "nutrition ", "heartrate ", "location ", "nutrition ", "profile ", "settings ", "sleep ", "social ", "weight");

// Retrieve the weight information for today
DateTime start = DateTime.Now;
Colorizer.Write("Processing [Yellow!{0}]...", start.ToShortDateString());
var weight = fc.GetWeightAsync(start, DateRangePeriod.OneMonth).Result;
Colorizer.WriteLine("found [Green!{0}] entries.", weight.Weights.Count);

// Save the downloaded information to disk
System.Xml.Serialization.XmlSerializer src = new System.Xml.Serialization.XmlSerializer(typeof(List<Weight>));
using (StreamWriter sw = new StreamWriter("weight.txt"))
{
src.Serialize(sw, weight);
}
}
}
}
36 changes: 36 additions & 0 deletions SampleConsole/SampleConsole/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SampleConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SampleConsole")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("11886ef6-6527-4061-a859-3191f7e3b192")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
74 changes: 74 additions & 0 deletions SampleConsole/SampleConsole/SampleConsole.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{11886EF6-6527-4061-A859-3191F7E3B192}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SampleConsole</RootNamespace>
<AssemblyName>SampleConsole</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="OutputColorizer, Version=1.2.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Fitbit\packages\OutputColorizer.1.1.0\lib\net45\OutputColorizer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AuthorizationHelper.cs" />
<Compile Include="Options.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Fitbit.Portable\Fitbit.Portable.csproj">
<Project>{1358d3b4-0698-4003-97eb-b6d489e04138}</Project>
<Name>Fitbit.Portable</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
4 changes: 4 additions & 0 deletions SampleConsole/SampleConsole/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="OutputColorizer" version="1.1.0" targetFramework="net452" />
</packages>