public static void ProcessEvents(EGAHTTPApiResponse responseEnum, JSONNode dataDict, string putbackSql, string deleteSql, int eventCount) { if (responseEnum == EGAHTTPApiResponse.Ok) { // Delete events GAStore.ExecuteQuerySync(deleteSql); GALogger.I("Event queue: " + eventCount + " events sent."); } else { // Put events back (Only in case of no response) if (responseEnum == EGAHTTPApiResponse.NoResponse) { GALogger.W("Event queue: Failed to send events to collector - Retrying next time"); GAStore.ExecuteQuerySync(putbackSql); // Delete events (When getting some anwser back always assume events are processed) } else { if (dataDict != null) { JSONNode json = null; IEnumerator <JSONNode> enumerator = dataDict.Childs.GetEnumerator(); if (enumerator.MoveNext()) { json = enumerator.Current; } if (responseEnum == EGAHTTPApiResponse.BadRequest && json is JSONArray) { GALogger.W("Event queue: " + eventCount + " events sent. " + dataDict.Count + " events failed GA server validation."); } else { GALogger.W("Event queue: Failed to send events."); } } else { GALogger.W("Event queue: Failed to send events."); } GAStore.ExecuteQuerySync(deleteSql); } } UpdateSessionTime(); }
public KeyValuePair <EGAHTTPApiResponse, JSONNode> SendEventsInArray(List <JSONNode> eventArray) #endif { JSONNode json; if (eventArray.Count == 0) { GALogger.D("sendEventsInArray called with missing eventArray"); } EGAHTTPApiResponse result = EGAHTTPApiResponse.NoResponse; string gameKey = GAState.GameKey; // Generate URL string url = baseUrl + "/" + gameKey + "/" + eventsUrlPath; GALogger.D("Sending 'events' URL: " + url); // make JSON string from data string JSONstring = GAUtilities.ArrayOfObjectsToJsonString(eventArray); if (JSONstring.Length == 0) { GALogger.D("sendEventsInArray JSON encoding failed of eventArray"); json = null; result = EGAHTTPApiResponse.JsonEncodeFailed; return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json)); } string body = ""; HttpStatusCode responseCode = (HttpStatusCode)0; string responseDescription = ""; string authorization = ""; try { byte[] payloadData = CreatePayloadData(JSONstring, useGzip); HttpWebRequest request = CreateRequest(url, payloadData, useGzip); authorization = request.Headers[HttpRequestHeader.Authorization]; #if WINDOWS_UWP || WINDOWS_WSA using (Stream dataStream = await request.GetRequestStreamAsync()) #else using (Stream dataStream = request.GetRequestStream()) #endif { dataStream.Write(payloadData, 0, payloadData.Length); } #if WINDOWS_UWP || WINDOWS_WSA using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) #else using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) #endif { using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { string responseString = reader.ReadToEnd(); responseCode = response.StatusCode; responseDescription = response.StatusDescription; // print result body = responseString; } } } } catch (WebException e) { if (e.Response != null) { using (HttpWebResponse response = (HttpWebResponse)e.Response) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(streamResponse)) { string responseString = streamRead.ReadToEnd(); responseCode = response.StatusCode; responseDescription = response.StatusDescription; body = responseString; } } } } } catch (Exception e) { GALogger.E(e.ToString()); } GALogger.D("events request content: " + body); EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Events"); // if not 200 result if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed events Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring); json = null; result = requestResponseEnum; return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json)); } // decode JSON JSONNode requestJsonDict = JSON.Parse(body); if (requestJsonDict == null) { json = null; result = EGAHTTPApiResponse.JsonDecodeFailed; return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json)); } // print reason if bad request if (requestResponseEnum == EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed Events Call. Bad request. Response: " + requestJsonDict.ToString()); } // return response json = requestJsonDict; result = requestResponseEnum; return(new KeyValuePair <EGAHTTPApiResponse, JSONNode>(result, json)); }
public KeyValuePair <EGAHTTPApiResponse, JSONClass> RequestInitReturningDict() #endif { JSONClass json; EGAHTTPApiResponse result = EGAHTTPApiResponse.NoResponse; string gameKey = GAState.GameKey; // Generate URL string url = baseUrl + "/" + gameKey + "/" + initializeUrlPath; GALogger.D("Sending 'init' URL: " + url); JSONClass initAnnotations = GAState.GetInitAnnotations(); // make JSON string from data string JSONstring = initAnnotations.ToString(); if (string.IsNullOrEmpty(JSONstring)) { result = EGAHTTPApiResponse.JsonEncodeFailed; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } string body = ""; HttpStatusCode responseCode = (HttpStatusCode)0; string responseDescription = ""; string authorization = ""; try { byte[] payloadData = CreatePayloadData(JSONstring, useGzip); HttpWebRequest request = CreateRequest(url, payloadData, useGzip); authorization = request.Headers[HttpRequestHeader.Authorization]; #if WINDOWS_UWP || WINDOWS_WSA using (Stream dataStream = await request.GetRequestStreamAsync()) #else using (Stream dataStream = request.GetRequestStream()) #endif { dataStream.Write(payloadData, 0, payloadData.Length); } #if WINDOWS_UWP || WINDOWS_WSA using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) #else using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) #endif { using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { string responseString = reader.ReadToEnd(); responseCode = response.StatusCode; responseDescription = response.StatusDescription; // print result body = responseString; } } } } catch (WebException e) { if (e.Response != null) { using (HttpWebResponse response = (HttpWebResponse)e.Response) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(streamResponse)) { string responseString = streamRead.ReadToEnd(); responseCode = response.StatusCode; responseDescription = response.StatusDescription; body = responseString; } } } } } catch (Exception e) { GALogger.E(e.ToString()); } // process the response GALogger.D("init request content : " + body); JSONNode requestJsonDict = JSON.Parse(body); EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Init"); // if not 200 result if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed Init Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring); result = requestResponseEnum; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } if (requestJsonDict == null) { GALogger.D("Failed Init Call. Json decoding failed"); result = EGAHTTPApiResponse.JsonDecodeFailed; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // print reason if bad request if (requestResponseEnum == EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed Init Call. Bad request. Response: " + requestJsonDict.AsObject.ToString()); // return bad request result result = requestResponseEnum; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // validate Init call values JSONClass validatedInitValues = GAValidator.ValidateAndCleanInitRequestResponse(requestJsonDict); if (validatedInitValues == null) { result = EGAHTTPApiResponse.BadResponse; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // all ok result = EGAHTTPApiResponse.Ok; json = validatedInitValues; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); }
public static void StartNewSession(EGAHTTPApiResponse initResponse, JSONObject initResponseDict) { // init is ok if (initResponse == EGAHTTPApiResponse.Ok && initResponseDict != null) { // set the time offset - how many seconds the local time is different from servertime long timeOffsetSeconds = 0; if (initResponseDict["server_ts"] != null) { long serverTs = initResponseDict["server_ts"].AsLong; timeOffsetSeconds = CalculateServerTimeOffset(serverTs); } initResponseDict.Add("time_offset", new JSONNumber(timeOffsetSeconds)); // insert new config in sql lite cross session storage GAStore.SetState(SdkConfigCachedKey, initResponseDict.SaveToBinaryBase64()); // set new config and cache in memory Instance.sdkConfigCached = initResponseDict; Instance.sdkConfig = initResponseDict; Instance.InitAuthorized = true; } else if (initResponse == EGAHTTPApiResponse.Unauthorized) { GALogger.W("Initialize SDK failed - Unauthorized"); Instance.InitAuthorized = false; } else { // log the status if no connection if (initResponse == EGAHTTPApiResponse.NoResponse || initResponse == EGAHTTPApiResponse.RequestTimeout) { GALogger.I("Init call (session start) failed - no response. Could be offline or timeout."); } else if (initResponse == EGAHTTPApiResponse.BadResponse || initResponse == EGAHTTPApiResponse.JsonEncodeFailed || initResponse == EGAHTTPApiResponse.JsonDecodeFailed) { GALogger.I("Init call (session start) failed - bad response. Could be bad response from proxy or GA servers."); } else if (initResponse == EGAHTTPApiResponse.BadRequest || initResponse == EGAHTTPApiResponse.UnknownResponseCode) { GALogger.I("Init call (session start) failed - bad request or unknown response."); } // init call failed (perhaps offline) if (Instance.sdkConfig == null) { if (Instance.sdkConfigCached != null) { GALogger.I("Init call (session start) failed - using cached init values."); // set last cross session stored config init values Instance.sdkConfig = Instance.sdkConfigCached; } else { GALogger.I("Init call (session start) failed - using default init values."); // set default init values Instance.sdkConfig = Instance.sdkConfigDefault; } } else { GALogger.I("Init call (session start) failed - using cached init values."); } Instance.InitAuthorized = true; } { JSONNode currentSdkConfig = SdkConfig; if (currentSdkConfig["enabled"].IsBoolean && !currentSdkConfig["enabled"].AsBool) { Instance.Enabled = false; } else if (!Instance.InitAuthorized) { Instance.Enabled = false; } else { Instance.Enabled = true; } } // set offset in state (memory) from current config (config could be from cache etc.) Instance.ClientServerTimeOffset = SdkConfig["time_offset"] != null ? SdkConfig["time_offset"].AsLong : 0; // populate configurations PopulateConfigurations(SdkConfig); // if SDK is disabled in config if (!IsEnabled()) { GALogger.W("Could not start session: SDK is disabled."); // stop event queue // + make sure it's able to restart if another session detects it's enabled again GAEvents.StopEventQueue(); return; } else { GAEvents.EnsureEventQueueIsRunning(); } // generate the new session string newSessionId = Guid.NewGuid().ToString(); string newSessionIdLowercase = newSessionId.ToLowerInvariant(); // Set session id SessionId = newSessionIdLowercase; // Set session start SessionStart = GetClientTsAdjusted(); // Add session start event GAEvents.AddSessionStartEvent(); }