private void InvokeHelper(AsyncResult asyncResult)
 {
     if (asyncResult.RetriesAttempt == 0 || Config.ResignRetries)
     {
         if (Credentials is CognitoAWSCredentials)
         {
             var cred = Credentials as CognitoAWSCredentials;
             // very hacky solution
             cred.GetCredentialsAsync(delegate(AmazonServiceResult voidResult)
             {
                 if (voidResult.Exception != null)
                 {
                     asyncResult.IsCompleted = true;
                     AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "CognitoAWSCredentials", voidResult.Exception.Message);
                     asyncResult.HandleException(voidResult.Exception);
                     return;
                 }
                 ProcessHttpRequest(asyncResult);
             }, null);
             return;
         }
     }
     ProcessHttpRequest(asyncResult);
     return;
 }
Ejemplo n.º 2
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.º 3
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.º 4
0
        protected void GenerateNewCredentialsAsync(AmazonServiceCallback callback)
        {
            AmazonServiceResult voidResult = new AmazonServiceResult(null, null);

            IdentityProvider.RefreshAsync(delegate(AmazonServiceResult refreshResult)
            {
                if (refreshResult.Exception != null)
                {
                    voidResult.Exception = refreshResult.Exception;
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }


                // Pick role to use, depending on Logins
                string roleArn = UnAuthRoleArn;
                if (IdentityProvider.Logins.Count > 0)
                {
                    roleArn = AuthRoleArn;
                }
                if (string.IsNullOrEmpty(roleArn))
                {
                    voidResult.Exception = new AmazonServiceException(
                        new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                    "Unable to determine Role ARN. AuthRoleArn = [{0}], UnAuthRoleArn = [{1}], Logins.Count = {2}",
                                                                    AuthRoleArn, UnAuthRoleArn, IdentityProvider.Logins.Count)));
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }

                // Assume role with Open Id Token
                var assumeRequest = new AssumeRoleWithWebIdentityRequest
                {
                    WebIdentityToken = IdentityProvider.GetCurrentOpenIdToken(),
                    RoleArn          = roleArn,
                    RoleSessionName  = "UnityProviderSession",
                    DurationSeconds  = DefaultDurationSeconds
                };

                sts.AssumeRoleWithWebIdentityAsync(assumeRequest, delegate(AmazonServiceResult result)
                {
                    if (result.Exception != null)
                    {
                        voidResult.Exception = result.Exception;
                        AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "STS", result.Exception.Message);
                        AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                        return;
                    }
                    AssumeRoleWithWebIdentityResponse assumeRoleWithWebIdentityResponse = result.Response as AssumeRoleWithWebIdentityResponse;
                    this._currentState = new CredentialsRefreshState
                    {
                        Credentials = assumeRoleWithWebIdentityResponse.Credentials.GetCredentials(),
                        Expiration  = assumeRoleWithWebIdentityResponse.Credentials.Expiration
                    };
                    // success - FinalResponse
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }, null);
            }, null);
        }
        protected void InvokeS3Post(PostObjectRequest publicrequest, AmazonServiceCallback callback, object state)
        {
            AsyncResult asyncResult = new AsyncResult(new DefaultRequest(publicrequest, "Amazon.S3"),
                                                      publicrequest, callback,
                                                      state, new S3Signer(), null);

            try
            {
                asyncResult.Metrics.StartEvent(Metric.ClientExecuteTime);
                asyncResult.Request.Endpoint = DetermineEndpoint(asyncResult.Request);
                if (Config.LogMetrics)
                {
                    asyncResult.Metrics.IsEnabled = true;
                    asyncResult.Metrics.AddProperty(Metric.ServiceName, asyncResult.Request.ServiceName);
                    asyncResult.Metrics.AddProperty(Metric.ServiceEndpoint, asyncResult.Request.Endpoint);
                    asyncResult.Metrics.AddProperty(Metric.MethodName, asyncResult.RequestName);
                    asyncResult.Metrics.AddProperty(Metric.AsyncCall, !asyncResult.CompletedSynchronously);
                }
                //ConfigureRequest(asyncResult);

                InvokeHelperForS3PostObject(asyncResult, publicrequest);
            }
            catch (Exception e)
            {
                AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, "S3", e);
                asyncResult.IsCompleted = true;
                asyncResult.HandleException(e);
                return;
            }
            //return asyncResult;
        }
Ejemplo n.º 6
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");
            };
        }
        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.º 8
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");
 }
Ejemplo n.º 9
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.º 10
0
        // fetching/persisting new credentials in LocalStorage
        public override void GetCredentialsAsync(AmazonServiceCallback callback, object state)
        //internal IEnumerator GetCredentialsCoroutine(VoidResponse voidResponse)
        {
            //lock (this._refreshLock)
            //{

            //
            if (_currentState == null)
            {
                loadCachedCredentials();
            }
            // If credentials are expired, update
            if (ShouldUpdate)
            {
                GenerateNewCredentialsAsync(delegate(AmazonServiceResult voidResult)
                {
                    if (voidResult.Exception != null)
                    {
                        AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "Cognito", "Error occured during GetCredentialsAsync");
                        AmazonMainThreadDispatcher.ExecCallback(callback, new AmazonServiceResult(null, null, voidResult.Exception, state));
                        return;
                    }
                    // Check if the new credentials are already expired
                    if (ShouldUpdate)
                    {
                        voidResult.Exception = new AmazonServiceException("The retrieved credentials have already expired");
                        AmazonMainThreadDispatcher.ExecCallback(callback, new AmazonServiceResult(null, null, voidResult.Exception, state));
                        return;
                    }

                    // Offset the Expiration by PreemptExpiryTime
                    _currentState.Expiration -= PreemptExpiryTime;

                    if (ShouldUpdate)
                    {
                        // This could happen if the default value of PreemptExpiryTime is
                        // overriden and set too high such that ShouldUpdate returns true.

                        voidResult.Exception = new AmazonClientException(String.Format(
                                                                             "The preempt expiry time is set too high: Current time = {0}, Credentials expiry time = {1}, Preempt expiry time = {2}.",
                                                                             DateTime.Now, _currentState.Expiration, PreemptExpiryTime));
                        AmazonMainThreadDispatcher.ExecCallback(callback, new AmazonServiceResult(null, null, voidResult.Exception, state));
                        return;
                    }
                    saveCredentials();
                    AmazonMainThreadDispatcher.ExecCallback(callback, new AmazonServiceResult(null, null, null, state));
                });
                return;
            }
            AmazonMainThreadDispatcher.ExecCallback(callback, new AmazonServiceResult(null, null, null, state));


            //}
        }
Ejemplo n.º 11
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.º 12
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.º 13
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");
     }
 }
        public override void Put(string key, string value)
        {
            lock (SQLiteDatabase.SQLiteLock)
            {
                string          query = "SELECT count(*) as count FROM " + TABLE_RECORDS + " where " + COLUMN_KEY + " = ?";
                SQLiteStatement stmt  = null;
                try
                {
                    stmt = db.Prepare(query);
                    stmt.BindText(1, key);
                    if (stmt.Read())
                    {
                        long count = stmt.Fields["count"].INTEGER;
                        stmt.FinalizeStm();

                        if (count == 0)
                        {
                            // insert record
                            query = "INSERT INTO " + TABLE_RECORDS + " (" + COLUMN_KEY + ", " + COLUMN_VALUE + ") VALUES(?,?)";
                            stmt  = db.Prepare(query);
                            stmt.BindText(1, key);
                            stmt.BindText(2, value);
                            stmt.Step();
                            return;
                        }
                        else
                        {
                            // update record
                            query = "UPDATE " + TABLE_RECORDS + " SET " + COLUMN_VALUE + " = ? where " + COLUMN_KEY + " = ?";
                            stmt  = db.Prepare(query);
                            stmt.BindText(2, key);
                            stmt.BindText(1, value);
                            stmt.Step();
                            return;
                        }
                    }
                    else
                    {
                        AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "SQLiteKVStore", "Save failed");
                        throw new Exception("Save failed");
                    }
                }
                finally
                {
                    if (stmt != null)
                    {
                        stmt.FinalizeStm();
                    }
                }
            }
        }
        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.º 16
0
 private static void Execute <T>(AsyncCall call, DynamoDBAsyncState <T> result)
 {
     try
     {
         result.Return = call();
         AmazonMainThreadDispatcher.ExecCallback <T>(result.Callback, new AmazonDynamoResult <T>((T)result.Return, null, result.State));
         return;
     }
     catch (Exception ex)
     {
         AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, result.Operation, ex);
         AmazonMainThreadDispatcher.ExecCallback <T>(result.Callback, new AmazonDynamoResult <T>(default(T), ex, result.State));
         return;
     }
 }
        /// <summary>
        /// The HandleWWWErrorResponse differs significantly from the error handling doing in .NET sdk
        /// since the www.error string message is incomplete
        /// so this requires rewriting all responseunmarshallers.HandleErrorContext which is not part of this version
        /// hence exception thrown will always be of base type AmazonServiceException
        /// </summary>
        /// <returns>True if the error needs retry</returns>
        private bool HandleWWWErrorResponse(AsyncResult asyncResult)
        {
            WWWResponseData errorResponse = asyncResult.ResponseData;

            asyncResult.Metrics.AddProperty(Metric.Exception, errorResponse.Error);

            AmazonServiceException errorResponseException = null;

            errorResponseException = new AmazonServiceException(errorResponse.Error,
                                                                new WebException(errorResponse.Error));

            errorResponseException.UnityStatusCode = errorResponse.Error;
            try
            {
                errorResponseException.StatusCode = errorResponse.ErrorStatusCode;
            }
            catch (Exception e)
            {
                // Parsing exception
                AmazonLogging.LogException(AmazonLogging.AmazonLoggingLevel.Errors, asyncResult.Request.RequestName, e);
            }

            string curl = "curl " + (asyncResult.Request.HttpMethod == "GET" &&
                                     !HttpOverrideSupportedServices.Contains(asyncResult.Request.ServiceName) ?
                                     "-G " :  "-X POST ");

            foreach (string key in asyncResult.RequestData.Headers.Keys)
            {
                curl += " -H \"" + key + ": " + asyncResult.RequestData.Headers[key] + "\" ";
            }
            if (asyncResult.RequestData.Data != null)
            {
                curl += " -d '" + System.Text.Encoding.Default.GetString(asyncResult.RequestData.Data) + "' ";
            }

            curl += " " + asyncResult.RequestData.Url;
            Debug.LogError(curl);

            if (errorResponse.IsHeaderPresent(HeaderKeys.XAmzRequestIdHeader.ToUpper()))
            {
                errorResponseException.RequestId = errorResponse.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader);
            }

            asyncResult.Exception = errorResponseException;

            // currently no retries are done
            return(false);
        }
Ejemplo n.º 18
0
        public override void PutValue(string identityId, string datasetName, string key, string value)
        {
            lock (SQLiteDatabase.SQLiteLock)
            {
                bool result = this.PutValueInternal(identityId, datasetName, key, value);

                if (!result)
                {
                    AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "SQLite", "PutValue failed");
                }
                else
                {
                    this.UpdateLastModifiedTimestamp(identityId, datasetName);
                }
            }
        }
        private void InvokeHelperForS3PostObject(AsyncResult asyncResult, PostObjectRequest request)
        {
            if (asyncResult.RetriesAttempt == 0 || Config.ResignRetries)
            {
                // Add Post policy
                if (request.PostPolicy == null)
                {
                    int    position = request.Key.LastIndexOf('.');
                    string ext = null, contentType = null;
                    if (position != -1)
                    {
                        ext         = request.Key.Substring(position, request.Key.Length - position);
                        contentType = AmazonS3Util.MimeTypeFromExtension(ext);
                    }
                    else
                    {
                        contentType = "application/octet-stream";
                    }
                    request.PostPolicy = S3PostPolicyBuilder.GetPostPolicy(request.Bucket, request.Key, contentType);
                }



                if (Credentials is CognitoAWSCredentials)
                {
                    var cred = Credentials as CognitoAWSCredentials;
                    // very hacky solution
                    cred.GetCredentialsAsync(delegate(AmazonServiceResult voidResult)
                    {
                        if (voidResult.Exception != null)
                        {
                            asyncResult.IsCompleted = true;
                            AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "CognitoAWSCredentials", voidResult.Exception.Message);
                            asyncResult.HandleException(voidResult.Exception);
                            return;
                        }
                        request.SignedPolicy = S3PostUploadSignedPolicy.GetSignedPolicy(request.PostPolicy, cred);
                        ProcessS3PostRequest(asyncResult, request);
                    }, null);
                    return;
                }
                request.SignedPolicy = S3PostUploadSignedPolicy.GetSignedPolicy(request.PostPolicy, Credentials);
            }

            ProcessS3PostRequest(asyncResult, request);
        }
Ejemplo n.º 20
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);
        }
 public static void LoadEndpointDefinitions()
 {
     try
     {
         TextAsset awsEndpoints = UnityEngine.Resources.Load("aws_endpoints_json") as TextAsset;
         using (Stream stream = new MemoryStream(awsEndpoints.bytes))
         {
             using (StreamReader reader = new StreamReader(stream))
             {
                 LoadEndpointDefinitions(reader);
             }
         }
     }
     catch (System.Exception exception)
     {
         AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.ErrorsAsExceptions, "LoadEndpointDefinitions",
                                "cannot load service endpoint file : " + exception.Message);
     }
 }
Ejemplo n.º 22
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);
        }
        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.º 24
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");
            };
        }
        protected void Invoke <T, R>(R request, AmazonServiceCallback callback, object state, IMarshaller <T, R> marshaller, ResponseUnmarshaller unmarshaller, AbstractAWSSigner signer)
            where T : IRequest
            where R : AmazonWebServiceRequest
        {
            AsyncResult result = null;

            try
            {
                ProcessPreRequestHandlers(request);

                IRequest irequest = marshaller.Marshall(request);
                result = new AsyncResult(irequest, request, callback, state, signer, unmarshaller);
                Invoke(result);
            }
            catch (Exception e)
            {
                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "Runtime", e.Message);
                result.HandleException(e);
                result.IsCompleted = true;
            }
            //return result;
        }
Ejemplo n.º 26
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.º 27
0
        public void SynchronizeInternalAsync()
        {
            try
            {
                List <string> mergedDatasets = GetLocalMergedDatasets();
                if (mergedDatasets.Count != 0)
                {
                    this.OnDatasetMerged(this, mergedDatasets);
                }

                this.RunSyncOperationAsync(MAX_RETRY, delegate(RunSyncOperationResponse response)
                {
                    if (response == null || response.Exception != null)
                    {
                        FireSyncFailureEvent(new DataStorageException("Unknown exception", response.Exception));
                    }
                });
            }
            catch (Exception e)
            {
                FireSyncFailureEvent(new DataStorageException("Unknown exception", e));
                AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "CognitoSyncManager", "failed to synchronize " + e.Message);
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Log the GameCircle message.
 /// </summary>
 /// <param name='message'>
 /// Message.
 /// </param>
 public static void Log(string message)
 {
     AmazonLogging.Log(errorLevel, serviceName, message);
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Logs the GameCircle warning.
 /// </summary>
 /// <param name='errorMessage'>
 /// Error message.
 /// </param>
 public static void LogGameCircleWarning(string errorMessage)
 {
     AmazonLogging.LogWarning(errorLevel, serviceName, errorMessage);
 }
 public override void WipeData()
 {
     local.WipeData();
     AmazonLogging.Log(AmazonLogging.AmazonLoggingLevel.Info, "DefaultCognitoSyncManager", "All data has been wiped");
 }