static void RemoteSettings_Completed(bool wasUpdatedFromServer, bool settingsChanged, int serverResponse) { requestInProgress = false; var origin = ConfigOrigin.Default; if (wasUpdatedFromServer) { if (serverResponse == 200) { requestStatus = ConfigRequestStatus.Success; } else { requestStatus = ConfigRequestStatus.Failed; } origin = ConfigOrigin.Remote; } else { requestStatus = ConfigRequestStatus.Success; origin = ConfigOrigin.Cached; } FetchCompleted?.Invoke(new ConfigResponse() { requestOrigin = origin, status = requestStatus }); if (queueRequest) { appConfig.ForceUpdate(); queueRequest = false; } }
private void FetchDeviceInformation(string theIPAddress) { var DevInfoUrl = "http://" + theIPAddress + "/devinfo.xml"; string xmlStr = string.Empty; do { try { using (var wc = new WebClient()) { xmlStr = wc.DownloadString(DevInfoUrl); } } catch (Exception ex) { Log?.Invoke(EventLogEntryCodes.FetchException, new string[] { theIPAddress, ex.Message }); FetchError?.Invoke(); Task.Delay(3000).Wait(); } } while (xmlStr == string.Empty && (!m_TokenSource.Token.IsCancellationRequested)); if (m_TokenSource.Token.IsCancellationRequested) { return; } else { Log?.Invoke(EventLogEntryCodes.FetchSuccessful, new string[] { theIPAddress }); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlStr); XmlNode MACNode = xmlDoc.DocumentElement.SelectSingleNode("/lines/macaddr"); XmlNode LocNode = xmlDoc.DocumentElement.SelectSingleNode("/lines/loc"); XmlNode FwverNode = xmlDoc.DocumentElement.SelectSingleNode("/lines/fwver"); XmlNode ModelNode = xmlDoc.DocumentElement.SelectSingleNode("/lines/model"); XmlNode DevNameNode = xmlDoc.DocumentElement.SelectSingleNode("/lines/devname"); FetchCompleted?.Invoke(new DeviceInformation { MACAddress = MACNode.InnerText, Name = DevNameNode.InnerText, Location = LocNode.InnerText, Firmware = FwverNode.InnerText, ProductModel = ModelNode.InnerText }); } }
private static void OnRawResponseReturned(ConfigOrigin origin, Dictionary <string, string> headers, string body) { if (body == null || headers == null) { return; } var configResponse = new ConfigResponse() { requestOrigin = origin, status = ConfigRequestStatus.Pending }; foreach (var validationFunc in rawResponseValidators) { if (validationFunc(headers, body) == false) { configResponse.status = ConfigRequestStatus.Failed; requestStatus = configResponse.status; FetchCompleted?.Invoke(configResponse); return; } } RawResponseValidated?.Invoke(origin, headers, body); JObject responseJObj = null; try { responseJObj = JObject.Parse(body); configResponse.status = ConfigRequestStatus.Success; } catch { configResponse.status = ConfigRequestStatus.Failed; } ResponseParsed?.Invoke(configResponse, responseJObj); requestStatus = configResponse.status; FetchCompleted?.Invoke(configResponse); }
private void OnTimedEvent(object sender, ElapsedEventArgs e) { if (!workQueue.TryDequeue(out Link l)) { return; } if (ShouldFetch != null) { var args = new ShouldFetchEventArgs(l); ShouldFetch(this, args); if (args.Cancel) { return; // do not fail/complete } } switch (DiscardMode) { case DiscardModeTypes.Fail: FetchFailed?.Invoke(this, new FetchFailEventArgs(l, 0, new Exception("NullDownloader:DiscardModeTypes.Fail"), new HeaderCollection())); break; case DiscardModeTypes.CompleteEmpty: FetchCompleted?.Invoke(this, new FetchCompleteEventArgs(l, new byte[0], new HeaderCollection(), new HeaderCollection())); break; case DiscardModeTypes.Ignore: default: // ignore ... break; } }
/// <summary> /// Raises the event. /// </summary> /// <param name="e"> /// The parameter provided to the event handler. /// </param> /// <remarks> /// <para> /// If your application is running in WPF, this event /// will be raised on the UI thread automatically. /// </para><para> /// If your application is running in Windows Forms, /// this event will be raised on a background thread. /// If you also set DataPortal.SynchronizationObject /// to a Windows Forms form or control, then the event /// will be raised on the UI thread automatically. /// </para><para> /// In any other environment (such as ASP.NET), this /// event will be raised on a background thread. /// </para> /// </remarks> protected virtual void OnFetchCompleted(DataPortalResult <T> e) { FetchCompleted?.Invoke(this, e); }
private void fetchCompleted(FetchCompleteEventArgs args) { lock (hExecuted) // Hashsets are not threadsafe { hExecuted.Add(args.Link.Uri.ToString()); if (args.Link.MovedUri != null) { hExecuted.Add(args.Link.MovedUri.ToString()); } lCompleted.Add(args.Link); } // Main CallBack if (FetchCompleted != null) { foreach (FetchComplete e in FetchCompleted.GetInvocationList()) { try { e.DynamicInvoke(this, args); } catch (Exception ex) { log.Error(ex, "Error on FetchComplete event"); } } } // Additional Link callback args.Link.FetchCompleteCallBack?.Invoke(this, args); // Parsers var contentType = args.ResponseHeaders.FirstOrDefault(h => h.Key == "Content-Type"); if (contentType.Value == null) { // try to guess var textContent = System.Text.Encoding.ASCII.GetString(args.Result.Take(128).ToArray()); if (!string.IsNullOrEmpty(textContent)) { if (textContent[0] == '{' && textContent.Contains(":")) { contentType = new KeyValuePair <string, string>("Content-Type", "application/json"); } if (textContent[0] == '<' && textContent.ToLower().Contains("html")) { contentType = new KeyValuePair <string, string>("Content-Type", "text/html"); } } } if (!string.IsNullOrEmpty(contentType.Value)) { foreach (var p in Parsers) { try { if (p.MimeTypes.Any(m => m.Equals(contentType.Value, StringComparison.InvariantCultureIgnoreCase))) { p.Parse(this, args); } } catch { } } } }
static void PostConfig(object userAttributes, object appAttributes) { requestStatus = ConfigRequestStatus.Pending; long timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds(); long rtSinceStart = (long)(Time.realtimeSinceStartup * 1000000); var commonJobj = JObject.FromObject(commonPayload); commonJobj.Add("t_since_start", rtSinceStart); JObject json = new JObject(); json.Add("common", commonJobj); List <JObject> items = new List <JObject>(); items.Add(json); items.Add(CreatePayloadJObjectFromValuesJObject(JObject.FromObject(deliveryPayload), "analytics.delivery.v1", timestamp)); var deviceInfoJObj = JObject.FromObject(deviceInfoPayload); deviceInfoJObj.Add("t_since_start", rtSinceStart); items.Add(CreatePayloadJObjectFromValuesJObject(deviceInfoJObj, "analytics.deviceInfo.v1", timestamp)); if (userAttributes == null) { items.Add(CreatePayloadJObjectFromValuesJObject(new JObject(), "analytics.deliveryUserAttributes.v1", timestamp)); } else { items.Add(CreatePayloadJObjectFromValuesJObject(JObject.FromObject(userAttributes), "analytics.deliveryUserAttributes.v1", timestamp)); } if (appAttributes == null) { items.Add(CreatePayloadJObjectFromValuesJObject(new JObject(), "analytics.deliveryAppAttributes.v1", timestamp)); } else { items.Add(CreatePayloadJObjectFromValuesJObject(JObject.FromObject(appAttributes), "analytics.deliveryAppAttributes.v1", timestamp)); } foreach (var func in requestPayloadProviders) { items.Add(func.Invoke()); } var sb = new StringBuilder(); using (var textWriter = new StringWriter(sb)) { ToNewlineDelimitedJson(textWriter, items); } var jsonText = sb.ToString(); var request = new UnityWebRequest("https://config.uca.cloud.unity3d.com", UnityWebRequest.kHttpVerbPOST); request.SetRequestHeader("Content-Type", "application/json"); foreach (var headerProvider in requestHeaderProviders) { var header = headerProvider.Invoke(); request.SetRequestHeader(header.key, header.value); } request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(jsonText)); request.downloadHandler = new DownloadHandlerBuffer(); request.SendWebRequest().completed += (AsyncOperation op) => { var origin = ConfigOrigin.Remote; var response = ((UnityWebRequestAsyncOperation)op).webRequest; var configResponse = new ConfigResponse() { requestOrigin = origin, status = requestStatus }; if (response.isHttpError || response.isNetworkError) { configResponse.status = ConfigRequestStatus.Failed; FetchCompleted?.Invoke(configResponse); } else { RawResponseReturned?.Invoke(origin, request.GetResponseHeaders(), request.downloadHandler.text); } }; }
/// <summary>Invokes <see cref="FetchCompleted"/>.</summary> /// <param name="remote">Remote.</param> /// <param name="changes">Reference changes.</param> internal void OnFetchCompleted(Remote remote, ReferenceChange[] changes) => FetchCompleted?.Invoke(this, new FetchCompletedEventArgs(remote, changes));