Ejemplo n.º 1
0
        private BatchItemResponse BuildResponseWithError(string key, string version, string error)
        {
            BatchItemResponse itemResp = new BatchItemResponse()
            {
                Key       = key,
                Version   = version,
                Error     = error,
                ErrorDesc = error
            };

            return(itemResp);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This method executes the batch request.
        /// </summary>
        public void Execute()
        {
            this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Started Executing Method Execute for Batch");

            // Create Intuit Batch Request
            IntuitBatchRequest intuitBatchRequest = new IntuitBatchRequest();

            intuitBatchRequest.BatchItemRequest = this.batchRequests.ToArray <BatchItemRequest>();

            string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/batch", Utility.CoreConstants.VERSION, this.serviceContext.RealmId);

            // Creates request parameters
            RequestParameters parameters;

            if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
            {
                parameters = new RequestParameters(uri, HttpVerbType.POST, Utility.CoreConstants.CONTENTTYPE_APPLICATIONJSON);
            }
            else
            {
                parameters = new RequestParameters(uri, HttpVerbType.POST, Utility.CoreConstants.CONTENTTYPE_APPLICATIONXML);
            }
            // Prepares request
            HttpWebRequest request = this.restHandler.PrepareRequest(parameters, intuitBatchRequest);

            string response = string.Empty;

            try
            {
                // gets response
                response = this.restHandler.GetResponse(request);
            }
            catch (IdsException ex)
            {
                IdsExceptionManager.HandleException(ex);
            }

            CoreHelper.CheckNullResponseAndThrowException(response);

            // de serialize object
            IntuitResponse restResponse = (IntuitResponse)this.responseSerializer.Deserialize <IntuitResponse>(response);

            this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Execute method for batch.");
            foreach (object obj in restResponse.AnyIntuitObjects)
            {
                BatchItemResponse batchItemResponse = obj as BatchItemResponse;
                this.batchResponses.Add(batchItemResponse);

                // process batch item
                this.intuitBatchItemResponses.Add(ProcessBatchItemResponse(batchItemResponse));
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Tries to get the <see cref="Intuit.Ipp.DataService.IntuitBatchResponse"/> with the specified id
        /// </summary>
        /// <param name="id"> unique batchitem id. </param>
        /// <returns>True if the item was found, otherwise false</returns>
        public bool TryGetValue(string id, out IntuitBatchResponse intuitBatchResponse)
        {
            BatchItemResponse batchresponse = this.batchResponses.FirstOrDefault(item => item.bId == id);

            if (batchresponse == null)
            {
                intuitBatchResponse = null;
                return(false);
            }

            intuitBatchResponse = ProcessBatchItemResponse(batchresponse);
            return(true);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the <see cref="Intuit.Ipp.DataService.IntuitBatchResponse"/> with the specified id.
        /// </summary>
        /// <param name="id"> unique batchitem id. </param>
        public IntuitBatchResponse this[string id]
        {
            get
            {
                BatchItemResponse batchresponse = this.batchResponses.Find(item => item.bId == id);
                // if (batchresponse == null)
                // {
                //    throw new IdsException(string.Format("Could not find the batch item response with the specified id: {0}", id));
                // }

                IntuitBatchResponse result = ProcessBatchItemResponse(batchresponse);
                return(result);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// call back method for asynchronous batch execution.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="Intuit.Ipp.Core.AsyncCallCompletedEventArgs"/> instance containing the event data.</param>
        private void BatchAsyncompleted(object sender, AsyncCallCompletedEventArgs eventArgs)
        {
            BatchExecutionCompletedEventArgs batchCompletedEventArgs = new BatchExecutionCompletedEventArgs();

            try
            {
                if (eventArgs.Error == null)
                {
                    try
                    {
                        IEntitySerializer responseSerializer = CoreHelper.GetSerializer(this.serviceContext, false);
                        IntuitResponse    restResponse       = (IntuitResponse)responseSerializer.Deserialize <IntuitResponse>(eventArgs.Result);
                        foreach (object obj in restResponse.AnyIntuitObjects)
                        {
                            BatchItemResponse batchItemResponse = obj as BatchItemResponse;
                            this.batchResponses.Add(batchItemResponse);

                            // process batch item
                            this.intuitBatchItemResponses.Add(ProcessBatchItemResponse(batchItemResponse));
                        }

                        batchCompletedEventArgs.Batch = this;
                        this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs);
                    }
                    catch (SystemException systemException)
                    {
                        IdsException idsException = new IdsException("Batch execution failed", systemException);
                        this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString());
                        batchCompletedEventArgs.Error = idsException;
                        this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs);
                    }
                }
                else
                {
                    batchCompletedEventArgs.Error = eventArgs.Error;
                    this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs);
                }
            }
            catch (Exception e)
            {
                IdsException idsException = new IdsException("Batch execution failed", e);
                this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString());
                batchCompletedEventArgs.Error = idsException;
                this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// process batch item response
        /// </summary>
        /// <param name="batchitemResponse">The batchitem response.</param>
        /// <returns> returns IntuitBatchResponse object.</returns>
        private static IntuitBatchResponse ProcessBatchItemResponse(BatchItemResponse batchitemResponse)
        {
            IntuitBatchResponse result = new IntuitBatchResponse();

            result.Id = batchitemResponse.bId;
            Fault fault = batchitemResponse.AnyIntuitObject as Fault;

            if (fault == null)
            {
                CDCResponse cdcResponses = batchitemResponse.AnyIntuitObject as CDCResponse;
                if (cdcResponses != null)
                {
                    result.ResponseType = ResponseType.CdcQuery;
                    int count = 1;
                    IntuitCDCResponse returnValue    = new IntuitCDCResponse();
                    object[]          queryResponses = cdcResponses.AnyIntuitObjects;
                    if (queryResponses != null)
                    {
                        foreach (QueryResponse queryResponse in queryResponses)
                        {
                            Type           type     = queryResponse.GetType();
                            List <IEntity> entities = new List <IEntity>();

                            PropertyInfo[] propertyInfoArray = type.GetProperties();

                            foreach (PropertyInfo propertyInfo in propertyInfoArray)
                            {
                                if (true == propertyInfo.PropertyType.IsArray)
                                {
                                    object tempEntities = propertyInfo.GetValue(queryResponse, null);
                                    if (tempEntities != null)
                                    {
                                        object[] tempEntityArray = (object[])tempEntities;

                                        if (tempEntityArray.Length > 0)
                                        {
                                            List <IEntity> arr        = new List <IEntity>();
                                            string         entityName = string.Empty;
                                            foreach (object item in tempEntityArray)
                                            {
                                                entities.Add((IEntity)item);
                                                entityName = item.GetType().Name;
                                                count++;
                                            }
                                            returnValue.entities.Add(entityName, entities);
                                        }
                                        break;
                                    }
                                }
                            }
                            result.CDCResponse = returnValue;
                        }
                    }
                }
                else
                {
                    IEntity entity = batchitemResponse.AnyIntuitObject as IEntity;
                    if (entity == null)
                    {
                        QueryResponse queryResponse = batchitemResponse.AnyIntuitObject as QueryResponse;
                        if (queryResponse != null)
                        {
                            result.ResponseType = ResponseType.Query;
                            QueryResponse returnValue = new QueryResponse();
                            returnValue.totalCount          = queryResponse.totalCount;
                            returnValue.totalCountSpecified = queryResponse.totalCountSpecified;
                            result.QueryResponse            = returnValue;

                            if (queryResponse.AnyIntuitObjects != null && queryResponse.AnyIntuitObjects.Count() > 0)
                            {
                                foreach (object obj in queryResponse.AnyIntuitObjects)
                                {
                                    result.AddEntities(obj as IEntity);
                                }
                            }
                        }
                        else
                        {
                            //Not sure how we end up here
                        }
                    }
                    else
                    {
                        result.ResponseType = ResponseType.Entity;
                        result.Entity       = entity;
                    }
                }
            }
            else
            {
                result.ResponseType = ResponseType.Exception;
                IdsException idsException = IterateFaultAndPrepareException(fault);
                result.Exception = idsException;
            }

            return(result);
        }
Ejemplo n.º 7
0
        public async Task <BatchResponse> Store(string bucketName, BatchSet value)
        {
            var db = client.GetDatabase(DbName);

            var collection = db.GetCollection <BsonDocument>(bucketName);
            var response   = new BatchResponse();

            response.BatchItemResponses = new List <BatchItemResponse>();
            SyncLogItem syncLogItem = new SyncLogItem();

            syncLogItem.KeyVersion = new Dictionary <string, string>();

            foreach (var document in value.ChangedDocuments)
            {
                var newDoc = Mapper.ToBsonDoc(document);
                newDoc["_rev"] = this.GenerateNewVersion();
                try
                {
                    var exists = await collection.Find(filter : new BsonDocument {
                        { "_id", document.Key }
                    }).FirstOrDefaultAsync();

                    if (exists == null && !string.IsNullOrEmpty(document.Version)) //somebody else deleted the doc-> conflict
                    {
                        BatchItemResponse respWithError = BuildResponseWithError(document.Key, document.Version, "conflict");
                        response.ItemsWithErrors++;
                        response.BatchItemResponses.Add(respWithError);
                        continue;
                    }
                    var result = await collection.ReplaceOneAsync(filter : new BsonDocument {
                        { "_id", document.Key }, { "_rev", BsonTypeMapper.MapToBsonValue(document.Version) }
                    },
                                                                  options : new UpdateOptions {
                        IsUpsert = true
                    },
                                                                  replacement : newDoc);

                    BatchItemResponse itemResp = new BatchItemResponse
                    {
                        Key     = document.Key,
                        Version = newDoc["_rev"].AsString
                    };
                    response.BatchItemResponses.Add(itemResp);
                    syncLogItem.KeyVersion.Add(itemResp.Key, itemResp.Version);
                }
                catch (MongoWriteException ex)
                {
                    string error = ex.Message;
                    if (ex.Message.Contains("duplicate key"))//conflict
                    {
                        error = "conflict";
                    }
                    var itemResp = BuildResponseWithError(document.Key, document.Version, error);
                    response.ItemsWithErrors++;
                    response.BatchItemResponses.Add(itemResp);
                }
            }
            foreach (var document in value.DeletedDocuments)
            {
                BatchItemResponse itemResp = new BatchItemResponse()
                {
                    Key     = document.Key,
                    Version = document.Version
                };
                var del = await collection.DeleteOneAsync(filter : new BsonDocument {
                    { "_id", document.Key }, { "_rev", BsonTypeMapper.MapToBsonValue(document.Version) }
                });

                if (del.DeletedCount == 0)
                {
                    var docFromDB = collection.Find(filter: new BsonDocument {
                        { "_id", document.Key }
                    }).FirstOrDefaultAsync();
                    if (docFromDB != null)
                    {
                        itemResp.Error     = "conflict";
                        itemResp.ErrorDesc = "conflict";
                        response.ItemsWithErrors++;
                    }
                }
                response.BatchItemResponses.Add(itemResp);
            }
            //store uploadedAnchor
            if (syncLogItem.KeyVersion.Count > 0)
            {
                syncLogItem.TimeInserted = DateTime.UtcNow;
                BsonDocument syncLogDoc = new BsonDocument();
                syncLogDoc["KeyVersion"]   = new BsonDocument(syncLogItem.KeyVersion);
                syncLogDoc["TimeInserted"] = syncLogItem.TimeInserted;
                var collectionLog = db.GetCollection <BsonDocument>(SyncLogBucket);
                await collectionLog.InsertOneAsync(syncLogDoc);

                response.UploadAnchor = syncLogDoc["_id"].ToString();
            }

            return(response);
        }
Ejemplo n.º 8
0
        public async Task <BatchResponse> Store(string bucketName, BatchSet batch)
        {
            using (var client = new MyCouchClient(DbServerUrl, bucketName))
            {
                var dbExists = await client.Database.HeadAsync();

                if (dbExists.IsSuccess)
                {
                    BulkRequest bulkRequest = new BulkRequest();

                    DateTime        start = DateTime.Now;
                    int             size  = 0;
                    SiaqodbDocument crObjForUpdateViews = null;
                    if (batch.ChangedDocuments != null)
                    {
                        foreach (SiaqodbDocument obj in batch.ChangedDocuments)
                        {
                            if (obj != null)
                            {
                                if (crObjForUpdateViews == null)
                                {
                                    crObjForUpdateViews = obj;
                                }

                                await CheckTagsViews(client, bucketName, obj.Tags);

                                CouchDBDocument doc = Mapper.ToCouchDBDoc(obj);
                                var             serializedObject = client.Serializer.Serialize <CouchDBDocument>(doc);
                                bulkRequest.Include(serializedObject);
                                size += serializedObject.Length;
                            }
                        }
                    }
                    if (batch.DeletedDocuments != null)
                    {
                        foreach (DeletedDocument obj in batch.DeletedDocuments)
                        {
                            if (obj != null)
                            {
                                if (obj.Version != null)//otherwise means is a non-existing object
                                {
                                    bulkRequest.Delete(obj.Key, obj.Version);
                                }
                            }
                        }
                    }
                    var response = await client.Documents.BulkAsync(bulkRequest);

                    if (response.IsSuccess)
                    {
                        var cnorResponse = new BatchResponse();
                        if (response.Rows != null)
                        {
                            cnorResponse.BatchItemResponses = new List <BatchItemResponse>();
                            SyncLogItem syncLogItem = new SyncLogItem();
                            syncLogItem.KeyVersion = new Dictionary <string, string>();
                            foreach (var row in response.Rows)
                            {
                                BatchItemResponse wresp = new BatchItemResponse();
                                if (!string.IsNullOrEmpty(row.Error))
                                {
                                    cnorResponse.ItemsWithErrors++;
                                }
                                wresp.Error     = row.Error;
                                wresp.ErrorDesc = row.Reason;
                                wresp.Key       = row.Id;
                                wresp.Version   = row.Rev;
                                cnorResponse.BatchItemResponses.Add(wresp);
                                if (string.IsNullOrEmpty(row.Error))
                                {
                                    syncLogItem.KeyVersion.Add(row.Id, row.Rev);
                                }
                            }
                            if (syncLogItem.KeyVersion.Count > 0)
                            {
                                syncLogItem.TimeInserted = DateTime.UtcNow;
                                using (var clientLog = new MyCouchClient(DbServerUrl, SyncLogBucket))
                                {
                                    string serLogItem = Newtonsoft.Json.JsonConvert.SerializeObject(syncLogItem);
                                    var    logResp    = await clientLog.Documents.PostAsync(serLogItem);

                                    cnorResponse.UploadAnchor = logResp.Id;
                                }
                            }
                        }
                        if (crObjForUpdateViews != null)
                        {
                            await this.StartRebuildViews(client, crObjForUpdateViews);
                        }

                        return(cnorResponse);
                    }
                    else
                    {
                        CheckBucketNotFound(bucketName, response);
                    }
                }
                else if (dbExists.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    throw new BucketNotFoundException(bucketName);
                }
                return(null);
            }
        }