Fitbit get distance data in miles not kilometers - c#

I have a sample project that gets data from Fitbit but the information comes in metric system not imperial system. Here is the code that pulls a list of Dates and Strings pair using TimeSeriesDataList class, but in kilometers not miles. How can I modify this code to get the data in miles instead of kilometers? Any help is greatly appreciated.
public class TimeSeriesDataList
{
public List<Data> DataList { get; set; }
public class Data
{
public DateTime DateTime { get; set; }
public string Value { get; set; }
}
}
public class FitbitClient : IFitbitClient
{
/// <summary>
/// Get TimeSeries data for another user accessible with this user's credentials
/// </summary>
/// <param name="timeSeriesResourceType"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="userId"></param>
/// <returns></returns>
private TimeSeriesDataList GetTimeSeries(TimeSeriesResourceType timeSeriesResourceType, DateTime baseDate, string endDateOrPeriod, string userId)
{
string userSignifier = "-"; //used for current user
if (!string.IsNullOrWhiteSpace(userId))
userSignifier = userId;
// Here is where I believe I need to make a change, somehow, so that
// data that comes in when this is string is requested, comes in metric units
string requestUrl = string.Format("/1/user/{0}{1}/date/{2}/{3}.xml", userSignifier, StringEnum.GetStringValue(timeSeriesResourceType), baseDate.ToString("yyyy-MM-dd"), endDateOrPeriod);
RestRequest request = new RestRequest(requestUrl);
request.OnBeforeDeserialization = resp => {
XDocument doc = XDocument.Parse(resp.Content);
//IEnumerable<XElement> links = doc.Descendants("result");
var rootElement = doc.Descendants("result").FirstOrDefault().Descendants().FirstOrDefault();
if (rootElement != null && !string.IsNullOrWhiteSpace(rootElement.Name.LocalName))
request.RootElement = rootElement.Name.LocalName;
};
var response = restClient.Execute<TimeSeriesDataList>(request);
HandleResponse(response);
return response.Data;
}
}
EDIT I am looking to get the data already converted by adding something along the lines of "Accept-Language" to the header, but I do not know how to utilize that concept. Using conversion crossed my mind but at this time I would like to see if there is an easier way by adding a simple header rather than creating a conversion class for every scenario, class holding the data, for each distinct region, etc.

I did a quick search and am assuming that RestRequest is the class from the RestSharp library. If so, according to their web site (http://restsharp.org) you would do something like:
request.AddHeader("Accept-Language", "...");
Not sure what the correct value should be, you'll need to figure that out from FitBit's API documentation.

Whatever value this code provides, you can simply divide it by 1.60934 to get the same distance in miles. Hope that helps you solve it.

double kilometers2 = 321.9;
double miles2 = ConvertDistance.ConvertKilometersToMiles

Related

Provide a complex object for a SwaggerExample?

We're using Swagger.Net package to help with our documentation.
I'm trying to add request data to be auto-generated into my documentation and was looking at this answer that provides this code block:
[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{...}
I'm not sure how I can translate that int into a more complex object. For example:
[Route("SaveCustomThing"), HttpPost]
[SwaggerExample("thing", ???)]
public HttpResponseMessage SaveCustomThing([FromBody] Thing thing)
{...}
How do I pass a pre-configured Thing object in the SwaggerExample attribute?
Looking at the code that attribute (SwaggerExample) takes two parameters:
public SwaggerExampleAttribute(string parameterName, object example)
{
this.ParameterName = parameterName;
this.Example = example;
}
https://github.com/heldersepu/Swagger-Net/blob/6afdb0c1ba611273f27e8a904ec2bb06a630b1b4/Swagger.Net/Swagger/Annotations/SwaggerExampleAttribute.cs#L16
We can see the first one is a string but second is an object...
In theory you should be able to pass anything there.
Another alternative I would recommend, if you have complex models like your Thing you should consider adding the examples on the model, we can do a lot more there... as you can see below we can add description, example values and with some other decorators we can limit the range of values code looks like:
/// <summary>
/// ## Geographic coordinates
/// ___
/// A **geographic coordinate system** is a coordinate system used in geography that enables every location on Earth to be specified by a set of numbers
/// </summary>
public class Location
{
/// <summary>**Latitude**: a geographic coordinate that specifies the north–south position of a point on the Earth's surface.</summary>
/// <example>25.85</example>
[Range(-90, 90)]
public float Lat { get; set; }
/// <summary>**Longitude**: a geographic coordinate that specifies the east-west position of a point on the Earth's surface.</summary>
/// <example>-80.27</example>
[Range(-180, 180)]
public float Lon { get; set; }
}
http://swagger-net-test.azurewebsites.net/swagger/ui/index#/Location/Location_Get2

Swagger UI Response Example Asp.Net Core Web Api

I'm using Swagger.AspNetCore to document my api. So far i was happy to use xml comments to generate response model examples until i reach the point when i've got to document embeded object. So i have simple model:
public class SummaryResult
{
/// <summary>Total Cost.</summary>
/// <value>Total Cost.</value>
/// <example>6433.2</example>
public double TotalCost { get; set; }
/// <summary>Owner.</summary>
public Owner Owner { get; set; }
}
public class Owner
{
/// <summary>Owner Name.</summary>
/// <value>Owner Name.</value>
/// <example>Michael</example>
public string Name { get; set; }
}
And Swagger UI document it only for TotalCost, Owner property just skipped whatever i do. Does anyone have a clue why this can happen? And how to fix it.
I know how to deal with List - just put on top xml comment like <list></list> but it's not my case.
Thank you
I just tested this and it shows fine on my end:
http://swagger-net-test.azurewebsites.net/swagger/ui/index#/ActionFilter/ActionFilter_Get
Here is how that looks like on the model tab:
As you can see in the image it does show the summary and the example value.
Here is the code:
https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Controllers/ActionFilterController.cs#L29
Educated guess there could be something else removing those elements.

PetaPoco Query View Always Returns NULLS

I have the below view in SQL Server represented using PetaPoco in my C# application:
/// <summary> Rep Level Keys. </summary>
[TableName("vXPATRepLevelKeys")]
[ExplicitColumns]
public partial class vXPATRepLevelKeys : dbo.Record<vXPATRepLevelKeys>
{
/// <summary> Gets or sets the RepLevelKey. </summary>
public string RepLevelKey { get; set; }
}
However, when I attempt to select from the view using:
var result = _database.Fetch<xPAT.vXPATRepLevelKeys>("SELECT * FROM vXPATRepLevelKeys").OrderBy(x => x.RepLevelKey);
var asStrings = result.Select(x => x.RepLevelKey).ToList();
I just get a list of NULL values. asStrings has 33 items in the list, all being NULL. However, when I run the above view myself, I get 33 non-null results.
I'm new to PetaPoco (tbh, I'm not even sure if it is a PetaPoco related issue) and have inherited this application, which I'm attempting to add this new view to so any help is greatly appreciated.
If you use the [ExplicitColumns] attribute, you must use the [Column] attribute on each property
[Column]
public string RepLevelKey { get; set; }

RestSharp Serialize/Deserialize Naming Conversion

I am attempting to wrap the Plivo API (yes I'm aware it's been done) using RestSharp.
However, I cannot find a method to translate the API Naming conventions to my own, for example:
A "Call` (https://www.plivo.com/docs/api/call/#make-an-outbound-call) requires a minimum of:
to, from, and answer_url parameters be provided.
These parameters are also case-sensitive.
I would like to be able to provide a CallRequest Class, wrapping the data required in my preferred naming conventions, and then somehow translate these prior to serialization by RestSharp.
Example:
public class CallRequest
{
/// <summary>
/// The phone number to be used as the caller id (with the country code).For e.g, a USA caller id number could be, 15677654321, with '1' for the country code.
/// </summary>
public string From { get; set; }
/// <summary>
/// The regular number(s) or sip endpoint(s) to call. Regular number must be prefixed with country code but without the + sign). For e.g, to dial a number in the USA, the number could be, 15677654321, with '1' for the country code. Multiple numbers can be sent by using a delimiter. For e.g. 15677654321<12077657621<12047657621. Sip endpoints must be prefixed with sip: E.g., sip:john1234#phone.plivo.com. To make bulk calls, the delimiter < is used. For eg. 15677654321<15673464321<sip:john1234#phone.plivo.com Yes, you can mix regular numbers and sip endpoints.
/// </summary>
public string To { get; set; }
/// <summary>
/// The URL invoked by Plivo when the outbound call is answered.
/// </summary>
public string AnswerUrl { get; set; }
}
This data would then be translated to Plivo's convention in the following functions:
private T Execute<T>(IRestRequest request) where T : new()
{
var client = new RestClient
{
BaseUrl = new Uri(BaseUrl),
Authenticator = new HttpBasicAuthenticator(_accountId, _authToken),
UserAgent = "PlivoSharp"
};
request.AddHeader("Content-Type", "application/json");
request.AddParameter("auth_id", _accountId, ParameterType.UrlSegment);
request.RequestFormat = DataFormat.Json;
client.AddHandler("application/json", new JsonDeserializer());
var response = client.Execute<T>(request);
if (response.ErrorException == null) return response.Data;
const string message = "Error retrieving response. Check inner details for more info.";
var plivoException = new ApplicationException(message, response.ErrorException);
throw plivoException;
}
public CallResponse MakeCall(CallRequest callRequest)
{
var request = new RestRequest
{
RequestFormat = DataFormat.Json,
Resource = "Account/{auth_id}/Call/",
Method = Method.POST
};
//SOMEHOW TRANSLATE THE PROPERTIES INTO THE DATA BELOW
request.AddBody(new
{
to = "17#####",
from = "18#####",
answer_url = "http://m------.xml"
});
return Execute<CallResponse>(request);
}
Unfortunately it looks as though JSON property renaming is not implemented out of the box in RestSharp. You have a couple of options:
Download Restsharp from https://github.com/restsharp/RestSharp and rebuild it yourself enabling the compiler option SIMPLE_JSON_DATACONTRACT. Then you will be able to rename properties using data contract attributes. For more, see here: RestSharp JsonDeserializer with special characters in identifiers
I just rebuilt the most recent version of RestSharp (version 105.1.0)
with this option enabled. Using the following version of your class:
[DataContract]
public class CallRequest
{
[DataMember(Name = "from")]
public string From { get; set; }
[DataMember(Name = "to")]
public string To { get; set; }
[DataMember(Name = "answer_url")]
public string AnswerUrl { get; set; }
}
I was able to generate the following JSON:
var request = new CallRequest { AnswerUrl = "AnswerUrl", From = "from", To = "to" };
var json = SimpleJson.SerializeObject(request);
Debug.WriteLine(json);
// Prints {"from":"from","to":"to","answer_url":"AnswerUrl"}
I'm not sure how thoroughly tested this option is, however, since it's compiled out by default.
Manually serialize and deserialize with a different serializer such as Json.NET that supports property renaming. To do this, see RestSharp - using the Json.net serializer (archived here.)

C# save/retrieve an array of structures from settings file

I have a simple question (I think) that I'm not making much progress finding an answer to with Google. I have a structure as follows:
/// <summary>
/// A class to represent the sync settings for a single camera.
/// </summary>
public class CameraSyncSettings
{
public string ID { get; set; }
public string SyncPath { get; set; }
public bool OverwriteExisting { get; set; }
};
And then an array of these in the program, one for each camera:
List<CameraSyncSettings> MyCameraSettings = new List<CameraSyncSettings>();
Now, what I want to do is have a property in my settings such that I can read/write this array into it to persist the information between sessions.
How can I do this and what is the best/most efficient way?
You can achieve it by using Properties.Settings of type ListDictionary
Example:
Properties.Settings.Default.Example.Add("Setting1", new CameraSyncSettings());
Properties.Settings.Default.Example.Add("Setting2", new CameraSyncSettings());
Properties.Settings.Default.Example.Add("Setting3", new CameraSyncSettings());
Properties.Settings.Default.Save();
see link for more information : http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
NB: You can set the Scope of Properties.Settings.Default.Example to Application or User
As we've cleared in the comments you want to use app.config: this project should pretty much cover all your needs.

Categories

Resources