private static void UpdateSessionTime()
 {
     if (GAState.SessionIsStarted())
     {
         JSONClass ev           = GAState.GetEventAnnotations();
         string    jsonDefaults = ev.SaveToBase64();
         string    sql          = "INSERT OR REPLACE INTO ga_session(session_id, timestamp, event) VALUES($session_id, $timestamp, $event);";
         Dictionary <string, object> parameters = new Dictionary <string, object>();
         parameters.Add("$session_id", ev["session_id"].Value);
         parameters.Add("$timestamp", GAState.SessionStart);
         parameters.Add("$event", jsonDefaults);
         GAStore.ExecuteQuerySync(sql, parameters);
     }
 }
    /// <summary>
    /// Gets the JSON key value pair
    /// </summary>
    /// <returns>The JSON key value.</returns>
    /// <param name="name">Name.</param>
    /// <param name="aValue">A value.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public static string getJSONKeyValue <T> (T aValue, string name = "")
    {
        JSONBinaryTag tag = JSONPersistor.GetJSONBinaryTag <T> (aValue);

        Debug.Log("tag: " + tag);

        if (aValue.GetType().IsPrimitive)
        {
            //val.GetType().ToString()
            if (string.IsNullOrEmpty(name))
            {
                name = "someValue";
            }

            return("\"" + tag + "_" + name + "\"" + separator + "\"" + aValue.ToString() + "\"");

/*				} else if (tag == JSONBinaryTag.Array) {
 *
 *                                              string arrayStr = name + " [ ";
 *                                              JSONArray arr = (JSONArray)aValue;
 *
 *                                              if (arr.Count > 0) {
 *                                                              int i = 0;
 *                                                              foreach (JSONNode node in arr.Childs) {
 *                                                                              if (i > 0) {
 *                                                                                              arrayStr += " , ";
 *                                                                              }
 *                                                                              arrayStr += node.Value;
 *                                                                              i++;
 *                                                              }
 *
 *                                              }
 *                                              arrayStr += " ]";
 *
 *                                              return arrayStr;*/
        }
        else if (tag == JSONBinaryTag.Class)
        {
            JSONClass jClass = aValue as JSONClass;
            return(jClass.SaveToBase64());
            //} else if (aValue.GetType ().IsClass) {
        }

        return("");
    }
        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());
            }
        }
Exemple #4
0
        public static void StartNewSession(EGAHTTPApiResponse initResponse, JSONClass 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 JSONData(timeOffsetSeconds));

                // insert new config in sql lite cross session storage
                GAStore.SetState(SdkConfigCachedKey, initResponseDict.SaveToBase64());

                // 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;
            }

            // 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;

            // 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();
        }