Specifies the parameters for the HTTP request that will be executed against a given resource.
        private async Task Authenticate()
        {
            var client = new RestClient
            {
                BaseUrl = "https://datamarket.accesscontrol.windows.net",
                UserAgent = UserAgent,
            };
            var request = new RestRequest("v2/OAuth2-13", HttpMethod.Post)
            {
                ContentType = ContentTypes.FormUrlEncoded,
                ReturnRawString = true,
            };
            request.AddParameter("client_id", ClientId);
            request.AddParameter("client_secret", ClientSecret);
            request.AddParameter("scope", "http://music.xboxlive.com");
            request.AddParameter("grant_type", "client_credentials");

            var result = await client.ExecuteAsync<string>(request);

            TokenResponse = JsonConvert.DeserializeObject<TokenResult>(result);
            if (TokenResponse != null)
            {
                TokenResponse.TimeStamp = DateTime.Now;
            }
        }
Example #2
0
 /// <summary>
 /// Get the statistics for a project by date
 /// </summary>
 /// <param name="projectId">The id of the project (non-hashed)</param>
 /// <returns>The list of project stats ordered by date</returns>
 public async Task<List<ProjectStats>> GetByDate(int projectId)
 {
     var request = new RestRequest(this.ServiceKey + string.Format("/projects/{0}/by_date.json", projectId), HttpMethod.Get) { ContentType = ContentTypes.Json };
     var authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("api:{0}", ApiKey)));
     request.Headers.Add("Authorization", "Basic " + authInfo);
     return await ExecuteAsync<List<ProjectStats>>(request);
 }
Example #3
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public async Task<Account> Get()
 {
     var request = new RestRequest("account.json", HttpMethod.Get) { ContentType = ContentTypes.Json };
     var authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("api:{0}", ApiKey)));
     request.Headers.Add("Authorization", "Basic " + authInfo);
     return await ExecuteAsync<Account>(request);
 }
 /// <summary>
 /// Returns a list of meteo information
 /// </summary>
 /// <returns></returns>
 public async Task<Meteo[]> GetMeteoAsync()
 {
     var request = new RestRequest("meteo", HttpMethod.Get);
     
     var result = await _httpClient.ExecuteWithPolicyAsync<Meteo[]>(this, request);
     return result;
 }
        public async Task<Device[]> GetDevicesAsync(bool includeDeviceState = false, Enums.EndpointGetModes loadMode = EndpointGetModes.None, bool allowCache = true)
        {
            if (loadMode == EndpointGetModes.IncludeEndpointInfoOnly)
                throw new ArgumentException("IncludeEndpointInfoOnly is not supported because it doesn't contain information to correlate devices to endpoints. Please specify IncludeFullAttributes.");

            

            if (allowCache && _cachedDevicesList != null && _cachedLoadMode == loadMode)
                return _cachedDevicesList;

            var request = new RestRequest("devices", HttpMethod.Get);
            
            var devices = await _httpClient.ExecuteWithPolicyAsync<Device[]>(this, request);

            if (includeDeviceState)
            {
                // Do a seperate call to get all device statuses and correlate device state with devices
                // based on uuid
                var stateRequest = new RestRequest("devices/statuses", HttpMethod.Get);
                var deviceStatuses = await _httpClient.ExecuteWithPolicyAsync<Device[]>(this, stateRequest);

                foreach (var device in devices)
                {
                    var deviceState = deviceStatuses.FirstOrDefault(d => d.Uuid.Equals(device.Uuid));
                    if (deviceState != null)
                        device.State = deviceState.State;
                }
            }

            if (loadMode == EndpointGetModes.IncludeFullAttributes ||
                loadMode == EndpointGetModes.IncludeFullAttributesWithValues)
            {
                // Do seperate calls to get endpoint, endpoint attributes and maybe even attribute values
                // and correlate them to devices
                var endpoints = await GetEndpointsAsync(loadMode, allowCache);
                foreach (var device in devices)
                {
                    var deviceWithEndpoints =
                        endpoints.Where(
                            e =>
                                e.Attributes != null &&
                                e.Attributes.Any(a => a.Device != null && a.Device.Uuid.Equals(device.Uuid))).ToArray();
                    if (deviceWithEndpoints.Length > 0)
                    {
                        if (device.Endpoints == null)
                            device.Endpoints = new List<Endpoint>();
                        device.Endpoints.AddRange(deviceWithEndpoints);
                    }
                }
            }


            if (allowCache)
            {
                _cachedDevicesList = devices;
                _cachedLoadMode = loadMode;
            }
            return devices;
        }
       public async Task<SecurityResponse> InitializeSecuritySessionAsync()
        {
                        

            var request = new RestRequest("security/session/init/", HttpMethod.Get);
            
            return await _httpClient.ExecuteWithPolicyAsync<SecurityResponse>(this, request);           
        }
        public async Task<byte[]> GetResourceAsync(Uri uri)
        {
            var client = new RestClient();
            var request = new RestRequest(uri.AbsoluteUri, HttpMethod.Get, ContentTypes.ByteArray);

            var result = await client.ExecuteAsync<byte[]>(request);

            return result;
        }
        public async Task<SecurityResponse> LoginAlarmWithPinAsync(string secureSessionId, string salt, string nonce, string pinCode)
        {
            

            string token = Utils.GetToken(salt + pinCode, nonce);

            var request = new RestRequest("security/session/login/" + secureSessionId + "?token=" + token, HttpMethod.Get);
            
            return await _httpClient.ExecuteWithPolicyAsync<SecurityResponse>(this, request);
        }
        /// <summary>
        /// Returns a list of rooms
        /// </summary>
        /// <returns></returns>
        public async Task<Room[]> GetRoomsAsync()
        {
            

            // Note that this API call requires the forward slash at the end. This is different than
            // other API calls!
            var request = new RestRequest("rooms/", HttpMethod.Get);
            
            return  await _httpClient.ExecuteWithPolicyAsync<Room[]>(this, request);            
        }       
Example #10
0
        private RestRequest GetPopulatedRequest(string resourceUrl)
        {
            if (string.IsNullOrWhiteSpace(TokenResponse.AccessToken))
                throw new Exception();

            var request = new RestRequest(resourceUrl) { ContentType = ContentTypes.Json };

            request.AddUrlSegment("namespace", "music");

            return request;
        }
Example #11
0
        /// <summary>
        /// clients as an asynchronous operation.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <returns>Task&lt;List&lt;Client&gt;&gt;.</returns>
        /// <exception cref="HttpRequestException">Throws an exception if the <see cref="P:System.Net.Http.HttpResponseMessage.IsSuccessStatusCode" /> property for the HTTP response is false.</exception>
        public static async Task<List<Client>> ClientsAsync(this WowClient self)
        {
            var request = new RestRequest
            {
                Resource = "clients"
            };

            var result = await self.Client.ExecuteAsync<List<Client>>(request);

            return result;
        }
Example #12
0
        /// <summary>
        /// Clientses the specified self.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <returns>List&lt;Client&gt;.</returns>
        public static List<Client> Clients(this WowClient self)
        {
            var request = new RestRequest
            {
                Resource = "clients"
            };

            var result = AsyncHelpers.RunSync(()=>self.Client.ExecuteAsync<List<Client>>(request));

            return result;
        }
Example #13
0
        /// <summary>
        /// Gets the lead types.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <returns>List&lt;System.String&gt;.</returns>
        public static List<string> GetLeadTypes(this WowClient self)
        {

            var request = new RestRequest
            {
                Resource = "settings/leadtypes"
            };

            var result = AsyncHelpers.RunSync(() => self.Client.ExecuteAsync<List<string>>(request));

            return result;
        }
Example #14
0
        // this WowClient self, 
        /// <summary>
        /// get lead types as an asynchronous operation.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <returns>Task&lt;List&lt;System.String&gt;&gt;.</returns>
        /// <exception cref="HttpRequestException">
        /// Throws an exception if the <see cref="P:System.Net.Http.HttpResponseMessage.IsSuccessStatusCode" /> property for the HTTP response is false.
        /// </exception>
        public async static Task<List<string>> GetLeadTypesAsync(this WowClient self)
        {

            var request = new RestRequest
                {
                    Resource = "settings/leadtypes"
                };

            var result = await self.Client.ExecuteAsync<List<string>>(request);

            return result;
        }
Example #15
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public async Task<ThemesList> GetThemes()
 {
     var request = new RestRequest("getThemes", HttpMethod.Get)
     {
         ContentType = ContentTypes.Xml,
         IgnoreXmlAttributes = true
     };
     request.AddQueryString("apiKey", ApiId);
     //RWM: Using this version handles null results and gives you access to possible exceptions.
     var results = await SendAsync<ThemesList>(request);
     return results.Content;
 }
        /// <summary>
        /// Returns a list of meteo conditions
        /// </summary>
        /// <param name="uuid">UUID of the meteo condition</param>
        /// <param name="allowCache"></param>
        /// <returns></returns>
        public async Task<MeteoConditions> GetMeteoConditionsAsync(Guid uuid, bool allowCache = true)
        {
            if (allowCache && _cachedMeteoConditions != null)
                return _cachedMeteoConditions;

            var request = new RestRequest("meteo/" + uuid + "/conditions", HttpMethod.Get);
            
            var result = await _httpClient.ExecuteWithPolicyAsync<MeteoConditions>(this, request);

            if (allowCache || _cachedMeteoConditions != null)
                _cachedMeteoConditions = result;
            return result;
        }
Example #17
0
        /// <summary>
        /// Gets the client details.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <returns>ClientDetails.</returns>
        public static ClientDetails GetClientDetails(this WowClient self, string clientId)
        {
            var request = new RestRequest
            {
                Resource = "clients/{clientId}"
            };

            request.AddUrlSegment("clientId", clientId);

            var result = AsyncHelpers.RunSync(() => self.Client.ExecuteAsync<ClientDetails>(request));

            return result;

        }
Example #18
0
        /// <summary>
        /// get client details as an asynchronous operation.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <returns>Task&lt;ClientDetails&gt;.</returns>
        /// <exception cref="HttpRequestException">Throws an exception if the <see cref="P:System.Net.Http.HttpResponseMessage.IsSuccessStatusCode" /> property for the HTTP response is false.</exception>
        public async static Task<ClientDetails> GetClientDetailsAsync(this WowClient self, string clientId)
        {
            var request = new RestRequest
                {
                    Resource = "clients/{clientId}"
                };

            request.AddUrlSegment("clientId", clientId);

            var result = await self.Client.ExecuteAsync<ClientDetails>(request);

            return result;

        }
Example #19
0
        /// <summary>
        /// Companies the details.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="leadId">The lead identifier.</param>
        /// <returns>Task&lt;CompanyDetails&gt;.</returns>
        /// <exception cref="HttpRequestException">
        /// Throws an exception if the <see cref="P:System.Net.Http.HttpResponseMessage.IsSuccessStatusCode" /> property for the HTTP response is false.
        /// </exception>
        public async static Task<CompanyDetails> CompanyDetailsAsync(this WowClient self, string clientId, Guid leadId)
        {
            var request = new RestRequest
                {
                    Resource = "client/{clientid}/company/{leadid}"
                };

            request.AddUrlSegment("leadid", leadId.ToString());
            request.AddUrlSegment("clientid", clientId);

            var result = await self.Client.ExecuteAsync<CompanyDetails>(request);

            return result;
        }
        /// <summary>
        /// Gets the tracked links.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="take">The take.</param>
        /// <returns>RecieveTrackedLinks.</returns>
        public static RecieveTrackedLinks GetTrackedLinks(this WowClient self, string clientId, int take)
        {
            var request = new RestRequest
            {
                Resource = "client/{clientId}/trackedlinks/{take}"
            };

            request.AddUrlSegment("clientId", clientId);
            request.AddUrlSegment("take", take.ToString(CultureInfo.InvariantCulture));

            var result = AsyncHelpers.RunSync(() => self.Client.ExecuteAsync<RecieveTrackedLinks>(request));

            return result;
        }
Example #21
0
        /// <summary>
        /// Companies the details.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="leadId">The lead identifier.</param>
        /// <returns>CompanyDetails.</returns>
        public static CompanyDetails CompanyDetails(this WowClient self, string clientId, Guid leadId)
        {
            var request = new RestRequest
            {
                Resource = "client/{clientid}/company/{leadid}"
            };

            request.AddUrlSegment("leadid", leadId.ToString());
            request.AddUrlSegment("clientid", clientId);

            var result = AsyncHelpers.RunSync(() => self.Client.ExecuteAsync<CompanyDetails>(request));

            return result;
        }
        public async Task<Endpoint[]> GetEndpointsAsync(EndpointGetModes loadMode = EndpointGetModes.IncludeEndpointInfoOnly, bool allowCache = true)
        {
            if (loadMode == EndpointGetModes.None)
                return null;

            if (allowCache && _cachedEndpointsList != null)
                return _cachedEndpointsList;

            var request = new RestRequest("endpoints", HttpMethod.Get);
            
            var endpoints = await _httpClient.ExecuteWithPolicyAsync<Endpoint[]>(this, request);

            if (loadMode == EndpointGetModes.IncludeFullAttributes ||
                loadMode == EndpointGetModes.IncludeFullAttributesWithValues)
            {
                var attributes = await GetAttributesFullAsync(allowCache);
                var attributesWithEndpoint = attributes.Where(a=>a.Endpoint != null && a.Endpoint.Uuid != Guid.Empty);
                Attribute[] attributeValues = null;

                if (loadMode == EndpointGetModes.IncludeFullAttributesWithValues)
                {
                    attributeValues = await GetAttributeValuesAsync();
                }

                foreach (var attribute in attributesWithEndpoint)
                {
                    var endpoint = endpoints.FirstOrDefault(e => e.Uuid.Equals(attribute.Endpoint.Uuid));
                    if (endpoint != null)
                    {
                        if (endpoint.Attributes == null)
                            endpoint.Attributes = new List<Attribute>();

                        if (attributeValues != null)
                        {
                            var attributeWithValue =
                                attributeValues.FirstOrDefault(a => a.Uuid.Equals(attribute.Uuid) && a.Value != null);
                            if (attributeWithValue != null)
                                attribute.Value = attributeWithValue.Value;
                        }

                        endpoint.Attributes.Add(attribute);
                    }
                }
            }

            if (allowCache)
                _cachedEndpointsList = endpoints;
            return endpoints;
        }
        /// <summary>
        /// Marks the tracked links processed.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="processId">The process identifier.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        /// <exception cref="HttpRequestException">
        /// Throws an exception if the <see cref="P:System.Net.Http.HttpResponseMessage.IsSuccessStatusCode" /> property for the HTTP response is false.
        /// </exception>
        public async static Task<bool> MarkTrackedLinksProcessedAsync(this WowClient self, string clientId, Guid processId)
        {
            var request = new RestRequest
                {
                    Resource = "client/{clientId}/trackedlinks/markprocessed/{processId}"
                };

            request.AddHeader("api-version", "1");
            request.AddUrlSegment("clientId", clientId);
            request.AddUrlSegment("processId", processId.ToString());

            var result = await self.Client.ExecuteAsync<BasicResult>(request);

            return result.Result;
        }
        public async Task<AlarmZone[]> GetAlarmZonesAsync(Guid paritionUuid, bool allowCache = true)
        {
            

            if (allowCache && _cachedAlarmZonesList != null)
                return _cachedAlarmZonesList;

            var request = new RestRequest("alarm/partitions/" + paritionUuid + "/zones", HttpMethod.Get);
            
            var result = await _httpClient.ExecuteWithPolicyAsync<AlarmZone[]>(this, request);

            if (allowCache || _cachedAlarmZonesList != null)
                _cachedAlarmZonesList = result;
            return result;
        }
        public async Task<Scene[]> GetScenesAsync(bool allowCache = true)
        {
            

            if (allowCache && _cachedScenesList != null)
                return _cachedScenesList;

            var request = new RestRequest("scenes", HttpMethod.Get);
            
            var result = await _httpClient.ExecuteWithPolicyAsync<Scene[]>(this, request);

            if (allowCache || _cachedScenesList != null)
                _cachedScenesList = result;
            return result;
        }
Example #26
0
 private RestRequest CreateRequest(string api, HttpMethod method, object msgBody = null)
 {
     // replace operator id
     var apiPath = api.Replace(OPERATOR_ID_PLACEHOLDER, operatorId);
     var req = new RestRequest(GetRequestUri(apiPath), method);
     req.ContentType = ContentTypes.Json;
     if (msgBody != null)
     {
         req.AddParameter(msgBody);
     }
     else
     {
         if (method == HttpMethod.Post)
         {
             req.AddParameter(new object[]{ });
         }
     }
     return req;
 }
Example #27
0
        /// <summary>
        /// Gets the latest leads.
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="lastMinutes">The last minutes.</param>
        /// <param name="numberToGet">The number to get.</param>
        /// <returns>List&lt;Lead&gt;.</returns>
        /// <exception cref="System.ArgumentException">You can only get the leads for the last 60 minutes;lastMinutes</exception>
        public static List<Lead> GetLatestLeads(this WowClient self, string clientId, int lastMinutes, int numberToGet = 10)
        {
            if (lastMinutes > 60)
            {
                throw new ArgumentException("You can only get the leads for the last 60 minutes", "lastMinutes");
            }

            var request = new RestRequest
            {
                Resource = "latestleads/{clientId}/{minutes}/{numberToGet}"
            };

            request.AddUrlSegment("clientId", clientId);
            request.AddUrlSegment("minutes", lastMinutes.ToString());
            request.AddUrlSegment("numberToGet", numberToGet.ToString());

            var result = AsyncHelpers.RunSync(() => self.Client.ExecuteAsync<List<Lead>>(request));

            return result;

        }
Example #28
0
 public async Task<List<Station>> GetLocations(KeyValuePair<string, string> valuePair)
 {
     var ro = new StationRootObject();
     try
     {
         var request = new RestRequest
         {
             Resource = Stations + ConvertValuePairToQueryString(new[] {valuePair})
         };
         ro = await _restClient.ExecuteAsync<StationRootObject>(request);
     }
     catch (HttpRequestException)
     {
         Message.ShowToast(AppResources.APIClientErrorDown);
     }
     catch (Exception e)
     {
         Message.SendErrorEmail(e.Message + e.InnerException, "Client - GetLocations");
     }
     return ro.Station;
 }
        public async Task<MeteoConditions> GetMeteoConditionsWithValuesAsync(Guid uuid, bool allowCache = true)
        {
            
            var meteoConditions = await GetMeteoConditionsAsync(uuid, allowCache);
            var request = new RestRequest("meteo/attributes/values?update=false", HttpMethod.Get);

            
            var attributeValues = await _httpClient.ExecuteWithPolicyAsync<Model.Attribute[]>(this, request);

            foreach (Model.Attribute attribute in meteoConditions.Attributes)
            {
                var attributeValue = attributeValues.FirstOrDefault(a => a.Uuid == attribute.Uuid);
                if (attributeValue != null)
                {
                    // Note that not all conditions received are in the attribute value list
                    attribute.Value = attributeValue.Value;
                }
            }


            return meteoConditions;
        }
        public async Task<String> ExecuteQueryAsync(IHsaQuery query)
        {
            var client = new RestClient();
            var request = new RestRequest(query.Uri.AbsoluteUri, HttpMethod.Get, ContentTypes.Json);
            request.Headers.Add("X-Mashape-Key", query.ApiInfo.ApiKey);

            var result = await client.ExecuteAsync<String>(request);

            return result;
        }