Ejemplo n.º 1
0
        private void loadCachedCredentials()
        {
            String AK  = _persistentStore.Get(AK_KEY);
            String SK  = _persistentStore.Get(SK_KEY);
            String ST  = _persistentStore.Get(ST_KEY);
            String EXP = _persistentStore.Get(EXP_KEY);
            string IP  = _persistentStore.Get(IP_KEY);

            long ticks = EXP != null?long.Parse(EXP) : 0;

            // make sure we have valid data in prefs
            if (AK == null || SK == null ||
                ST == null || IP == null)
            {
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "No valid credentials found in LocalStorage");
                _currentState = null;
                return;
            }

            _currentState = new CredentialsRefreshState
            {
                Credentials = new ImmutableCredentials(AK, SK, ST),
                Expiration  = new DateTime(ticks)
            };
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "Loaded credentials from LocalStorage");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Increments the delivery attempt.
        /// </summary>
        /// <returns>true</returns>
        /// <c>false</c>
        /// <param name="rowIds">Row identifiers.</param>
        public bool IncrementDeliveryAttempt(List <string> rowIds)
        {
            bool success = false;

            lock (_lock)
            {
                SQLiteStatement stmt = null;
                try
                {
#if SQL_DEBUG
                    DateTime _dbExecutionStartTime = DateTime.Now;
#endif
                    string ids   = "'" + String.Join("', '", rowIds.ToArray()) + "'";
                    string query = String.Format("UPDATE " + TABLE_NAME + " SET " + EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME + "= " + EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME + "+1 WHERE " + EVENT_ID_COLUMN_NAME + " IN ({0})", ids);
                    stmt = db.Prepare(query);
                    stmt.Step();
                    success = true;
#if SQL_DEBUG
                    DateTime _dbExecutionEndTime = DateTime.Now;
                    double   totalSeconds        = _dbExecutionEndTime.Subtract(_dbExecutionStartTime).TotalSeconds;
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteEventStore", "Increment Operation completed on local store in " + totalSeconds + " seconds");
#endif
                }
                finally
                {
                    if (stmt != null)
                    {
                        stmt.FinalizeStm();
                    }
                }
            }
            return(success);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="region">Region to use when accessing Amazon Cognito and AWS Security Token Service.</param>
        public CachingCognitoAWSCredentials(
            string accountId, string identityPoolId,
            string unAuthRoleArn, string authRoleArn,
            RegionEndpoint region)
            : this(
                unAuthRoleArn, authRoleArn,
                new AmazonCognitoIdentityProvider(accountId, identityPoolId, new AnonymousAWSCredentials(), region),
                new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials(), region))
        {
            if (string.IsNullOrEmpty(accountId))
            {
                throw new ArgumentNullException("accountId cannot be null");
            }
            if (string.IsNullOrEmpty(identityPoolId))
            {
                throw new ArgumentNullException("identityPoolId cannot be null");
            }
            if (string.IsNullOrEmpty(unAuthRoleArn) && string.IsNullOrEmpty(authRoleArn))
            {
                throw new ArgumentNullException("Both unAuthRoleArn and authRoleArn cannot be null");
            }
#if UNITY_WEBPLAYER
            _persistentStore = new InMemoryKVStore();
#else
            _persistentStore = new SQLiteKVStore();
#endif

            string IP = _persistentStore.Get(IP_KEY);

            if (!string.IsNullOrEmpty(IP) && 0 == IP.CompareTo(identityPoolId))
            {
                IdentityProvider.UpdateIdentity(_persistentStore.Get(ID_KEY));

                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "Loaded Cached IdentityID from LocalStorage");
                loadCachedCredentials();
            }
            else if (!string.IsNullOrEmpty(IP))
            {
                // identity pool id is different from whats caching
                Clear();
            }

            IdentityProvider.IdentityChangedEvent += delegate(object sender, IdentityChangedArgs e)
            {
                if (!string.IsNullOrEmpty(e.OldIdentityId))
                {
                    this.Clear();
                }
                if (string.IsNullOrEmpty(_persistentStore.Get(IP_KEY)))
                {
                    // identity pool id is not cached
                    _persistentStore.Put(IP_KEY, this.IdentityProvider.IdentityPoolId);
                }
                // caching identity whenever new identity is found
                _persistentStore.Put(ID_KEY, e.NewIdentityId);
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "Saved identityID to LocalStorage");
            };
        }
Ejemplo n.º 4
0
 internal void ClearCredentials()
 {
     _sessionCredentials = null;
     _persistentStore.Clear(namespacedKey(AK_KEY));
     _persistentStore.Clear(namespacedKey(SK_KEY));
     _persistentStore.Clear(namespacedKey(ST_KEY));
     _persistentStore.Clear(namespacedKey(EXP_KEY));
     AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoAWSCredentials", "Clear Credentials");
 }
        public void IdentityChanged(object sender, EventArgs e)
        {
            var identityChangedEvent = e as IdentityChangedArgs;

            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Info, "DefaultCognitoSyncManager", "identity change detected");

            local.ChangeIdentityId(identityChangedEvent.OldIdentityId == null ? DatasetUtils.UNKNOWN_IDENTITY_ID
                                   : identityChangedEvent.OldIdentityId, identityChangedEvent.NewIdentityId);
        }
Ejemplo n.º 6
0
        public void Debug(String msg)
        {
#if UNITY_EDITOR || UNITY_IPHONE || UNITY_ANDROID
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, tag, msg);
#elif __ANDROID__
            Android.Util.Log.Debug(tag, msg);
#elif __IOS__
            System.Console.WriteLine(msg);
#endif
        }
Ejemplo n.º 7
0
 internal override void Clear()
 {
     base.Clear();
     _persistentStore.Clear(IP_KEY);
     _persistentStore.Clear(ID_KEY);
     _persistentStore.Clear(AK_KEY);
     _persistentStore.Clear(SK_KEY);
     _persistentStore.Clear(ST_KEY);
     _persistentStore.Clear(EXP_KEY);
     AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "Clear Cached Credentials");
 }
Ejemplo n.º 8
0
 private void saveCredentials()
 {
     if (_sessionCredentials != null)
     {
         _persistentStore.Put(namespacedKey(AK_KEY), _sessionCredentials.Credentials.AccessKey);
         _persistentStore.Put(namespacedKey(SK_KEY), _sessionCredentials.Credentials.SecretKey);
         _persistentStore.Put(namespacedKey(ST_KEY), _sessionCredentials.Credentials.Token);
         _persistentStore.Put(namespacedKey(EXP_KEY), _sessionCredentials.Expiration.Ticks.ToString());
         _persistentStore.Put(namespacedKey(ID_KEY), IdentityProvider.GetCurrentIdentityId());
         AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoAWSCredentials", "Saved credentials to LocalStorage");
     }
 }
Ejemplo n.º 9
0
 private void saveCredentials()
 {
     if (_currentState != null)
     {
         _persistentStore.Put(AK_KEY, _currentState.Credentials.AccessKey);
         _persistentStore.Put(SK_KEY, _currentState.Credentials.SecretKey);
         _persistentStore.Put(ST_KEY, _currentState.Credentials.Token);
         _persistentStore.Put(EXP_KEY, _currentState.Expiration.Ticks.ToString());
         _persistentStore.Put(IP_KEY, IdentityProvider.IdentityPoolId);
         _persistentStore.Put(ID_KEY, IdentityProvider.GetCurrentIdentityId());
         AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CachingCognitoAWSCredentials", "Saved credentials to LocalStorage");
     }
 }
        private void ProcessS3PostResponse(object state)
        {
            AsyncResult asyncResult = null;

            try
            {
                asyncResult = state as AsyncResult;
                asyncResult.ServiceResult.HttpResponseData = asyncResult.ResponseData;

                S3PostUploadResponse response = new S3PostUploadResponse();

                WWWResponseData responseData = asyncResult.ResponseData;

                if (!String.IsNullOrEmpty(responseData.Error) || !String.IsNullOrEmpty(System.Text.Encoding.UTF8.GetString(responseData.GetBytes())))
                {
                    AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Critical, "S3", responseData.Error);
                    foreach (string key in responseData.GetHeaderNames())
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "S3", key + " : " + responseData.GetHeaderValue(key));
                    }

                    if (asyncResult.Exception == null)
                    {
                        asyncResult.Exception = new AmazonServiceException("Bad Request");
                    }

                    asyncResult.IsCompleted            = true;
                    response.StatusCode                = HttpStatusCode.BadRequest;
                    asyncResult.ServiceResult.Response = response;
                    AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Warnings, "S3", "RetriesAttempt exceeded");
                    asyncResult.HandleException(asyncResult.Exception);

                    return;
                }
                else
                {
                    asyncResult.IsCompleted            = true;
                    response.StatusCode                = HttpStatusCode.NoContent;
                    asyncResult.ServiceResult.Response = response;
                    asyncResult.InvokeCallback();
                    return;
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                asyncResult.HandleException(e);
                return;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get All event from the Event Store
        /// </summary>
        /// <param name="appid">Appid.</param>
        /// <returns>All the events as a List of <see cref="ThirdParty.Json.LitJson.JsonData"/>.</returns>
        public List <JsonData> GetAllEvents(string appId)
        {
            List <JsonData> eventList = new List <JsonData>();

            lock (_lock)
            {
                SQLiteStatement stmt = null;
                try
                {
#if SQL_DEBUG
                    DateTime _dbExecutionStartTime = DateTime.Now;
#endif
                    string query = "SELECT * FROM " + TABLE_NAME + " WHERE " + MA_APP_ID_COLUMN_NAME + " = ?  ORDER BY " + EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME + ",ROWID LIMIT " + MAX_ALLOWED_SELECTS;
                    stmt = db.Prepare(query);
                    stmt.BindText(1, appId);
                    while (stmt.Read())
                    {
                        JsonData data = new JsonData();
                        data["id"]    = stmt.Fields[EVENT_ID_COLUMN_NAME].TEXT;
                        data["event"] = stmt.Fields[EVENT_COLUMN_NAME.ToLower()].TEXT;
                        data["appId"] = stmt.Fields[MA_APP_ID_COLUMN_NAME].TEXT;
                        eventList.Add(data);
                    }
#if SQL_DEBUG
                    DateTime _dbExecutionEndTime = DateTime.Now;
                    double   totalSeconds        = _dbExecutionEndTime.Subtract(_dbExecutionStartTime).TotalSeconds;
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteEventStore", "Select All Operation completed from local store in " + totalSeconds + " seconds");
#endif
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Exception happens when getting events.");
                }
                finally
                {
                    if (stmt != null)
                    {
                        stmt.FinalizeStm();
                    }
                }
            }

            return(eventList);
        }
        private IEnumerator FireNetworkRequestCoroutine(AsyncResult result)
        {
            // this check is probably not needed since Dequeue operation is supposed to invoked only from the Unity MainThread
            if (result != null)
            {
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, result.Request.ServiceName,
                                  "Making WWW request");

                // making WWW request call
                yield return(result.RequestData.FireRequest());

                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, result.Request.ServiceName,
                                  "Completing WWW request");
                result.ResponseData = result.RequestData.GetResponseData();
                // switching to background thread
                ThreadPool.QueueUserWorkItem(result.WaitCallback, (object)result);
            }
            RequestPending--;
            yield break;
        }
Ejemplo n.º 13
0
        protected bool DefaultConflictResolution(List <SyncConflict> conflicts)
        {
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Info, this.GetType().ToString(), "Last writer wins conflict resolution for dataset ");

            List <Record> resolvedRecords = new List <Record>();

            foreach (SyncConflict conflict in conflicts)
            {
                if (conflict.RemoteRecord == null || conflict.LocalRecord.LastModifiedDate.Value.CompareTo(conflict.RemoteRecord.LastModifiedDate) > 0)
                {
                    resolvedRecords.Add(conflict.ResolveWithLocalRecord());
                }
                else
                {
                    resolvedRecords.Add(conflict.ResolveWithRemoteRecord());
                }
            }
            this.Resolve(resolvedRecords);
            return(true);
        }
Ejemplo n.º 14
0
        public override void Synchronize()
        {
            ThreadPool.QueueUserWorkItem(delegate(object notUsed)
            {
                if (!IsNetworkAvailable())
                {
                    FireSyncFailureEvent(new NetworkException("Network connectivity unavailable."));

                    return;
                }
                List <string> mergedDatasets = GetLocalMergedDatasets();
                if (mergedDatasets.Count > 0)
                {
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "DefaultDataset", "detected merge datasets " + _datasetName);

                    if (this.OnDatasetMerged != null)
                    {
                        this.OnDatasetMerged(this, mergedDatasets);
                    }
                }

                if (_cognitoCredentials.IdentityProvider.GetCurrentIdentityId() != null)
                {
                    SynchronizeInternalAsync();
                }
                else
                {
                    _cognitoCredentials.IdentityProvider.RefreshAsync(delegate(AmazonServiceResult voidResult)
                    {
                        if (voidResult.Exception != null)
                        {
                            FireSyncFailureEvent(voidResult.Exception);
                            return;
                        }
                        SynchronizeInternalAsync();
                    }, null);
                }
            });
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Constructs a new CognitoAWSCredentials instance, which will use the
        /// specified Amazon Cognito identity pool to make a requests to the
        /// AWS Security Token Service (STS) to request short lived session credentials.
        /// </summary>
        /// <param name="accountId">The AWS accountId for the account with Amazon Cognito</param>
        /// <param name="identityPoolId">The Amazon Cogntio identity pool to use</param>
        /// <param name="unAuthRoleArn">The ARN of the IAM Role that will be assumed when unauthenticated</param>
        /// <param name="authRoleArn">The ARN of the IAM Role that will be assumed when authenticated</param>
        /// <param name="cibClient">Preconfigured Cognito Identity client to make requests with</param>
        /// <param name="stsClient">Preconfigured STS client to make requests with</param>
        public CognitoAWSCredentials(string unAuthRoleArn, string authRoleArn,
                                     AbstractCognitoIdentityProvider idClient, IAmazonSecurityTokenService stsClient)
        {
            if (idClient == null)
            {
                throw new ArgumentNullException("idClient");
            }

            UnAuthRoleArn    = unAuthRoleArn;
            AuthRoleArn      = authRoleArn;
            IdentityProvider = idClient;
            sts = stsClient;

                        #if UNITY_WEBPLAYER
            _persistentStore = new InMemoryKVStore();
                        #else
            _persistentStore = new SQLiteKVStore();
                        #endif

            //Load cached credentials
            string cachedIdentity = _persistentStore.Get(namespacedKey(ID_KEY));
            if (string.IsNullOrEmpty(cachedIdentity))
            {
                //Try to recover unamespaced identities stored by old versions of the SDK
                cachedIdentity = _persistentStore.Get(ID_KEY);
            }
            if (!string.IsNullOrEmpty(cachedIdentity))
            {
                IdentityProvider.UpdateIdentity(cachedIdentity);
                loadCachedCredentials();
            }

            //Register Identity Changed Listener to update the cache
            IdentityProvider.IdentityChangedEvent += delegate(object sender, IdentityChangedArgs e)
            {
                saveCredentials();
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoAWSCredentials", "Saved identityID to LocalStorage");
            };
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Init this instance. This methods needs to be called from the main thread, Otherwise the values may not initialize correctly
        /// </summary>
        public void Init()
        {
            PersistentDataPath = Application.persistentDataPath;

#if UNITY_ANDROID && !UNITY_EDITOR
            //device related information

            AndroidJavaClass buildJavaClass   = new AndroidJavaClass("android.os.Build");
            AndroidJavaClass versionJavaClass = new AndroidJavaClass("android.os.Build$VERSION");

            PlatformVersion = versionJavaClass.GetStatic <string>("RELEASE");
            Model           = buildJavaClass.GetStatic <string>("MODEL");
            Make            = buildJavaClass.GetStatic <string>("MANUFACTURER");

            AndroidJavaClass  localeClass  = new AndroidJavaClass("java.util.Locale");
            AndroidJavaObject localeObject = localeClass.CallStatic <AndroidJavaObject>("getDefault");
            Locale = localeObject.Call <string>("toString");

            Platform = Application.platform.ToString();

            //application related information
            AndroidJavaClass  unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentContext   = unityPlayerClass.GetStatic <AndroidJavaObject>("currentActivity");

            PackageName = currentContext.Call <string>("getPackageName");

            AndroidJavaObject packageManager = currentContext.Call <AndroidJavaObject>("getPackageManager");
            AndroidJavaObject packageinfo    = packageManager.Call <AndroidJavaObject>("getPackageInfo", PackageName, 0);

            AndroidJavaObject applicationInfo = packageManager.Call <AndroidJavaObject>("getApplicationInfo", PackageName, 0);

            VersionCode = System.Convert.ToString(packageinfo.Get <int>("versionCode"));
            VersionName = packageinfo.Get <string>("versionName");
            Title       = packageManager.Call <string>("getApplicationLabel", applicationInfo);
#elif UNITY_IOS && !UNITY_EDITOR
            //platform related information
            Platform        = Application.platform.ToString();
            Locale          = locale();
            PlatformVersion = SystemInfo.operatingSystem;
            Make            = "apple";
            if (iPhone.generation.ToString().StartsWith("iPhone"))
            {
                Model = "iPhone";
            }
            else if (iPhone.generation.ToString().StartsWith("iPad"))
            {
                Model = "iPad";
            }
            else
            {
                Model = "iPod";
            }

            //Application related information
            Title       = title();
            VersionCode = versionCode();
            VersionName = versionName();
            PackageName = packageName();
#else
            Platform = Application.platform.ToString();
            if (Thread.CurrentThread.CurrentCulture != CultureInfo.InvariantCulture)
            {
                Locale = Thread.CurrentThread.CurrentCulture.Name;
            }
            else
            {
                Locale = Application.systemLanguage.ToString();
            }
            PlatformVersion = SystemInfo.operatingSystem;
            Model           = SystemInfo.deviceModel;
            Make            = "";
#endif
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "PlatformInfo", "make = " + Make);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "PlatformInfo", "model = " + Model);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "PlatformInfo", "platform version = " + PlatformVersion);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "PlatformInfo", "locale = " + Locale);

            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "ApplicationInfo", "Title = " + Title);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "ApplicationInfo", "Version Code = " + VersionCode);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "ApplicationInfo", "Version Name = " + VersionName);
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "ApplicationInfo", "Package Name = " + PackageName);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Add an event to the store.
        /// </summary>
        /// <returns><c>true</c>, if event was put, <c>false</c> otherwise.</returns>
        public bool PutEvent(string eventString, string appId)
        {
            bool success             = false;
            bool proceedToInsert     = false;
            long currentDatabaseSize = GetDatabaseSize();

            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException("AppId");
            }

            if (currentDatabaseSize >= _maxDbSize)
            {
                proceedToInsert = false;

                InvalidOperationException e = new InvalidOperationException();
                _logger.Error(e, "The database size has exceeded the threshold limit. Unable to insert any new events");
            }
            else if (currentDatabaseSize / _maxDbSize >= _dbWarningThreshold)
            {
                proceedToInsert = true;
                _logger.InfoFormat("The database size is almost full");
            }
            else
            {
                proceedToInsert = true;
            }


            //keep the lock as short as possible
            if (proceedToInsert)
            {
                lock (_lock)
                {
                    SQLiteStatement stmt = null;
                    try
                    {
#if SQL_DEBUG
                        DateTime _dbExecutionStartTime = DateTime.Now;
#endif
                        string query = "INSERT INTO " + TABLE_NAME + " (" + EVENT_COLUMN_NAME + "," + EVENT_ID_COLUMN_NAME + "," + MA_APP_ID_COLUMN_NAME + ") values(?,?,?)";
                        stmt = db.Prepare(query);
                        stmt.BindText(1, eventString);
                        stmt.BindText(2, Guid.NewGuid().ToString());
                        stmt.BindText(3, appId);
                        stmt.Step();
                        success = true;
#if SQL_DEBUG
                        DateTime _dbExecutionEndTime = DateTime.Now;
                        double   totalSeconds        = _dbExecutionEndTime.Subtract(_dbExecutionStartTime).TotalSeconds;
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteEventStore", "Put Operation completed on local store in " + totalSeconds + " seconds");
#endif
                    }
                    finally
                    {
                        if (stmt != null)
                        {
                            stmt.FinalizeStm();
                        }
                    }
                }
            }

            return(success);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Log the GameCircle message.
 /// </summary>
 /// <param name='message'>
 /// Message.
 /// </param>
 public static void Log(string message)
 {
     AmazonLogging.Log(errorLevel, serviceName, message);
 }
        /// <summary>
        /// Invoked as a callback from the AmazonMainThreadDispatcher
        /// Processes the http response
        /// </summary>
        /// <param name="state">State is expected to be AsyncResult</param>
        private void ProcessHttpResponse(object state)
        {
            AsyncResult asyncResult = null;

            try
            {
                asyncResult = state as AsyncResult;
                AmazonWebServiceResponse response = null;
                UnmarshallerContext      context  = null;

                var responseData = asyncResult.ResponseData;

                if (!String.IsNullOrEmpty(responseData.Error))
                {
                    AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Critical,
                                           asyncResult.Request.ServiceName, responseData.Error);

                    if (HandleWWWErrorResponse(asyncResult))
                    {
                        if (++asyncResult.RetriesAttempt >= 3)
                        {
                            if (asyncResult.Exception == null)
                            {
                                asyncResult.Exception = new AmazonServiceException("Maximum retries attempts completed");
                            }
                            // maxretries
                            asyncResult.IsCompleted = true;
                            AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors,
                                                       asyncResult.Request.ServiceName, asyncResult.Exception);
                            asyncResult.HandleException(asyncResult.Exception);
                            return;
                        }
                        else
                        {
                            // retry here
                            InvokeHelper(asyncResult);
                            return;
                        }
                    }
                    else
                    {
                        // non-retriable error
                        asyncResult.IsCompleted = true;
                        asyncResult.HandleException(asyncResult.Exception);
                        return;
                    }
                }
                else
                {
                    using (asyncResult.Metrics.StartEvent(Metric.ResponseProcessingTime))
                    {
                        var unmarshaller = asyncResult.Unmarshaller;
                        LogResponse(asyncResult.Metrics, asyncResult.Request, HttpStatusCode.Accepted);

                        context = unmarshaller.CreateContext(responseData,
                                                             this.SupportResponseLogging &&
                                                             (Config.LogResponse || Config.ReadEntireResponse),
                                                             responseData.OpenResponse(),
                                                             asyncResult.Metrics);
                        try
                        {
                            using (asyncResult.Metrics.StartEvent(Metric.ResponseUnmarshallTime))
                            {
                                response = unmarshaller.Unmarshall(context);
                                if (responseData.IsHeaderPresent("STATUS"))
                                {
                                    response.HttpStatusCode = responseData.StatusCode;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            //unmarshalling exception
                            asyncResult.IsCompleted = true;
                            asyncResult.HandleException(e);
                            return;
                        }
                        context.ValidateCRC32IfAvailable();
                        if (responseData.IsHeaderPresent(HeaderKeys.ContentLengthHeader.ToUpper()))
                        {
                            response.ContentLength = Convert.ToInt32(responseData.GetHeaderValue(HeaderKeys.ContentLengthHeader.ToUpper()));
                        }
                        else
                        {
                            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Warnings, asyncResult.Request.ServiceName, "cannot find CONTENT-LENGTH header");
                        }

                        asyncResult.ServiceResult.Response = response;

                        if (response.ResponseMetadata != null)
                        {
                            asyncResult.Metrics.AddProperty(Metric.AWSRequestID, response.ResponseMetadata.RequestId);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, asyncResult.Request.ServiceName, e);
                asyncResult.HandleException(e);
            }

            asyncResult.IsCompleted = true;
            asyncResult.InvokeCallback();
            return;
        }
 public override void WipeData()
 {
     local.WipeData();
     AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Info, "DefaultCognitoSyncManager", "All data has been wiped");
 }
        private void ProcessS3PostRequest(AsyncResult asyncResult, PostObjectRequest request)
        {
            try
            {
                WWWRequestData requestData = new WWWRequestData();
                string         subdomain   = request.Region.Equals(RegionEndpoint.USEast1) ? "s3" : "s3-" + request.Region.SystemName;

                if (request.Bucket.IndexOf('.') > -1)
                {
                    requestData.Url = string.Format(CultureInfo.InvariantCulture, "http://{0}.amazonaws.com/{1}/", subdomain, request.Bucket);
                }
                else
                {
                    requestData.Url = string.Format(CultureInfo.InvariantCulture, "http://{0}.{1}.amazonaws.com", request.Bucket, subdomain);
                }


                // prepare WWW
                var boundary = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Replace('=', 'z');
                requestData.Headers.Add(HeaderKeys.ContentTypeHeader, string.Format(CultureInfo.InvariantCulture, "multipart/form-data; boundary={0}", boundary));
#if !UNITY_WEBPLAYER
                requestData.Headers.Add(HeaderKeys.UserAgentHeader, UNITY_USER_AGENT);
#endif

                // append upload data

                using (var reqStream = new MemoryStream())
                {
                    request.WriteFormData(boundary, reqStream);

                    byte[] boundaryBytes = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "--{0}\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n", boundary));

                    reqStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                    using (var inputStream = null == request.Path ? request.InputStream : File.OpenRead(request.Path))
                    {
                        byte[] buf = new byte[1024];
                        int    bytesRead;
                        while ((bytesRead = inputStream.Read(buf, 0, 1024)) > 0)
                        {
                            reqStream.Write(buf, 0, bytesRead);
                        }
                    }

                    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "\r\n--{0}--", boundary));

                    reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "S3", requestData.Url);

                    requestData.Data = reqStream.ToArray();
                }
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "S3", Encoding.Default.GetString(requestData.Data));

                asyncResult.RequestData  = requestData;
                asyncResult.WaitCallback = ProcessS3PostResponse;

                // switching to main thread
                AmazonMainThreadDispatcher.QueueAWSRequest(asyncResult);
            }
            catch (Exception e)
            {
                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "S3", e.Message);
                asyncResult.IsCompleted = true;
                asyncResult.HandleException(e);
                return;
            }
        }
Ejemplo n.º 22
0
        private void RunSyncOperationAsync(int retry, Action <RunSyncOperationResponse> callback)
        {
            if (retry < 0)
            {
                callback(new RunSyncOperationResponse(false, null));
                return;
            }

            long lastSyncCount = _local.GetLastSyncCount(GetIdentityId(), _datasetName);

            // if dataset is deleted locally, push it to remote
            if (lastSyncCount == -1)
            {
#if DELETE_METHOD_SUPPORT
                _remote.DeleteDatasetAsync(_datasetName, delegate(AmazonCognitoResult result)
                {
                    if (result.Exception != null)
                    {
                        var e = result.Exception as DataStorageException;
                        AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "CognitoSyncManager", "OnSyncFailure" + e.Message);
                        this.FireSyncFailureEvent(e);
                        callback(new RunSyncOperationResponse(false, null));
                        return;
                    }

                    _local.PurgeDataset(GetIdentityId(), _datasetName);
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncSuccess: dataset delete is pushed to remote");
                    this.FireSyncSuccessEvent(new List <Record>());
                    callback(new RunSyncOperationResponse(true, null));
                    return;
                }, null);
#endif
                // invalid scenario
                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Critical, "CognitoSyncManager", "OnSyncFailure: DeleteDataset is an invalid operation");
                FireSyncFailureEvent(new DataStorageException("DeleteDataset is an invalid operation"));
                callback(new RunSyncOperationResponse(false, null));
                return;
            }

            // get latest modified records from remote
            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "get latest modified records since " + lastSyncCount);

            _remote.ListUpdatesAsync(_datasetName, lastSyncCount, delegate(AmazonCognitoResult listUpdatesResult)
            {
                RemoteDataStorage.DatasetUpdates datasetUpdates = null;
                if (listUpdatesResult == null || listUpdatesResult.Exception != null)
                {
                    var e = listUpdatesResult.Exception as DataStorageException;
                    AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", e);
                    FireSyncFailureEvent(e);
                    callback(new RunSyncOperationResponse(false, listUpdatesResult.Exception));
                    return;
                }

                ListUpdatesResponse listUpdatesResponse = listUpdatesResult.Response as ListUpdatesResponse;
                datasetUpdates = listUpdatesResponse.DatasetUpdates;


                if (datasetUpdates.MergedDatasetNameList.Count != 0 && this.OnDatasetMerged != null)
                {
                    bool resume = this.OnDatasetMerged(this, datasetUpdates.MergedDatasetNameList);
                    if (resume)
                    {
                        this.RunSyncOperationAsync(--retry, callback);
                        return;
                    }
                    else
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncFailure: Manual cancel");
                        FireSyncFailureEvent(new DataStorageException("Manual cancel"));
                        callback(new RunSyncOperationResponse(false, null));
                        return;
                    }
                }


                // if the dataset doesn't exist or is deleted, trigger onDelete
                if (lastSyncCount != 0 && !datasetUpdates.Exists ||
                    datasetUpdates.Deleted && this.OnDatasetDeleted != null)
                {
                    bool resume = this.OnDatasetDeleted(this);
                    if (resume)
                    {
                        // remove both records and metadata
                        _local.DeleteDataset(GetIdentityId(), _datasetName);
                        _local.PurgeDataset(GetIdentityId(), _datasetName);
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncSuccess");
                        FireSyncSuccessEvent(new List <Record>());
                        callback(new RunSyncOperationResponse(true, null));
                        return;
                    }
                    else
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncFailure");
                        FireSyncFailureEvent(new DataStorageException("Manual cancel"));
                        callback(new RunSyncOperationResponse(false, null));
                        return;
                    }
                }


                List <Record> remoteRecords = datasetUpdates.Records;
                if (remoteRecords.Count != 0)
                {
                    // if conflict, prompt developer/user with callback
                    List <SyncConflict> conflicts = new List <SyncConflict>();
                    List <Record> conflictRecords = new List <Record>();
                    foreach (Record remoteRecord in remoteRecords)
                    {
                        Record localRecord = _local.GetRecord(GetIdentityId(),
                                                              _datasetName,
                                                              remoteRecord.Key);
                        // only when local is changed and its value is different
                        if (localRecord != null && localRecord.Modified &&
                            !StringUtils.Equals(localRecord.Value, remoteRecord.Value))
                        {
                            conflicts.Add(new SyncConflict(remoteRecord, localRecord));
                            conflictRecords.Add(remoteRecord);
                        }
                    }
                    // retaining only non-conflict records
                    remoteRecords.RemoveAll(t => conflictRecords.Contains(t));

                    if (conflicts.Count > 0)
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", String.Format("{0} records in conflict!", conflicts.Count));

                        bool syncConflictResult = false;
                        if (this.OnSyncConflict == null)
                        {
                            // delegate is not implemented so the conflict resolution is applied
                            syncConflictResult = this.DefaultConflictResolution(conflicts);
                        }
                        else
                        {
                            syncConflictResult = this.OnSyncConflict(this, conflicts);
                        }
                        if (!syncConflictResult)
                        {
                            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "User cancelled conflict resolution");
                            callback(new RunSyncOperationResponse(false, null));
                            return;
                        }
                    }

                    // save to local
                    if (remoteRecords.Count > 0)
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", String.Format("save {0} records to local", remoteRecords.Count));
                        _local.PutRecords(GetIdentityId(), _datasetName, remoteRecords);
                    }


                    // new last sync count
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", String.Format("updated sync count {0}", datasetUpdates.SyncCount));
                    _local.UpdateLastSyncCount(GetIdentityId(), _datasetName,
                                               datasetUpdates.SyncCount);
                }


                // push changes to remote
                List <Record> localChanges = this.GetModifiedRecords();
                if (localChanges.Count != 0)
                {
                    AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", String.Format("push {0} records to remote", localChanges.Count));

                    _remote.PutRecordsAsync(_datasetName, localChanges,
                                            datasetUpdates.SyncSessionToken, delegate(AmazonCognitoResult putRecordsResult)
                    {
                        if (putRecordsResult.Exception != null)
                        {
                            if (putRecordsResult.Exception.GetType() == typeof(DataConflictException))
                            {
                                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Warnings, "CognitoSyncManager", "Conflicts detected when pushing changes to remote: " + putRecordsResult.Exception.Message);
                                this.RunSyncOperationAsync(--retry, callback);
                                return;
                            }
                            else if (putRecordsResult.Exception.GetType() == typeof(DataStorageException))
                            {
                                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncFailure" + putRecordsResult.Exception.Message);
                                FireSyncFailureEvent(putRecordsResult.Exception);
                                callback(new RunSyncOperationResponse(false, null));
                                return;
                            }
                        }
                        PutRecordsResponse putRecordsResponse = putRecordsResult.Response as PutRecordsResponse;
                        List <Record> result = putRecordsResponse.UpdatedRecords;

                        // update local meta data
                        _local.PutRecords(GetIdentityId(), _datasetName, result);

                        // verify the server sync count is increased exactly by one, aka no
                        // other updates were made during this update.
                        long newSyncCount = 0;
                        foreach (Record record in result)
                        {
                            newSyncCount = newSyncCount < record.SyncCount
                                ? record.SyncCount
                                    : newSyncCount;
                        }
                        if (newSyncCount == lastSyncCount + 1)
                        {
                            AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Info, "DefaultDataset",
                                              String.Format("updated sync count %d", newSyncCount));
                            _local.UpdateLastSyncCount(GetIdentityId(), _datasetName,
                                                       newSyncCount);
                        }

                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncSuccess");
                        // call back
                        FireSyncSuccessEvent(remoteRecords);
                        callback(new RunSyncOperationResponse(true, null));
                        return;
                    }, null);
                    return;
                }


                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "CognitoSyncManager", "OnSyncSuccess");
                // call back
                FireSyncSuccessEvent(remoteRecords);
                callback(new RunSyncOperationResponse(true, null));
                return;
            }, null);
        }
Ejemplo n.º 23
0
        private void SetupDatabase()
        {
            lock (SQLiteDatabase.SQLiteLock)
            {
                SQLiteStatement stmt = null;
                try
                {
                    db = new SQLiteDatabase(this.dataPath);

                    string query = "SELECT count(*) as count FROM sqlite_master WHERE type='table' AND name='" + TABLE_DATASETS + "'";
                    //sqliteStm stmHandle = db.
                    stmt = db.Prepare(query);


                    if (stmt.Read() && stmt.Fields["count"].INTEGER == 0)
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteLocalStorage", "running create dataset");
                        db.Exec(
                            "CREATE TABLE " + TABLE_DATASETS + "("
                            + DatasetColumns.IDENTITY_ID + " TEXT NOT NULL,"
                            + DatasetColumns.DATASET_NAME + " TEXT NOT NULL,"
                            + DatasetColumns.CREATION_TIMESTAMP + " TEXT DEFAULT '0',"
                            + DatasetColumns.LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
                            + DatasetColumns.LAST_MODIFIED_BY + " TEXT,"
                            + DatasetColumns.STORAGE_SIZE_BYTES + " INTEGER DEFAULT 0,"
                            + DatasetColumns.RECORD_COUNT + " INTEGER DEFAULT 0,"
                            + DatasetColumns.LAST_SYNC_COUNT + " INTEGER NOT NULL DEFAULT 0,"
                            + DatasetColumns.LAST_SYNC_TIMESTAMP + " INTEGER DEFAULT '0',"
                            + DatasetColumns.LAST_SYNC_RESULT + " TEXT,"
                            + "UNIQUE (" + DatasetColumns.IDENTITY_ID + ", "
                            + DatasetColumns.DATASET_NAME + ")"
                            + ")");
                    }

                    stmt.FinalizeStm();
                    query = "SELECT count(*) as count FROM sqlite_master WHERE type='table' AND name='" + TABLE_RECORDS + "'";

                    stmt = db.Prepare(query);


                    if (stmt.Read() && stmt.Fields["count"].INTEGER == 0)
                    {
                        AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteLocalStorage", "running create records");
                        db.Exec(
                            "CREATE TABLE " + TABLE_RECORDS + "("
                            + RecordColumns.IDENTITY_ID + " TEXT NOT NULL,"
                            + RecordColumns.DATASET_NAME + " TEXT NOT NULL,"
                            + RecordColumns.KEY + " TEXT NOT NULL,"
                            + RecordColumns.VALUE + " TEXT,"
                            + RecordColumns.SYNC_COUNT + " INTEGER NOT NULL DEFAULT 0,"
                            + RecordColumns.LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
                            + RecordColumns.LAST_MODIFIED_BY + " TEXT,"
                            + RecordColumns.DEVICE_LAST_MODIFIED_TIMESTAMP + " TEXT DEFAULT '0',"
                            + RecordColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 1,"
                            + "UNIQUE (" + RecordColumns.IDENTITY_ID + ", " + RecordColumns.DATASET_NAME
                            + ", " + RecordColumns.KEY + ")"
                            + ")");
                    }
                }
                finally
                {
                    if (stmt != null)
                    {
                        stmt.FinalizeStm();
                    }
                }
                AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Verbose, "SQLiteLocalStorage", "completed setupdatabase");
            }
        }