/// <summary> /// Subscribes a person to multiple <see cref="ConvertKitCourse" />s. /// </summary> /// <param name="email">The subscriber's email address.</param> /// <param name="firstName">The subscriber's first name.</param> /// <param name="courseIds">A list of Course ids to subscribe them to.</param> /// <returns>The subscriber.</returns> public async Task <ConvertKitSubscriber> SubscribeToCourses(string email, string firstName, IEnumerable <long> courseIds) { long?defaultCourse = courseIds.FirstOrDefault(); if (defaultCourse == null) { throw new NullReferenceException("You must specify at least one course id to subscribe to."); } var req = RequestEngine.CreateRequest($"Courses/{defaultCourse}/subscribe", Method.POST, "subscription"); if (courseIds.Count() > 1) { req.AddQueryParameter("courses", string.Join(",", courseIds.Where(f => f != defaultCourse))); } return(await RequestEngine.ExecuteRequestAsync <ConvertKitSubscriber>(_RestClient, req)); }
/// <summary> /// A method that will throw an exception which looks like { errors: { "order" : [ "some error message" ] } } /// </summary> /// <returns></returns> public async Task ThrowArrayException() { var request = RequestEngine.CreateRequest("orders.json", Method.POST); //Creating an order with tax lines on both line items and the order will return an error var order = new ShopifyOrder() { CreatedAt = DateTime.UtcNow, LineItems = new List <ShopifyLineItem>() { new ShopifyLineItem() { Title = "Click Keyboard", Price = 99.99, Grams = 600, Quantity = 1, TaxLines = new List <ShopifyTaxLine>() { new ShopifyTaxLine() { Price = 1.0, Rate = 0.01, Title = "Keyboard tax" } } } }, TaxLines = new List <ShopifyTaxLine>() { new ShopifyTaxLine() { Price = 6.0, Rate = 0.06, Title = "State tax" } } }; request.AddJsonBody(new { order }); //Make request await RequestEngine.ExecuteRequestAsync <ShopifyOrder>(_RestClient, request); }
internal async Task <List <Channel> > GetChannelsInternalAsync(int sensorId, Func <string, bool> nameFilter = null, Func <int, bool> idFilter = null) { if (nameFilter == null) { nameFilter = n => true; } if (idFilter == null) { idFilter = i => true; } var response = await RequestEngine.ExecuteRequestAsync(new ChannelParameters(sensorId)).ConfigureAwait(false); response.Descendants("item").Where(item => item.Element("objid").Value == "-4").Remove(); var items = response.Descendants("item").ToList(); items.Where(e => !nameFilter(e.Element("name").Value?.ToString()) || !idFilter(Convert.ToInt32(e.Element("objid").Value.ToString())) ).Remove(); items = response.Descendants("item").ToList(); await Task.WhenAll(items.Select(async item => { var id = Convert.ToInt32(item.Element("objid").Value); var properties = await GetChannelPropertiesAsync(sensorId, id).ConfigureAwait(false); item.Add(properties.Nodes()); item.Add(new XElement("injected_sensorId", sensorId)); })).ConfigureAwait(false); if (items.Count > 0) { return(XmlDeserializer <Channel> .DeserializeList(response).Items); } return(new List <Channel>()); }
//###################################### // GetChannelsInternal //###################################### internal List <Channel> GetChannelsInternal(int sensorId, Func <string, bool> nameFilter = null, Func <int, bool> idFilter = null) { if (nameFilter == null) { nameFilter = n => true; } if (idFilter == null) { idFilter = i => true; } var response = RequestEngine.ExecuteRequest(new ChannelParameters(sensorId)); response.Descendants("item").Where(item => item.Element("objid").Value == "-4").Remove(); var items = response.Descendants("item").ToList(); items.Where(e => !nameFilter(e.Element("name").Value?.ToString()) || !idFilter(Convert.ToInt32(e.Element("objid").Value.ToString())) ).Remove(); items = response.Descendants("item").ToList(); foreach (var item in items) { var id = Convert.ToInt32(item.Element("objid").Value); var properties = GetChannelProperties(sensorId, id); item.Add(properties.Nodes()); item.Add(new XElement("injected_sensorId", sensorId)); } if (items.Count > 0) { return(XmlDeserializer <Channel> .DeserializeList(response).Items); } return(new List <Channel>()); }
private async Task RestartProbeInternalAsync(int[] probeIds, bool waitForRestart, Func <ProbeRestartProgress[], bool> progressCallback, CancellationToken token) { var restartTime = waitForRestart ? (DateTime?)(await GetStatusAsync(token).ConfigureAwait(false)).DateTime : null; if (probeIds != null && probeIds.Length > 1) { var tasks = probeIds.Select(probeId => RequestEngine.ExecuteRequestAsync(new RestartProbeParameters(probeId), token: token)); await Task.WhenAll(tasks).ConfigureAwait(false); } else { RequestEngine.ExecuteRequest(new RestartProbeParameters(probeIds?.Cast <int?>().FirstOrDefault()), token: token); } if (waitForRestart) { var probe = probeIds == null || probeIds.Length == 0 ? await GetProbesAsync(token).ConfigureAwait(false) : await GetProbesAsync(Property.Id, probeIds, token).ConfigureAwait(false); await WaitForProbeRestartAsync(restartTime.Value, probe, progressCallback, token).ConfigureAwait(false); } }
private async Task <string> PostOrPutAsync(HttpMethod method, string apiPath, object data, string rootElement = null) { JsonContent content = null; if (string.IsNullOrEmpty(rootElement)) { content = new JsonContent(data); } else { var body = new Dictionary <string, object> { { rootElement, data } }; content = new JsonContent(body); } using (var req = RequestEngine.CreateRequest(_AuthState, apiPath, method, content, rootElement)) { return(await RequestEngine.ExecuteRequestToStringAsync(req, ExecutionPolicy)); } }
private void RestartProbeInternal(int[] probeIds, bool waitForRestart, Func <ProbeRestartProgress[], bool> progressCallback, CancellationToken token) { var restartTime = waitForRestart ? (DateTime?)GetStatus().DateTime : null; if (probeIds != null && probeIds.Length > 1) { foreach (var probeId in probeIds) { RequestEngine.ExecuteRequest(new RestartProbeParameters(probeId), token: token); } } else { RequestEngine.ExecuteRequest(new RestartProbeParameters(probeIds?.Cast <int?>().FirstOrDefault()), token: token); } if (waitForRestart) { var probe = probeIds == null || probeIds.Length == 0 ? GetProbes(new ProbeParameters(), token) : GetProbes(Property.Id, probeIds, token); WaitForProbeRestart(restartTime.Value, probe, progressCallback, token); } }
//###################################### // GetNotificationActionsInternal //###################################### internal List <NotificationAction> GetNotificationActionsInternal(NotificationActionParameters parameters) { var response = RequestEngine.ExecuteRequest(parameters); var items = response.Descendants("item").ToList(); foreach (var item in items) { var id = Convert.ToInt32(item.Element("objid").Value); var properties = GetNotificationActionProperties(id); item.Add(properties.Nodes()); } var actions = XmlDeserializer <NotificationAction> .DeserializeList(response).Items; var actionsWithSchedules = ResponseParser.GroupActionSchedules(actions).ToList(); UpdateActionSchedules(actionsWithSchedules); return(actions); }
internal async Task <List <NotificationAction> > GetNotificationActionsInternalAsync(NotificationActionParameters parameters) { var response = await RequestEngine.ExecuteRequestAsync(parameters).ConfigureAwait(false); var items = response.Descendants("item").ToList(); await Task.WhenAll(items.Select(async item => { var id = Convert.ToInt32(item.Element("objid").Value); var properties = await GetNotificationActionPropertiesAsync(id).ConfigureAwait(false); item.Add(properties.Nodes()); })).ConfigureAwait(false); var actions = XmlDeserializer <NotificationAction> .DeserializeList(response).Items; var actionsWithSchedules = ResponseParser.GroupActionSchedules(actions).ToList(); await UpdateActionSchedulesAsync(actionsWithSchedules).ConfigureAwait(false); return(actions); }
/// <summary> /// A convenience function that tries to ensure that a given URL is a valid Bizweb domain. It does this by making a HEAD request to the given domain, and returns true if the response contains an X-StoreId header. /// /// **Warning**: a domain could fake the response header, which would cause this method to return true. /// /// **Warning**: this method of validation is not officially supported by Bizweb and could break at any time. /// </summary> /// <param name="url">The URL of the shop to check.</param> /// <returns>A boolean indicating whether the URL is valid.</returns> public static async Task <bool> IsValidShopDomainAsync(string url) { var uri = RequestEngine.BuildUri(url, false); using (var msg = new HttpRequestMessage(HttpMethod.Head, uri)) { var version = (typeof(AuthorizationService)).GetTypeInfo().Assembly.GetName().Version; msg.Headers.Add("User-Agent", $"BizwebSharp v{version} (https://github.com/vinhch/BizwebSharp)"); try { using (var response = await HttpUtils.SendHttpRequestNoRedirectAsync(msg)) { return(response.Headers .Any(h => h.Key.Equals("X-StoreId", StringComparison.OrdinalIgnoreCase))); } } catch (HttpRequestException) { return(false); } } }
private static BizwebRequestMessage CreateRequestMessage(BizwebAuthorizationState authState, string path, HttpMethod method, string rootElement = null, object payload = null) { JsonContent content = null; if (payload == null) { return(RequestEngine.CreateRequest(authState, path, method, rootElement: rootElement)); } if (method != HttpMethod.Get && method != HttpMethod.Delete) { content = new JsonContent(payload); } else if (payload is Parameterizable) { path = RequestEngine.CreateUriPathAndQuery(path, ((Parameterizable)payload).ToParameters()); } else { //foreach (var propertyInfo in payload.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) //{ // req.AddParameter(propertyInfo.Name, propertyInfo.GetValue(payload)); //} var token = JToken.FromObject(payload); var queryParams = token.Select(s => { var i = (JProperty)s; return(new KeyValuePair <string, object>(i.Name, i.Value)); }); path = RequestEngine.CreateUriPathAndQuery(path, queryParams); } return(RequestEngine.CreateRequest(authState, path, method, content, rootElement)); }
public async Task TestRequestEngineAsync() { var engine = new RequestEngine(2); var batch0 = new SequentialRequestBatch(); var result0 = batch0.Enqueue(new TestRequest("0", this)); var result1 = batch0.Enqueue(new TestRequest("1", this)); var result2 = batch0.Enqueue(new TestRequest("2", this)); var result3 = batch0.Enqueue(new TestRequest("3", this)); var batch1 = new SequentialRequestBatch(); var result4 = batch1.Enqueue(new TestRequest("4", this)); var result5 = batch1.Enqueue(new TestRequest("5", this)); var result6 = batch1.Enqueue(new TestRequest("6", this)); var result7 = batch1.Enqueue(new TestRequest("7", this)); var batch2 = new SequentialRequestBatch(); var result8 = batch2.Enqueue(new TestRequest("8", this)); var result9 = batch2.Enqueue(new TestRequest("9", this)); var resulta = batch2.Enqueue(new TestRequest("a", this)); var resultb = batch2.Enqueue(new TestRequest("b", this)); var batch3 = new SequentialRequestBatch(); var resultc = batch3.Enqueue(new TestRequest("c", this)); var resultd = batch3.Enqueue(new TestRequest("d", this)); var resulte = batch3.Enqueue(new TestRequest("e", this)); var resultf = batch3.Enqueue(new TestRequest("f", this)); var br1 = engine.SendRequest(batch0); var br2 = engine.SendRequest(batch1); var br3 = engine.SendRequest(batch2); var br4 = engine.SendRequest(batch3); await br1; await br2; await br3; await br4; foreach (var line in ResultList) { Debug.WriteLine(line); } }
/// <summary> /// Builds an authorization URL for OAuth integration. /// </summary> /// <param name="scopes">A permission strings, separated by comma, e.g. 'read_orders,write_script_tags'. /// These are the permissions that your app needs to run.</param> /// <param name="myApiUrl">The shop's *.bizwebvietnam.net URL.</param> /// <param name="apiKey">Your app's public API key.</param> /// <param name="redirectUri">URL to redirect the user to after integration.</param> /// <param name="state"> /// An optional, random string value provided by your application which is unique for each authorization request. /// During the OAuth callback phase, your application should check that this value matches the one you provided to this method. /// </param> /// <returns>The authorization url.</returns> public static Uri BuildAuthorizationUrl(string scopes, string myApiUrl, string apiKey, string redirectUri, string state = null) { //Prepare a uri builder for the tenant URL var builder = new UriBuilder(RequestEngine.BuildUri(myApiUrl)); //Build the querystring var qs = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("client_id", apiKey), new KeyValuePair <string, string>("scope", scopes), new KeyValuePair <string, string>("redirect_uri", redirectUri) }; if (string.IsNullOrEmpty(state) == false) { qs.Add(new KeyValuePair <string, string>("state", state)); } builder.Path = "admin/oauth/authorize"; builder.Query = string.Join("&", qs.Select(s => $"{s.Key}={s.Value}")); return(builder.Uri); }
internal async Task SetObjectPropertyAsync <T>(BaseSetObjectPropertyParameters <T> parameters, int numObjectIds, CancellationToken token) => await RequestEngine.ExecuteRequestAsync(parameters, m => Task.FromResult <PrtgResponse>(ResponseParser.ParseSetObjectPropertyUrl(numObjectIds, m)), token).ConfigureAwait(false);
internal void SetObjectProperty <T>(BaseSetObjectPropertyParameters <T> parameters, int numObjectIds) => RequestEngine.ExecuteRequest(parameters, m => ResponseParser.ParseSetObjectPropertyUrl(numObjectIds, m));
private async Task <PrtgResponse> GetObjectPropertiesRawInternalAsync(int objectId, object objectType, CancellationToken token) => (await RequestEngine.ExecuteRequestAsync(new GetObjectPropertyParameters(objectId, objectType), token: token).ConfigureAwait(false));
private PrtgResponse GetObjectPropertiesRawInternal(int objectId, object objectType, CancellationToken token = default(CancellationToken)) => RequestEngine.ExecuteRequest(new GetObjectPropertyParameters(objectId, objectType), token: token);
private int CloneObject(CloneParameters parameters, CancellationToken token) => ResponseParser.Amend(RequestEngine.ExecuteRequest(parameters, ResponseParser.CloneRequestParser, token), ResponseParser.CloneResponseParser);
private async Task SetNotificationTriggerInternalAsync(TriggerParameters parameters, CancellationToken token) { await ValidateTriggerParametersAsync(parameters, token).ConfigureAwait(false); await RequestEngine.ExecuteRequestAsync(parameters, token : token).ConfigureAwait(false); }
internal async Task ApproveProbeInternalAsync(int probeId, ProbeApproval action, CancellationToken token) => await RequestEngine.ExecuteRequestAsync(new ApproveProbeParameters(probeId, action)).ConfigureAwait(false);
/// <summary> /// Subscribes a person to a <see cref="ConvertKitCourse"/>. /// </summary> /// <param name="email">The subscriber's email address.</param> /// <param name="firstName">The subscriber's first name.</param> /// <param name="courseId">The id of the Course to subscribe them to.</param> /// <returns>The subscriber.</returns> public async Task <ConvertKitSubscriber> SubscribeToCourse(string email, string firstName, long courseId) { var req = RequestEngine.CreateRequest($"courses/{courseId}/subscribe", Method.POST, "subscription"); return(await RequestEngine.ExecuteRequestAsync <ConvertKitSubscriber>(_RestClient, req)); }
internal void ApproveProbeInternal(Either <Probe, int> probeOrId, ProbeApproval action) => RequestEngine.ExecuteRequest(new ApproveProbeParameters(probeOrId, action));
internal void SetObjectProperty <T>(BaseSetObjectPropertyParameters <T> parameters, int numObjectIds, CancellationToken token) => RequestEngine.ExecuteRequest(parameters, m => ResponseParser.ParseSetObjectPropertyUrl(numObjectIds, m), token);
public void Awake() { Current = this; }
internal void ApproveProbeInternal(int probeId, ProbeApproval action) => RequestEngine.ExecuteRequest(new ApproveProbeParameters(probeId, action));
private async Task <XElement> GetChannelPropertiesAsync(int sensorId, int channelId, CancellationToken token) { var parameters = new ChannelPropertiesParameters(sensorId, channelId); return(await RequestEngine.ExecuteRequestAsync(parameters, r => ChannelSettings.GetChannelXml(r, channelId), token).ConfigureAwait(false)); }
internal void FoldObject(int objectId, bool fold) => RequestEngine.ExecuteRequest(new FoldParameters(objectId, fold));
private void SetNotificationTriggerInternal(TriggerParameters parameters, CancellationToken token) { ValidateTriggerParameters(parameters, token); RequestEngine.ExecuteRequest(parameters, token: token); }
protected BaseService(IceCatAccessConfig config) { _AccessConfig = config; _Client = RequestEngine.CreateClient(config); }
private XElement GetChannelProperties(int sensorId, int channelId, CancellationToken token) { var parameters = new ChannelPropertiesParameters(sensorId, channelId); return(RequestEngine.ExecuteRequest(parameters, r => ChannelSettings.GetChannelXml(r, channelId), token)); }