Esempio n. 1
0
        public static void Initialize(string gameKey, string gameSecret)
        {
#if WINDOWS_UWP || WINDOWS_WSA || WINDOWS_PHONE
            CoreApplication.Suspending += OnSuspending;
            CoreApplication.Resuming   += OnResuming;
#endif
            GADevice.UpdateConnectionType();

            GAThreading.PerformTaskOnGAThread("initialize", () =>
            {
                if (IsSdkReady(true, false))
                {
                    GALogger.W("SDK already initialized. Can only be called once.");
                    return;
                }
                if (!GAValidator.ValidateKeys(gameKey, gameSecret))
                {
                    GALogger.W("SDK failed initialize. Game key or secret key is invalid. Can only contain characters A-z 0-9, gameKey is 32 length, gameSecret is 40 length. Failed keys - gameKey: " + gameKey + ", secretKey: " + gameSecret);
                    return;
                }

                GAState.SetKeys(gameKey, gameSecret);

                if (!GAStore.EnsureDatabase(false))
                {
                    GALogger.W("Could not ensure/validate local event database: " + GADevice.WritablePath);
                }

                GAState.InternalInitialize();
            });
        }
        private static void TrimEventTable()
        {
            if (DbSizeBytes > MaxDbSizeBytesBeforeTrim)
            {
                JSONArray resultSessionArray = ExecuteQuerySync("SELECT session_id, Max(client_ts) FROM ga_events GROUP BY session_id ORDER BY client_ts LIMIT 3");

                if (resultSessionArray != null && resultSessionArray.Count > 0)
                {
                    string sessionDeleteString = "";

                    for (int i = 0; i < resultSessionArray.Count; ++i)
                    {
                        sessionDeleteString += resultSessionArray[i].Value;

                        if (i < resultSessionArray.Count - 1)
                        {
                            sessionDeleteString += ",";
                        }
                    }

                    string deleteOldSessionSql = "DELETE FROM ga_events WHERE session_id IN (\"" + sessionDeleteString + "\");";
                    GALogger.W("Database too large when initializing. Deleting the oldest 3 sessions.");
                    ExecuteQuerySync(deleteOldSessionSql);
                    ExecuteQuerySync("VACUUM");
                }
            }
        }
Esempio n. 3
0
        public static void AddSessionEndEvent()
        {
            long session_start_ts   = GAState.SessionStart;
            long client_ts_adjusted = GAState.GetClientTsAdjusted();
            long sessionLength      = client_ts_adjusted - session_start_ts;

            if (sessionLength < 0)
            {
                // Should never happen.
                // Could be because of edge cases regarding time altering on device.
                GALogger.W("Session length was calculated to be less then 0. Should not be possible. Resetting to 0.");
                sessionLength = 0;
            }

            // Event specific data
            JSONClass eventDict = new JSONClass();

            eventDict["category"] = CategorySessionEnd;
            eventDict.Add("length", new JSONData(sessionLength));

            // Add custom dimensions
            AddDimensionsToEvent(eventDict);

            // Add to store
            AddEventToStore(eventDict);

            // Log
            GALogger.I("Add SESSION END event.");

            // Send all event right away
            ProcessEvents("", false);
        }
Esempio n. 4
0
 public static bool ValidateGender(EGAGender gender)
 {
     if (gender == EGAGender.Undefined || !(gender == EGAGender.Male || gender == EGAGender.Female))
     {
         GALogger.W("Validation fail - gender: Has to be 'male' or 'female'.");
         return(false);
     }
     return(true);
 }
Esempio n. 5
0
 public static bool ValidateBirthyear(long birthYear)
 {
     if (birthYear < 0 || birthYear > 9999)
     {
         GALogger.W("Validation fail - birthYear: Cannot be (null) or invalid range.");
         return(false);
     }
     return(true);
 }
Esempio n. 6
0
 public static bool ValidateFacebookId(string facebookId)
 {
     if (!ValidateString(facebookId, false))
     {
         GALogger.W("Validation fail - facebook id: id cannot be (null), empty or above 64 characters.");
         return(false);
     }
     return(true);
 }
Esempio n. 7
0
 public static bool ValidateResourceEvent(EGAResourceFlowType flowType, string currency, long amount, string itemType, string itemId)
 {
     if (flowType == EGAResourceFlowType.Undefined)
     {
         GALogger.W("Validation fail - resource event - flowType: Invalid flow type.");
         return(false);
     }
     if (string.IsNullOrEmpty(currency))
     {
         GALogger.W("Validation fail - resource event - currency: Cannot be (null)");
         return(false);
     }
     if (!GAState.HasAvailableResourceCurrency(currency))
     {
         GALogger.W("Validation fail - resource event - currency: Not found in list of pre-defined available resource currencies. String: " + currency);
         return(false);
     }
     if (!(amount > 0))
     {
         GALogger.W("Validation fail - resource event - amount: Float amount cannot be 0 or negative. Value: " + amount);
         return(false);
     }
     if (string.IsNullOrEmpty(itemType))
     {
         GALogger.W("Validation fail - resource event - itemType: Cannot be (null)");
         return(false);
     }
     if (!ValidateEventPartLength(itemType, false))
     {
         GALogger.W("Validation fail - resource event - itemType: Cannot be (null), empty or above 64 characters. String: " + itemType);
         return(false);
     }
     if (!ValidateEventPartCharacters(itemType))
     {
         GALogger.W("Validation fail - resource event - itemType: Cannot contain other characters than A-z, 0-9, -_., ()!?. String: " + itemType);
         return(false);
     }
     if (!GAState.HasAvailableResourceItemType(itemType))
     {
         GALogger.W("Validation fail - resource event - itemType: Not found in list of pre-defined available resource itemTypes. String: " + itemType);
         return(false);
     }
     if (!ValidateEventPartLength(itemId, false))
     {
         GALogger.W("Validation fail - resource event - itemId: Cannot be (null), empty or above 64 characters. String: " + itemId);
         return(false);
     }
     if (!ValidateEventPartCharacters(itemId))
     {
         GALogger.W("Validation fail - resource event - itemId: Cannot contain other characters than A-z, 0-9, -_., ()!?. String: " + itemId);
         return(false);
     }
     return(true);
 }
Esempio n. 8
0
 public static void SetCustomDimension03(string dimension)
 {
     GAThreading.PerformTaskOnGAThread("setCustomDimension03", () =>
     {
         if (!GAValidator.ValidateDimension03(dimension))
         {
             GALogger.W("Could not set custom03 dimension value to '" + dimension + "'. Value not found in available custom03 dimension values");
             return;
         }
         GAState.SetCustomDimension03(dimension);
     });
 }
Esempio n. 9
0
 public static void ConfigureAvailableCustomDimensions03(params string[] customDimensions)
 {
     GAThreading.PerformTaskOnGAThread("configureAvailableCustomDimensions03", () =>
     {
         if (IsSdkReady(true, false))
         {
             GALogger.W("Available custom dimensions must be set before SDK is initialized");
             return;
         }
         GAState.AvailableCustomDimensions03 = customDimensions;
     });
 }
Esempio n. 10
0
 public static void ConfigureAvailableResourceItemTypes(params string[] resourceItemTypes)
 {
     GAThreading.PerformTaskOnGAThread("configureAvailableResourceItemTypes", () =>
     {
         if (IsSdkReady(true, false))
         {
             GALogger.W("Available resource item types must be set before SDK is initialized");
             return;
         }
         GAState.AvailableResourceItemTypes = resourceItemTypes;
     });
 }
Esempio n. 11
0
        public static bool ValidateBusinessEvent(string currency, long amount, string cartType, string itemType, string itemId)
        {
            // validate currency
            if (!ValidateCurrency(currency))
            {
                GALogger.W("Validation fail - business event - currency: Cannot be (null) and need to be A-Z, 3 characters and in the standard at openexchangerates.org. Failed currency: " + currency);
                return(false);
            }

            if (amount < 0)
            {
                GALogger.W("Validation fail - business event - amount. Cannot be less than 0. Failed amount: " + amount);
                return(false);
            }

            // validate cartType
            if (!ValidateShortString(cartType, true))
            {
                GALogger.W("Validation fail - business event - cartType. Cannot be above 32 length. String: " + cartType);
                return(false);
            }

            // validate itemType length
            if (!ValidateEventPartLength(itemType, false))
            {
                GALogger.W("Validation fail - business event - itemType: Cannot be (null), empty or above 64 characters. String: " + itemType);
                return(false);
            }

            // validate itemType chars
            if (!ValidateEventPartCharacters(itemType))
            {
                GALogger.W("Validation fail - business event - itemType: Cannot contain other characters than A-z, 0-9, -_., ()!?. String: " + itemType);
                return(false);
            }

            // validate itemId
            if (!ValidateEventPartLength(itemId, false))
            {
                GALogger.W("Validation fail - business event - itemId. Cannot be (null), empty or above 64 characters. String: " + itemId);
                return(false);
            }

            if (!ValidateEventPartCharacters(itemId))
            {
                GALogger.W("Validation fail - business event - itemId: Cannot contain other characters than A-z, 0-9, -_., ()!?. String: " + itemId);
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        public static JSONObject ValidateAndCleanInitRequestResponse(JSONNode initResponse)
        {
            // make sure we have a valid dict
            if (initResponse == null)
            {
                GALogger.W("validateInitRequestResponse failed - no response dictionary.");
                return(null);
            }

            JSONObject validatedDict = new JSONObject();

            // validate enabled field
            try
            {
                validatedDict.Add("enabled", new JSONBool(initResponse["enabled"].IsBoolean ? initResponse["enabled"].AsBool : true));
            }
            catch (Exception)
            {
                GALogger.W("validateInitRequestResponse failed - invalid type in 'enabled' field.");
                return(null);
            }

            // validate server_ts
            try
            {
                long serverTsNumber = initResponse["server_ts"].IsNumber ? initResponse["server_ts"].AsLong : -1;
                if (serverTsNumber > 0)
                {
                    validatedDict.Add("server_ts", new JSONNumber(serverTsNumber));
                }
            }
            catch (Exception e)
            {
                GALogger.W("validateInitRequestResponse failed - invalid type in 'server_ts' field. type=" + initResponse["server_ts"].GetType() + ", value=" + initResponse["server_ts"] + ", " + e);
                return(null);
            }

            // validate configurations field
            try
            {
                validatedDict.Add("configurations", initResponse["configurations"].IsArray ? initResponse["configurations"].AsArray : new JSONArray());
            }
            catch (Exception e)
            {
                GALogger.W("validateInitRequestResponse failed - invalid type in 'configurations' field. type=" + initResponse["configurations"].GetType() + ", value=" + initResponse["configurations"] + ", " + e);
                return(null);
            }

            return(validatedDict);
        }
Esempio n. 13
0
        public static bool ValidateArrayOfStrings(long maxCount, long maxStringLength, bool allowNoValues, string logTag, params string[] arrayOfStrings)
        {
            string arrayTag = logTag;

            // use arrayTag to annotate warning log
            if (string.IsNullOrEmpty(arrayTag))
            {
                arrayTag = "Array";
            }

            if (arrayOfStrings == null)
            {
                GALogger.W(arrayTag + " validation failed: array cannot be null. ");
                return(false);
            }

            // check if empty
            if (allowNoValues == false && arrayOfStrings.Length == 0)
            {
                GALogger.W(arrayTag + " validation failed: array cannot be empty. ");
                return(false);
            }

            // check if exceeding max count
            if (maxCount > 0 && arrayOfStrings.Length > maxCount)
            {
                GALogger.W(arrayTag + " validation failed: array cannot exceed " + maxCount + " values. It has " + arrayOfStrings.Length + " values.");
                return(false);
            }

            // validate each string
            foreach (string arrayString in arrayOfStrings)
            {
                int stringLength = arrayString == null ? 0 : arrayString.Length;
                // check if empty (not allowed)
                if (stringLength == 0)
                {
                    GALogger.W(arrayTag + " validation failed: contained an empty string.");
                    return(false);
                }

                // check if exceeding max length
                if (maxStringLength > 0 && stringLength > maxStringLength)
                {
                    GALogger.W(arrayTag + " validation failed: a string exceeded max allowed length (which is: " + maxStringLength + "). String was: " + arrayString);
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 14
0
 public static bool ValidateErrorEvent(EGAErrorSeverity severity, string message)
 {
     if (severity == EGAErrorSeverity.Undefined)
     {
         GALogger.W("Validation fail - error event - severity: Severity was unsupported value.");
         return(false);
     }
     if (!ValidateLongString(message, true))
     {
         GALogger.W("Validation fail - error event - message: Message cannot be above 8192 characters.");
         return(false);
     }
     return(true);
 }
Esempio n. 15
0
        public static bool ValidateSdkErrorEvent(string gameKey, string gameSecret, EGASdkErrorType type)
        {
            if (!ValidateKeys(gameKey, gameSecret))
            {
                return(false);
            }

            if (type == EGASdkErrorType.Undefined)
            {
                GALogger.W("Validation fail - sdk error event - type: Type was unsupported value.");
                return(false);
            }
            return(true);
        }
Esempio n. 16
0
 public static bool ValidateDesignEvent(string eventId, double value)
 {
     if (!ValidateEventIdLength(eventId))
     {
         GALogger.W("Validation fail - design event - eventId: Cannot be (null) or empty. Only 5 event parts allowed seperated by :. Each part need to be 32 characters or less. String: " + eventId);
         return(false);
     }
     if (!ValidateEventIdCharacters(eventId))
     {
         GALogger.W("Validation fail - design event - eventId: Non valid characters. Only allowed A-z, 0-9, -_., ()!?. String: " + eventId);
         return(false);
     }
     // value: allow 0, negative and nil (not required)
     return(true);
 }
Esempio n. 17
0
        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();
        }
Esempio n. 18
0
 public static void ConfigureBuild(string build)
 {
     GAThreading.PerformTaskOnGAThread("configureBuild", () =>
     {
         if (IsSdkReady(true, false))
         {
             GALogger.W("Build version must be set before SDK is initialized.");
             return;
         }
         if (!GAValidator.ValidateBuild(build))
         {
             GALogger.I("Validation fail - configure build: Cannot be null, empty or above 32 length. String: " + build);
             return;
         }
         GAState.Build = build;
     });
 }
Esempio n. 19
0
        public void SendSdkErrorEvent(EGASdkErrorType type)
        {
            if (!GAState.IsEventSubmissionEnabled)
            {
                return;
            }

            string gameKey   = GAState.GameKey;
            string secretKey = GAState.GameSecret;

            // Validate
            if (!GAValidator.ValidateSdkErrorEvent(gameKey, secretKey, type))
            {
                return;
            }

            // Generate URL
            string url = baseUrl + "/" + gameKey + "/" + eventsUrlPath;

            GALogger.D("Sending 'events' URL: " + url);

            string payloadJSONString = "";

            JSONObject json = GAState.GetSdkErrorEventAnnotations();

            string typeString = SdkErrorTypeToString(type);

            json.Add("type", typeString);

            List <JSONNode> eventArray = new List <JSONNode>();

            eventArray.Add(json);
            payloadJSONString = GAUtilities.ArrayOfObjectsToJsonString(eventArray);

            if (string.IsNullOrEmpty(payloadJSONString))
            {
                GALogger.W("sendSdkErrorEvent: JSON encoding failed.");
                return;
            }

            GALogger.D("sendSdkErrorEvent json: " + payloadJSONString);
            byte[]       payloadData  = Encoding.UTF8.GetBytes(payloadJSONString);
            SdkErrorTask sdkErrorTask = new SdkErrorTask(type, payloadData, secretKey);

            sdkErrorTask.Execute(url);
        }
Esempio n. 20
0
        private static bool IsSdkReady(bool needsInitialized, bool warn, String message)
        {
            if (!string.IsNullOrEmpty(message))
            {
                message = message + ": ";
            }

            // Make sure database is ready
            if (!GAStore.IsTableReady)
            {
                if (warn)
                {
                    GALogger.W(message + "Datastore not initialized");
                }
                return(false);
            }
            // Is SDK initialized
            if (needsInitialized && !GAState.Initialized)
            {
                if (warn)
                {
                    GALogger.W(message + "SDK is not initialized");
                }
                return(false);
            }
            // Is SDK enabled
            if (needsInitialized && !GAState.IsEnabled())
            {
                if (warn)
                {
                    GALogger.W(message + "SDK is disabled");
                }
                return(false);
            }
            // Is session started
            if (needsInitialized && !GAState.SessionIsStarted())
            {
                if (warn)
                {
                    GALogger.W(message + "Session has not started yet");
                }
                return(false);
            }
            return(true);
        }
Esempio n. 21
0
        protected void OnPostExecute(HttpStatusCode responseCode, string responseDescription)
        {
            if (string.IsNullOrEmpty(this.body))
            {
                GALogger.D("sdk error failed. Might be no connection. Description: " + responseDescription + ", Status code: " + responseCode);
                return;
            }

            if (responseCode != HttpStatusCode.OK)
            {
                GALogger.W("sdk error failed. response code not 200. status code: " + responseCode + ", description: " + responseDescription + ", body: " + this.body);
                return;
            }
            else
            {
                countMap[this.type] = countMap[this.type] + 1;
            }
        }
Esempio n. 22
0
        public static bool ValidateResourceItemTypes(params string[] resourceItemTypes)
        {
            if (!ValidateArrayOfStrings(20, 32, false, "resource item types", resourceItemTypes))
            {
                return(false);
            }

            // validate each resourceItemType for eventpart validation
            foreach (string resourceItemType in resourceItemTypes)
            {
                if (!ValidateEventPartCharacters(resourceItemType))
                {
                    GALogger.W("resource item types validation failed: a resource item type cannot contain other characters than A-z, 0-9, -_., ()!?. String was: " + resourceItemType);
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 23
0
        public static bool ValidateResourceCurrencies(params string[] resourceCurrencies)
        {
            if (!ValidateArrayOfStrings(20, 64, false, "resource currencies", resourceCurrencies))
            {
                return(false);
            }

            // validate each string for regex
            foreach (string resourceCurrency in resourceCurrencies)
            {
                if (!GAUtilities.StringMatch(resourceCurrency, "^[A-Za-z]+$"))
                {
                    GALogger.W("resource currencies validation failed: a resource currency can only be A-Z, a-z. String was: " + resourceCurrency);
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 24
0
        public static void ConfigureUserId(string uId)
        {
            GAThreading.PerformTaskOnGAThread("configureUserId", () =>
            {
                if (IsSdkReady(true, false))
                {
                    GALogger.W("A custom user id must be set before SDK is initialized.");
                    return;
                }
                if (!GAValidator.ValidateUserId(uId))
                {
                    GALogger.I("Validation fail - configure user_id: Cannot be null, empty or above 64 length. Will use default user_id method. Used string: " + uId);
                    return;
                }

                GAState.UserId = uId;
            });
        }
        public static JSONClass ValidateAndCleanInitRequestResponse(JSONNode initResponse)
        {
            // make sure we have a valid dict
            if (initResponse == null)
            {
                GALogger.W("validateInitRequestResponse failed - no response dictionary.");
                return(null);
            }

            JSONClass validatedDict = new JSONClass();

            // validate enabled field
            try
            {
                validatedDict.Add("enabled", new JSONData(initResponse["enabled"].AsBool));
            }
            catch (Exception)
            {
                GALogger.W("validateInitRequestResponse failed - invalid type in 'enabled' field.");
                return(null);
            }

            // validate server_ts
            try
            {
                long serverTsNumber = initResponse["server_ts"].AsLong;
                if (serverTsNumber > 0)
                {
                    validatedDict.Add("server_ts", new JSONData(serverTsNumber));
                }
                else
                {
                    GALogger.W("validateInitRequestResponse failed - invalid value in 'server_ts' field.");
                    return(null);
                }
            }
            catch (Exception e)
            {
                GALogger.W("validateInitRequestResponse failed - invalid type in 'server_ts' field. type=" + initResponse["server_ts"].GetType() + ", value=" + initResponse["server_ts"] + ", " + e);
                return(null);
            }

            return(validatedDict);
        }
Esempio n. 26
0
#pragma warning disable 0162
        public static void SetState(string key, string value)
        {
                        #if !UNITY_EDITOR
            if (value == null)
            {
                if (InMemory)
                {
#if UNITY
                    if (UnityEngine.PlayerPrefs.HasKey(State.GAState.InMemoryPrefix + key))
                    {
                        UnityEngine.PlayerPrefs.DeleteKey(State.GAState.InMemoryPrefix + key);
                    }
#else
                    GALogger.W("SetState: No implementation yet for InMemory=true");
#endif
                }
                else
                {
                    Dictionary <string, object> parameterArray = new Dictionary <string, object>();
                    parameterArray.Add("$key", key);
                    ExecuteQuerySync("DELETE FROM ga_state WHERE key = $key;", parameterArray);
                }
            }
            else
            {
                if (InMemory)
                {
#if UNITY
                    UnityEngine.PlayerPrefs.SetString(State.GAState.InMemoryPrefix + key, value);
#else
                    GALogger.W("SetState: No implementation yet for InMemory=true");
#endif
                }
                else
                {
                    Dictionary <string, object> parameterArray = new Dictionary <string, object>();
                    parameterArray.Add("$key", key);
                    parameterArray.Add("$value", value);
                    ExecuteQuerySync("INSERT OR REPLACE INTO ga_state (key, value) VALUES($key, $value);", parameterArray, true);
                }
            }
                        #endif
        }
Esempio n. 27
0
        public static void AddSessionEndEvent()
        {
            if (!GAState.IsEventSubmissionEnabled)
            {
                return;
            }

            long session_start_ts   = GAState.SessionStart;
            long client_ts_adjusted = GAState.GetClientTsAdjusted();
            long sessionLength      = client_ts_adjusted - session_start_ts;

            if (sessionLength < 0)
            {
                // Should never happen.
                // Could be because of edge cases regarding time altering on device.
                GALogger.W("Session length was calculated to be less then 0. Should not be possible. Resetting to 0.");
                sessionLength = 0;
            }

            // Event specific data
            JSONObject eventDict = new JSONObject();

            eventDict["category"] = CategorySessionEnd;
            eventDict.Add("length", new JSONNumber(sessionLength));

            // Add custom dimensions
            AddDimensionsToEvent(eventDict);

            IDictionary <string, object> fieldsToUse = GAState.CurrentGlobalCustomEventFields;

            // Add custom fields
            AddFieldsToEvent(eventDict, GAState.ValidateAndCleanCustomFields(fieldsToUse));

            // Add to store
            AddEventToStore(eventDict);

            // Log
            GALogger.I("Add SESSION END event.");

            // Send all event right away
            ProcessEvents("", false);
        }
Esempio n. 28
0
        private static void AddEventToStore(JSONClass eventData)
#endif
        {
            // Check if datastore is available
            if (!GAStore.IsTableReady)
            {
                GALogger.W("Could not add event: SDK datastore error");
                return;
            }

            // Check if we are initialized
            if (!GAState.Initialized)
            {
                GALogger.W("Could not add event: SDK is not initialized");
                return;
            }

            try
            {
                // Check db size limits (10mb)
                // If database is too large block all except user, session and business
                if (GAStore.IsDbTooLargeForEvents && !GAUtilities.StringMatch(eventData["category"].AsString, "^(user|session_end|business)$"))
                {
                    GALogger.W("Database too large. Event has been blocked.");
                    return;
                }

                // Get default annotations
                JSONClass ev = GAState.GetEventAnnotations();

                // Create json with only default annotations
                string jsonDefaults = ev.SaveToBase64();

                // Merge with eventData
                foreach (KeyValuePair <string, JSONNode> pair in eventData)
                {
                    ev.Add(pair.Key, pair.Value);
                }

                // Create json string representation
                string json = ev.ToString();

                // output if VERBOSE LOG enabled

                GALogger.II("Event added to queue: " + json);

                // Add to store
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("$status", "new");
                parameters.Add("$category", ev["category"].Value);
                parameters.Add("$session_id", ev["session_id"].Value);
                parameters.Add("$client_ts", ev["client_ts"].Value);
                parameters.Add("$event", ev.SaveToBase64());
                string sql = "INSERT INTO ga_events (status, category, session_id, client_ts, event) VALUES($status, $category, $session_id, $client_ts, $event);";

                GAStore.ExecuteQuerySync(sql, parameters);

                // Add to session store if not last
                if (eventData["category"].AsString.Equals(CategorySessionEnd))
                {
                    parameters.Clear();
                    parameters.Add("$session_id", ev["session_id"].Value);
                    sql = "DELETE FROM ga_session WHERE session_id = $session_id;";
                    GAStore.ExecuteQuerySync(sql, parameters);
                }
                else
                {
                    sql = "INSERT OR REPLACE INTO ga_session(session_id, timestamp, event) VALUES($session_id, $timestamp, $event);";
                    parameters.Clear();
                    parameters.Add("$session_id", ev["session_id"].Value);
                    parameters.Add("$timestamp", GAState.SessionStart);
                    parameters.Add("$event", jsonDefaults);
                    GAStore.ExecuteQuerySync(sql, parameters);
                }
            }
            catch (Exception e)
            {
                GALogger.E("addEventToStoreWithEventData: error using json");
                GALogger.E(e.ToString());
            }
        }
Esempio n. 29
0
#pragma warning disable 0162
        private static void EnsurePersistedStates()
        {
            if (GAStore.InMemory)
            {
#if UNITY
                GALogger.D("retrieving persisted states from local PlayerPrefs");

                GAState instance = GAState.Instance;

                instance.DefaultUserId = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, Guid.NewGuid().ToString());
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, "0"), out tmp);
                    SessionNum = tmp;
                }
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + TransactionNumKey, "0"), out tmp);
                    TransactionNum = tmp;
                }
                if (!string.IsNullOrEmpty(instance.FacebookId))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + FacebookIdKey, instance.FacebookId);
                }
                else
                {
                    instance.FacebookId = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + FacebookIdKey, "");
                }
                if (!string.IsNullOrEmpty(instance.Gender))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + GenderKey, instance.Gender);
                }
                else
                {
                    instance.Gender = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + GenderKey, "");
                }
                if (instance.BirthYear != 0)
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + BirthYearKey, instance.BirthYear.ToString());
                }
                else
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + BirthYearKey, "0"), out tmp);
                    instance.BirthYear = tmp;
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension01Key, "");
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension02Key, "");
                }
                if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension03Key, "");
                }

                string sdkConfigCachedString = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SdkConfigCachedKey, "");
                if (!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;
                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch (Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if (sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }
#else
                GALogger.W("EnsurePersistedStates: No implementation yet for InMemory=true");
#endif
            }
            else
            {
                // get and extract stored states
                JSONObject state_dict       = new JSONObject();
                JSONArray  results_ga_state = GAStore.ExecuteQuerySync("SELECT * FROM ga_state;");

                if (results_ga_state != null && results_ga_state.Count != 0)
                {
                    for (int i = 0; i < results_ga_state.Count; ++i)
                    {
                        JSONNode result = results_ga_state[i];
                        state_dict.Add(result["key"], result["value"]);
                    }
                }

                // insert into GAState instance
                GAState instance = GAState.Instance;

                instance.DefaultUserId = state_dict[DefaultUserIdKey] != null ? state_dict[DefaultUserIdKey].Value : Guid.NewGuid().ToString();

                SessionNum = state_dict[SessionNumKey] != null ? state_dict[SessionNumKey].AsInt : 0;

                TransactionNum = state_dict[TransactionNumKey] != null ? state_dict[TransactionNumKey].AsInt : 0;

                // restore cross session user values
                if (!string.IsNullOrEmpty(instance.FacebookId))
                {
                    GAStore.SetState(FacebookIdKey, instance.FacebookId);
                }
                else
                {
                    instance.FacebookId = state_dict[FacebookIdKey] != null ? state_dict[FacebookIdKey].Value : "";
                    if (!string.IsNullOrEmpty(instance.FacebookId))
                    {
                        GALogger.D("facebookid found in DB: " + instance.FacebookId);
                    }
                }

                if (!string.IsNullOrEmpty(instance.Gender))
                {
                    GAStore.SetState(GenderKey, instance.Gender);
                }
                else
                {
                    instance.Gender = state_dict[GenderKey] != null ? state_dict[GenderKey].Value : "";
                    if (!string.IsNullOrEmpty(instance.Gender))
                    {
                        GALogger.D("gender found in DB: " + instance.Gender);
                    }
                }

                if (instance.BirthYear != 0)
                {
                    GAStore.SetState(BirthYearKey, instance.BirthYear.ToString());
                }
                else
                {
                    instance.BirthYear = state_dict[BirthYearKey] != null ? state_dict[BirthYearKey].AsInt : 0;
                    if (instance.BirthYear != 0)
                    {
                        GALogger.D("birthYear found in DB: " + instance.BirthYear);
                    }
                }

                // restore dimension settings
                if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    GAStore.SetState(Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = state_dict[Dimension01Key] != null ? state_dict[Dimension01Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension01))
                    {
                        GALogger.D("Dimension01 found in cache: " + CurrentCustomDimension01);
                    }
                }

                if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    GAStore.SetState(Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = state_dict[Dimension02Key] != null ? state_dict[Dimension02Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension02))
                    {
                        GALogger.D("Dimension02 found in cache: " + CurrentCustomDimension02);
                    }
                }

                if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    GAStore.SetState(Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = state_dict[Dimension03Key] != null ? state_dict[Dimension03Key].Value : "";
                    if (!string.IsNullOrEmpty(CurrentCustomDimension03))
                    {
                        GALogger.D("Dimension03 found in cache: " + CurrentCustomDimension03);
                    }
                }

                // get cached init call values
                string sdkConfigCachedString = state_dict[SdkConfigCachedKey] != null ? state_dict[SdkConfigCachedKey].Value : "";
                if (!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;

                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch (Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if (sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }

                JSONArray results_ga_progression = GAStore.ExecuteQuerySync("SELECT * FROM ga_progression;");

                if (results_ga_progression != null && results_ga_progression.Count != 0)
                {
                    for (int i = 0; i < results_ga_progression.Count; ++i)
                    {
                        JSONNode result = results_ga_progression[i];
                        if (result != null && result.Count != 0)
                        {
                            instance.progressionTries[result["progression"].Value] = result["tries"].AsInt;
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        public static JSONObject ValidateAndCleanCustomFields(IDictionary <string, object> fields)
        {
            JSONObject result = new JSONObject();

            if (fields != null)
            {
                int count = 0;

                foreach (KeyValuePair <string, object> entry in fields)
                {
                    if (entry.Key == null || entry.Value == null)
                    {
                        GALogger.W("ValidateAndCleanCustomFields: entry with key=" + entry.Key + ", value=" + entry.Value + " has been omitted because its key or value is null");
                    }
                    else if (count < MaxCustomFieldsCount)
                    {
                        if (GAUtilities.StringMatch(entry.Key, "^[a-zA-Z0-9_]{1," + MaxCustomFieldsKeyLength + "}$"))
                        {
                            if (entry.Value is string || entry.Value is char)
                            {
                                string value = Convert.ToString(entry.Value);

                                if (value.Length <= MaxCustomFieldsValueStringLength && value.Length > 0)
                                {
                                    result[entry.Key] = value;
                                    ++count;
                                }
                                else
                                {
                                    GALogger.W("ValidateAndCleanCustomFields: entry with key=" + entry.Key + ", value=" + entry.Value + " has been omitted because its value is an empty string or exceeds the max number of characters (" + MaxCustomFieldsValueStringLength + ")");
                                }
                            }
                            else if (entry.Value is double)
                            {
                                result[entry.Key] = new JSONNumber((double)entry.Value);
                                ++count;
                            }
                            else if (entry.Value is float)
                            {
                                result[entry.Key] = new JSONNumber((float)entry.Value);
                                ++count;
                            }
                            else if (entry.Value is long || entry.Value is ulong)
                            {
                                result[entry.Key] = new JSONNumber(Convert.ToInt64(entry.Value));
                                ++count;
                            }
                            else if (entry.Value is int ||
                                     entry.Value is byte ||
                                     entry.Value is sbyte ||
                                     entry.Value is byte ||
                                     entry.Value is uint ||
                                     entry.Value is short ||
                                     entry.Value is ushort)
                            {
                                result[entry.Key] = new JSONNumber(Convert.ToInt32(entry.Value));
                                ++count;
                            }
                            else
                            {
                                GALogger.W("ValidateAndCleanCustomFields: entry with key=" + entry.Key + ", value=" + entry.Value + " has been omitted because its value is not a string or number");
                            }
                        }
                        else
                        {
                            GALogger.W("ValidateAndCleanCustomFields: entry with key=" + entry.Key + ", value=" + entry.Value + " has been omitted because its key illegal characters, an empty or exceeds the max number of characters (" + MaxCustomFieldsKeyLength + ")");
                        }
                    }
                    else
                    {
                        GALogger.W("ValidateAndCleanCustomFields: entry with key=" + entry.Key + ", value=" + entry.Value + " has been omitted because it exceeds the max number of custom fields (" + MaxCustomFieldsCount + ")");
                    }
                }
            }

            return(result);
        }