private static Task ExecuteBatchRequest()
        {
            return(Task.Run(() =>
            {
                CustomersContext context = new CustomersContext(new Uri(serviceUrl));
                context.Format.UseJson();
                IList <Customer> customers = context.Customers.ToList();
                Customer customerToAdd = new Customer
                {
                    Id = 5,
                    Name = "New Customer"
                };
                Customer customerToUpdate = customers.Skip(1).First();
                Customer customerToDelete = customers.Skip(2).First();

                context.AddToCustomers(customerToAdd);
                customerToUpdate.Name = "Peter";
                context.UpdateObject(customerToUpdate);
                context.DeleteObject(customerToDelete);

                DataServiceResponse response =
                    context.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset | SaveChangesOptions.ReplaceOnUpdate);
                if (!response.IsBatchResponse)
                {
                    Console.WriteLine("There was an error with the batch request");
                }
                int i = 0;
                foreach (OperationResponse individualResponse in response)
                {
                    Console.WriteLine("Operation {0} status code = {1}", i++, individualResponse.StatusCode);
                }
            }));
        }
Beispiel #2
0
        public async Task TestRandomEntityTypesAsync <T>(string entitySetName)
        {
            // clear respository
            await this.ClearRepositoryAsync(entitySetName);

            // TODO: Get ride of random generator in test codes. It's bad idea to introduce random factors in functional test
            var rand = new Random(RandomSeedGenerator.GetRandomSeed());

            T entityBaseline = await PostNewEntityAsync <T>(entitySetName, rand);

            T entityBeforeUpdate = await ReadFirstEntityAsync <T>(entitySetName);

            AssertExtension.PrimitiveEqual(entityBaseline, entityBeforeUpdate);

            DataServiceResponse responseUpdate = await UpdateEntityAsync <T>(entitySetName, entityBeforeUpdate, rand);

            T entityAfterUpdate = await ReadFirstEntityAsync <T>(entitySetName);

            AssertExtension.PrimitiveEqual(entityBeforeUpdate, entityAfterUpdate);

            DataServiceResponse responseDelete = await DeleteEntityAsync <T>(entitySetName, entityAfterUpdate);

            T[] entities = await ReadAllEntitiesAsync <T>(entitySetName);

            Assert.Empty(entities);
        }
Beispiel #3
0
        private void SaveCallback(IAsyncResult asyncResult)
        {
            DataServiceResponse response = null;

            try
            {
                response = context.EndSaveChanges(asyncResult);
            }
            catch (Exception ex)
            {
                gridControl1.BeginInvoke((MethodInvoker) delegate { context.CancelRequest(asyncResult); });
                HandleException(ex);
                gridControl1.BeginInvoke((MethodInvoker) delegate { DetachFailedEntities(); });
            }
            gridControl1.BeginInvoke((MethodInvoker) delegate { wSMS.Reload(); });
            gridControl1.BeginInvoke((MethodInvoker) delegate {
                if (SelectedRow > 0)
                {
                    gridView1.FocusedRowHandle = SelectedRow;
                }
                if (!String.IsNullOrEmpty(newCustomerKey) && gridView1.DataRowCount > OldRowCount)
                {
                    for (int i = 0; i < gridView1.DataRowCount; i++)
                    {
                        if (newCustomerKey == gridView1.GetRowCellValue(i, gridView1.Columns["CustomerID"]).ToString())
                        {
                            gridView1.FocusedRowHandle = i;
                            OldRowCount    = gridView1.DataRowCount;
                            newCustomerKey = String.Empty;
                            break;
                        }
                    }
                }
            });
        }
Beispiel #4
0
        public void SendsIndividualErrorWhenOneOfTheRequestsFails()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            DefaultBatchProxy.Container client = new DefaultBatchProxy.Container(serviceUrl);
            client.Format.UseJson();

            DefaultBatchProxy.DefaultBatchCustomer validCustomer = new DefaultBatchProxy.DefaultBatchCustomer()
            {
                Id   = 10,
                Name = "Customer 10"
            };

            DefaultBatchProxy.DefaultBatchCustomer invalidCustomer = new DefaultBatchProxy.DefaultBatchCustomer()
            {
                Id   = -1,
                Name = "Customer -1"
            };

            client.AddToDefaultBatchCustomer(validCustomer);
            client.AddToDefaultBatchCustomer(invalidCustomer);
            var aggregate = Assert.Throws <AggregateException>(() =>
            {
                DataServiceResponse response = client.SaveChangesAsync(SaveChangesOptions.BatchWithSingleChangeset).Result;
            });

            var exception = aggregate.InnerExceptions.Single() as DataServiceRequestException;

            Assert.NotNull(exception);
            Assert.Equal(200, exception.Response.BatchStatusCode);
            Assert.Equal(1, exception.Response.Count());
        }
Beispiel #5
0
        private static void QueryEntityInstance(DataServiceContextWrapper <DefaultContainer> contextWrapper)
        {
            // contextWrapper.Context.UndeclaredPropertyBehavior = UndeclaredPropertyBehavior.Support;
            contextWrapper.Configurations.ResponsePipeline
            .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
            .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
            .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

            var specialEmployee =
                contextWrapper.CreateQuery <Person>("Person").Where(p => p.PersonId == -10).Single() as SpecialEmployee;
            EntityDescriptor descriptor = contextWrapper.GetEntityDescriptor(specialEmployee);

            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            specialEmployee = contextWrapper.Execute <SpecialEmployee>(new Uri("Person(-10)", UriKind.Relative)).Single();
            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            DataServiceRequest[] requests = new DataServiceRequest[]
            {
                contextWrapper.CreateQuery <Person>("Person"),
                contextWrapper.CreateQuery <Customer>("Customer"),
            };

            DataServiceResponse responses = contextWrapper.ExecuteBatch(requests);
            bool personVerified           = false;
            bool customerVerified         = false;

            foreach (QueryOperationResponse response in responses)
            {
                foreach (object p in response)
                {
                    var      specialEmployee1 = p as SpecialEmployee;
                    Customer c = p as Customer;
                    if (specialEmployee1 != null)
                    {
                        Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee1.CarsLicensePlate,
                                        "Unexpected CarsLicensePlate");
                        Assert.AreEqual(1, specialEmployee1.BonusLevel, "Unexpected BonusLevel");
                        personVerified = true;
                    }

                    if (c != null)
                    {
                        Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected primitive property");
                        Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected complex property");
                        Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected collection property");
                        customerVerified = true;
                    }
                }
            }

            Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
        }
Beispiel #6
0
        public async Task SingletonQueryInBatchTest()
        {
            var serviceRoot   = this.BaseAddress + "/clientTest/";
            var ClientContext = new Client.Container(new Uri(serviceRoot));

            // Reset data source
            await ClientContext.ExecuteAsync(new Uri(serviceRoot + "Umbrella/Microsoft.Test.E2E.AspNet.OData.Singleton.ResetDataSource"), "POST");

            await ClientContext.ExecuteAsync(new Uri(serviceRoot + "Partners/Microsoft.Test.E2E.AspNet.OData.Singleton.ResetDataSource"),
                                             "POST");

            DataServiceRequest[] requests = new DataServiceRequest[] {
                ClientContext.CreateSingletonQuery <Client.Company>("Umbrella"),
                ClientContext.CreateQuery <Client.Partner>("Partners")
            };

            DataServiceResponse responses = await ClientContext.ExecuteBatchAsync(requests);

            foreach (var response in responses)
            {
                var companyResponse = response as QueryOperationResponse <Client.Company>;
                var partnerResponse = response as QueryOperationResponse <Client.Partner>;

                if (companyResponse != null)
                {
                    Assert.Equal("Umbrella", companyResponse.Single().Name);
                }

                if (partnerResponse != null)
                {
                    Assert.Equal(10, partnerResponse.ToArray().Count());
                }
            }
        }
        public bool SaveBizRuleCertMetadata(BizRuleCertMetadata bizRuleCertMetadata)
        {
            this.tableClient = account.CreateCloudTableClient();
            this.tableClient.CreateTableIfNotExist(BizRuleCertTableName);
            this.tableContext = tableClient.GetDataServiceContext();

            bizRuleCertMetadata.PartitionKey = bizRuleCertMetadata.TradingPartnerName;
            bizRuleCertMetadata.RowKey       = bizRuleCertMetadata.RuleCertFileName;
            bizRuleCertMetadata.Timestamp    = DateTime.UtcNow;

            if (BizRuleCerts.FirstOrDefault(t => t.PartitionKey == bizRuleCertMetadata.PartitionKey && t.RowKey == bizRuleCertMetadata.RowKey) == null)
            {
                BizRuleCerts.Add(bizRuleCertMetadata);
            }

            // We need upsert functionality here, hence removing AddObject call and adding UpdateObject
            // this.tableContext.AddObject(TradingPartnerSpecCertTableName, tradingPartnerSpecCert);
            // http://social.msdn.microsoft.com/Forums/windowsazure/en-US/892340f1-bfe1-4433-9246-b617abe6078c/upsert-operation-in-the-table
            // http://msdn.microsoft.com/en-us/library/windowsazure/hh452242.aspx
            // http://www.windowsazure.com/en-us/develop/net/how-to-guides/table-services/#replace-entity
            tableContext.AttachTo(BizRuleCertTableName, bizRuleCertMetadata);
            tableContext.UpdateObject(bizRuleCertMetadata);

            DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch | SaveChangesOptions.ReplaceOnUpdate);

            return(response.BatchStatusCode == Http200 || response.BatchStatusCode == Http201 || response.BatchStatusCode == Http202);
        }
        public void QueryEntityInstanceBatchAsync()
        {
            this.RunOnAtomAndJsonFormats(
                this.CreateContext,
                (contextWrapper) =>
            {
                contextWrapper.Context.IgnoreMissingProperties = true;

                contextWrapper.Configurations.ResponsePipeline
                .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
                .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
                .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

                DataServiceRequest[] requests = new DataServiceRequest[] {
                    contextWrapper.CreateQuery <Person>("Person(-10)"),
                    contextWrapper.CreateQuery <Customer>("Customer"),
                };

                DataServiceResponse responses = null;
                IAsyncResult r = contextWrapper.BeginExecuteBatch(
                    result =>
                {
                    responses = contextWrapper.EndExecuteBatch(result);
                },
                    null,
                    requests);

                while (!r.IsCompleted)
                {
                    Thread.Sleep(1000);
                }

                bool personVerified   = false;
                bool customerVerified = false;
                foreach (QueryOperationResponse response in responses)
                {
                    foreach (object p in response)
                    {
                        SpecialEmployee se1 = p as SpecialEmployee;
                        Customer c          = p as Customer;
                        if (se1 != null)
                        {
                            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", se1.CarsLicensePlate, "Unexpected CarsLicensePlate");
                            Assert.AreEqual(1, se1.BonusLevel, "Unexpected BonusLevel");
                            personVerified = true;
                        }

                        if (c != null)
                        {
                            Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property");
                            Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property");
                            Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property");
                            customerVerified = true;
                        }
                    }
                }

                Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
            });
        }
        public async Task <IActionResult> CreateEstablishment([FromBody] ViewModels.AdoxioEstablishment item)
        {
            // create a new establishment.
            var adoxioEstablishment = new Adoxio_establishment();

            // create a DataServiceCollection to add the record
            var EstablishmentCollection = new DataServiceCollection <Adoxio_establishment>(_system);

            EstablishmentCollection.Add(adoxioEstablishment);

            adoxioEstablishment.CopyValues(item);

            // PostOnlySetProperties is used so that settings such as owner will get set properly by the dynamics server.

            DataServiceResponse dsr = await _system.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithIndependentOperations);

            foreach (OperationResponse operationResult in dsr)
            {
                if (operationResult.StatusCode == 500) // error
                {
                    return(StatusCode(500, operationResult.Error.Message));
                }
            }
            ViewModels.AdoxioEstablishment result = adoxioEstablishment.ToViewModel();
            result.id = ((Guid)dsr.GetAssignedId()).ToString();

            return(Json(result));
        }
        /// <summary>
        /// Return the ID assigned by dynamics, or NULL if none.
        /// </summary>
        /// <param name="dsr"></param>
        /// <returns></returns>
        public static Guid?GetAssignedId(this DataServiceResponse dsr)
        {
            Guid?result = null;

            if (dsr != null)
            {
                var ienum = dsr.GetEnumerator();
                while (ienum.MoveNext())
                {
                    ChangeOperationResponse cor = (ChangeOperationResponse)ienum.Current;
                    if (cor.Descriptor is EntityDescriptor)
                    {
                        EntityDescriptor ed       = (EntityDescriptor)cor.Descriptor;
                        string           identity = ed.Identity.ToString();
                        // convert the identity to a guid.
                        int    endpos   = identity.LastIndexOf(")");
                        int    startpos = identity.LastIndexOf("(") + 1;
                        string guid     = identity.Substring(startpos, endpos - startpos);
                        result = Guid.ParseExact(guid, "D");
                        return(result);
                    }
                }
            }
            return(result);
        }
        public static void AddCustomAddress(String[] wkLine, Resources context)
        {
            string str1  = wkLine[0];               //Order No
            string str2  = wkLine[1];               //Advanced Payment ID
            string str3  = wkLine[2];               //Submit Date
            string str4  = wkLine[3];               //Payment Date
            string str5  = wkLine[4];               //Payment Time
            string str6  = wkLine[5];               //Total Amount
            string str7  = wkLine[6];               //Redac Division
            string str8  = wkLine[7];               //Parent Redac Division
            string str9  = wkLine[8];               //Tenant Name
            string str10 = wkLine[9];               //Company Name
            string str11 = wkLine[10];              //Street
            string str12 = wkLine[11];              //Street2
            string str13 = wkLine[12];              //Street3
            string str14 = wkLine[13];              //City
            string str15 = wkLine[14];              //US State
            string str16 = wkLine[15];              //ZIP/Postal code
            string str17 = wkLine[16];              //Country
            string str18 = wkLine[17];              //Main Phone
            string str19 = wkLine[18];              //Fax
            string str20 = wkLine[19];              //Email
            string str21 = wkLine[20];              //Purpose
            string str22 = wkLine[21];              //Amount
            string str23 = wkLine[22];              //Advance/Expense
            string str24 = wkLine[23];              //Payable to
            string str25 = wkLine[24];              //Payment Method
            string str26 = wkLine[25];              //Company ID
            string str27 = wkLine[26];              //Type
            string str28 = wkLine[27];              //CustomerGroup

            Console.WriteLine("account id : {0}", str26);
            DataServiceCollection <CustomerPostalAddress> customersCollection = new DataServiceCollection <CustomerPostalAddress>(context);
            CustomerPostalAddress myCustomer = new CustomerPostalAddress();

            customersCollection.Add(myCustomer);

            myCustomer.CustomerAccountNumber  = str26.Replace(",", "");
            myCustomer.CustomerLegalEntityId  = ConfigurationManager.AppSettings["RedacCompany"];
            myCustomer.AddressLocationRoles   = "Business";
            myCustomer.AddressDescription     = str2;
            myCustomer.AddressStreet          = str11 + " " + str12 + " " + str13;
            myCustomer.AddressCity            = str14;
            myCustomer.AddressState           = ConfigurationManager.AppSettings[str15];
            myCustomer.AddressZipCode         = str16;
            myCustomer.AddressCountryRegionId = str17.Length > 0 ? ConfigurationManager.AppSettings[str17] : "USA";
            myCustomer.IsPrimary = NoYes.No;

            DataServiceResponse response = null;

            try
            {
                response = context.SaveChanges(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithSingleChangeset);
                Console.WriteLine("added ok");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.InnerException);
            }
        }
        public async Task <IActionResult> DeleteEstablishment(string id)
        {
            // get the establishment.
            Guid adoxio_establishmetid = new Guid(id);

            try
            {
                Adoxio_establishment adoxioLegalEntity = await _system.Adoxio_establishments.ByKey(adoxio_establishmetid).GetValueAsync();

                _system.DeleteObject(adoxioLegalEntity);
                DataServiceResponse dsr = await _system.SaveChangesAsync();

                foreach (OperationResponse result in dsr)
                {
                    if (result.StatusCode == 500) // error
                    {
                        return(StatusCode(500, result.Error.Message));
                    }
                }
            }
            catch (Microsoft.OData.Client.DataServiceQueryException dsqe)
            {
                return(new NotFoundResult());
            }
            return(NoContent()); // 204
        }
        private void StartConfirmation()
        {
            CancelButton.Enabled  = false;
            ConfirmButton.Enabled = false;
            //open a progress alert
            ProgressAlert = UIAlertController.Create("Confirm Appointment", "Confirming appointment please wait...", UIAlertControllerStyle.Alert);
            PresentViewController(ProgressAlert, true, null);

            Task.Run(async() =>
            {
                DataServiceResponse <ConfirmationResponse> response = await ConfirmAppointmentAsync();
                if (response == null)
                {
                    ShowError(response);
                }
                else
                {
                    if (response.Success)
                    {
                        //refresh appointment data
                        ApplicationData.Current.GetClientAppointments();
                        //success
                        ShowSuccess(response);
                    }
                    else
                    {
                        //error
                        ShowError(response);
                    }
                }
            });
        }
        /// <summary>
        /// Verifies the data service response.
        /// </summary>
        /// <param name="responseData">The expected data for the response.</param>
        /// <param name="response">The response to verify.</param>
        /// <param name="cachedOperationsFromResponse">The individual operation responses, pre-enumerated and cached</param>
        /// <exception cref="TaupoNotSupportedException">
        /// When exception is expected in the response data 
        /// </exception>
        public void VerifyDataServiceResponse(DataServiceResponseData responseData, DataServiceResponse response, IList<OperationResponse> cachedOperationsFromResponse)
        {
            ExceptionUtilities.CheckArgumentNotNull(responseData, "responseData");
            ExceptionUtilities.CheckArgumentNotNull(response, "response");
            ExceptionUtilities.CheckArgumentNotNull(cachedOperationsFromResponse, "cachedOperationsFromResponse");
            ExceptionUtilities.CheckAllRequiredDependencies(this);

            this.Assert.AreEqual(responseData.IsBatchResponse, response.IsBatchResponse, "Verifying if it's a batch response.");
            this.Assert.AreEqual(responseData.BatchStatusCode, response.BatchStatusCode, "Verifying batch status code.");

            //// No batch headers verification
            //// Note: verifying order of operation responses as well as the content.

            this.Assert.AreEqual(responseData.Count, cachedOperationsFromResponse.Count, "Unexpected number of operation responses in data service response");

            for (int responseOrder = 0; responseOrder < responseData.Count; responseOrder++)
            {
                var operationResponseData = responseData[responseOrder];
                var currentResponse = cachedOperationsFromResponse[responseOrder];

                ChangeOperationResponseData changeResponseData = operationResponseData as ChangeOperationResponseData;
                if (changeResponseData != null)
                {
                    ChangeOperationResponse changeResponse = currentResponse as ChangeOperationResponse;
                    this.Assert.IsNotNull(changeResponse, GetVerificationFailureMessage(responseOrder, "Unexpected type of the operation response.\r\nExpected: {0}\r\nActual:   {1}", typeof(ChangeOperationResponse).FullName, currentResponse));

                    this.VerifyChangeOperationResponse(changeResponseData, changeResponse, responseOrder);
                }
                else
                {
                    throw new TaupoNotSupportedException(
                        GetVerificationFailureMessage(responseOrder, "Verification for the operation response data of type '{0}' is not supported by this verifier.", operationResponseData.GetType().FullName));
                }
            }
        }
Beispiel #15
0
        async static Task CreateCustomer(string name, Guid?label = null)
        {
            Console.WriteLine($"Create a new Customer: name={name}");
            Container context = GetContext();

            Customer newCustomer = new Customer
            {
                Name  = name,
                Label = label ?? Guid.Empty
            };

            context.AddToCustomers(newCustomer);

            DataServiceResponse responses = await context.SaveChangesAsync();

            foreach (var response in responses)
            {
                Console.WriteLine($"  StatusCode={response.StatusCode}");
            }

            Console.WriteLine();

            // List Customers
            await ListCustomers();
        }
        private async Task <DataServiceResponse <ConfirmationResponse> > ConfirmAppointmentAsync()
        {
            ScheduleDataSource  ds      = new ScheduleDataSource();
            Appointment         a       = ApplicationData.Current.NewAppointment;
            ConfirmationRequest request = new ConfirmationRequest()
            {
                AppointmentType       = a.AppointmentType.Value,
                AppointmentReason     = a.AppointmentSubType.Value,
                AppointmentSource     = Appointment.MOBILE_APP_SOURCE,
                AdvisorEmailAddress   = a.AdvisorEmail,
                AppointmentLanguage   = a.AppointmentLanguage,
                BranchNumber          = a.BranchNumber,
                ClientNumber          = ApplicationData.Current.Client.CustomerNumber,
                SendEmailConfirmation = true,
                StartTimeUtc          = a.StartDate.ToUniversalTime().ToString("o"),
                EndTimeUtc            = a.EndDate.ToUniversalTime().ToString("o"),
                IncludeIcsFile        = true,
                UiLanguageCode        = 1033,
                PreferredDateUtc      = a.StartDate.Date,
                AdvisorComments       = string.Empty,
                ClientComments        = string.Empty
            };
            DataServiceResponse <ConfirmationResponse> response = await ds.ConfirmAppointmentAsync(request);

            return(response);
        }
        public bool SaveSuspendedMessage(IFatpipeMessage message)
        {
            string location = "FpmDal->SaveSuspendedMessage";
            bool   result   = true;
            SuspendedMessageEntity suspendedMessage = null;

            //TODO remove the return statement
            // don't want any message to be suspended
            return(true);

            try
            {
                Stopwatch watch = Stopwatch.StartNew();
                suspendedMessage           = new SuspendedMessageEntity(message.Header.TenantIdentifier, message.Header.Identifier);
                suspendedMessage.Timestamp = DateTime.UtcNow;
                suspendedMessage.SuspendedMessageBlobReference = message.Header.Identifier;
                if (message.Status != null)
                {
                    suspendedMessage.ErrorMessage = string.Format(CultureInfo.InvariantCulture,
                                                                  "{0}. Message suspended after {1} retries. Error: {2}",
                                                                  message.Status.ProcessingResult,
                                                                  message.Status.NumberOfRetryAttempts,
                                                                  message.Status.ErrorDescription);
                }
                IOutboundFatpipeMessage outboundMessage = message as IOutboundFatpipeMessage;
                if (outboundMessage != null)
                {
                    if (outboundMessage.RoutingInfo != null)
                    {
                        suspendedMessage.PartnerIdentifier = outboundMessage.RoutingInfo.PartnerId;
                    }
                }

                this.suspendedTableServiceContext.AddObject(MaargConfiguration.Instance[MaargConfiguration.SuspendedMessageTableName], suspendedMessage);

                //save to suspended table and blob
                DataServiceResponse response = this.suspendedTableServiceContext.SaveChangesWithRetries();
                // The entry in the Q is the message blob name
                using (Stream stream = BizpipeMesssageStreaming.WriteBizpipeMessageToStream(message))
                {
                    CloudBlob blob = this.suspendedContainer.GetBlobReference(suspendedMessage.SuspendedMessageBlobReference);
                    blob.UploadFromStream(stream);
                }

                watch.Stop();
                LoggerFactory.Logger.Debug(location,
                                           "Message {0} saved to suspended queue in {1} ms.",
                                           message.Header.Identifier,
                                           watch.ElapsedMilliseconds);
            }
            catch (Exception exception)
            {
                LoggerFactory.Logger.Error(location, EventId.BizpipeSaveSuspendMessage
                                           , "Exception encountered during suspended message operation: {0}."
                                           , exception.ToString());
                result = false;
            }

            return(result);
        }
Beispiel #18
0
        protected override void UpdateDataObject(object dataContext, object table, object oldDataObject, object newDataObject)
        {
            var    dataServiceContext  = (DataServiceContext)dataContext;
            var    idataServiceContext = dataContext as IDataServiceContext;
            string etag = null;

            if (this._etagMap != null && this._etagMap.TryGetValue(DataServiceUtilities.BuildCompositeKey(oldDataObject), out etag))
            {
                if (idataServiceContext != null)
                {
                    idataServiceContext.AttachTo(TableName, newDataObject, etag);
                }
                else
                {
                    dataServiceContext.AttachTo(TableName, newDataObject, etag);
                }
            }
            else
            {
                if (idataServiceContext != null)
                {
                    idataServiceContext.AttachTo(TableName, newDataObject);
                }
                else
                {
                    dataServiceContext.AttachTo(TableName, newDataObject);
                }
            }

            ProcessForeignKeys(dataServiceContext, newDataObject, _values);

            dataServiceContext.UpdateObject(newDataObject);
            DataServiceResponse dataServiceResponse = dataServiceContext.SaveChanges();
        }
Beispiel #19
0
        public static void saveSurvey(Output output)
        {
            var outputWcf = new DbServices.Output
            {
            };

            try
            {
                db.AddToTableOutput(outputWcf);

                DataServiceResponse response = db.SaveChanges();
                foreach (ChangeOperationResponse change in response)
                {
                    EntityDescriptor descriptor = change.Descriptor as EntityDescriptor;

                    if (descriptor != null)
                    {
                        DbServices.Output added = descriptor.Entity as DbServices.Output;

                        if (added != null)
                        {
                            Console.WriteLine("Ankieta została zapisana");
                        }
                    }
                }
            }
            catch (DataServiceRequestException ex)
            {
                throw new ApplicationException(
                          "Wystąpił błąd podczas zapisu.", ex);
            }
        }
        public virtual void SendsIndividualErrorWhenOneOfTheRequestsFails()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            Default.Container client = new Default.Container(serviceUrl);
            client.Format.UseJson();

            Default.DefaultBatchCustomer validCustomer = new Default.DefaultBatchCustomer()
            {
                Id   = 10,
                Name = "Customer 10"
            };

            Default.DefaultBatchCustomer invalidCustomer = new Default.DefaultBatchCustomer()
            {
                Id   = -1,
                Name = "Customer -1"
            };

            client.AddToDefaultBatchCustomer(validCustomer);
            client.AddToDefaultBatchCustomer(invalidCustomer);
            DataServiceRequestException exception = Assert.Throws <DataServiceRequestException>(() =>
            {
                DataServiceResponse response = client.SaveChanges(SaveChangesOptions.Batch);
            });

            Assert.Equal(202, exception.Response.BatchStatusCode);
            Assert.Equal(1, exception.Response.Count());
        }
        public async Task <IActionResult> UpdateEstablishment([FromBody] ViewModels.AdoxioEstablishment item, string id)
        {
            if (id != item.id)
            {
                return(BadRequest());
            }
            // get the establishment.
            Guid adoxio_establishmetid = new Guid(id);
            DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Adoxio_establishment> AccountCollection = new DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Adoxio_establishment>(_system);

            Adoxio_establishment adoxioEstablishment = await _system.Adoxio_establishments.ByKey(adoxio_establishmetid).GetValueAsync();

            _system.UpdateObject(adoxioEstablishment);
            // copy values over from the data provided
            adoxioEstablishment.CopyValues(item);


            // PostOnlySetProperties is used so that settings such as owner will get set properly by the dynamics server.

            DataServiceResponse dsr = await _system.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithIndependentOperations);

            foreach (OperationResponse result in dsr)
            {
                if (result.StatusCode == 500) // error
                {
                    return(StatusCode(500, result.Error.Message));
                }
            }
            return(Json(adoxioEstablishment.ToViewModel()));
        }
Beispiel #22
0
        public Item AddItem(string prefix = "TEST")
        {
            Item item = CreateItem(GetNextValueItemCode(prefix), prefix);

            try
            {
                serviceContainer.AddToItems(item);
                DataServiceResponse response = serviceContainer.SaveChanges();
                if (response != null)
                {
                    ChangeOperationResponse opRes = (ChangeOperationResponse)response.SingleOrDefault();
                    object retItem = ((System.Data.Services.Client.EntityDescriptor)(opRes.Descriptor)).Entity;
                    if (retItem != null)
                    {
                        return((Item)retItem);
                    }
                }
            }
            catch (Exception ex)
            {
                serviceContainer.Detach(item);
                throw ex;
            }
            return(null);
        }
Beispiel #23
0
        public IList GetBatchObjects(string entityName, CriteriaOperator filter, Dictionary <string, string> properties)
        {
            DataServiceQuery query = CreateObjectQuery(entityName, filter, properties);

            DataServiceRequest[] batchRequests = new DataServiceRequest[] { query };
            DataServiceResponse  batchResponse = ServiceContext.ExecuteBatch(batchRequests);


            IList list = null;

            foreach (QueryOperationResponse response in batchResponse)
            {
                // Handle an error response.
                if (response.StatusCode > 299 || response.StatusCode < 200)
                {
                    Console.WriteLine("An error occurred.");
                    Console.WriteLine(response.Error.Message);
                }
                else
                {
                    foreach (var item in response)
                    {
                        if (list == null)
                        {
                            var listType = typeof(List <>).MakeGenericType(item.GetType());
                            list = Activator.CreateInstance(listType) as IList;
                        }
                        list.Add(item);
                    }
                }
            }

            return(list);
        }
Beispiel #24
0
        /// <summary>
        /// Verifies the data service response.
        /// </summary>
        /// <param name="responseData">The expected data for the response.</param>
        /// <param name="response">The response to verify.</param>
        /// <param name="cachedOperationsFromResponse">The individual operation responses, pre-enumerated and cached</param>
        /// <exception cref="TaupoNotSupportedException">
        /// When exception is expected in the response data
        /// </exception>
        public void VerifyDataServiceResponse(DataServiceResponseData responseData, DataServiceResponse response, IList <OperationResponse> cachedOperationsFromResponse)
        {
            ExceptionUtilities.CheckArgumentNotNull(responseData, "responseData");
            ExceptionUtilities.CheckArgumentNotNull(response, "response");
            ExceptionUtilities.CheckArgumentNotNull(cachedOperationsFromResponse, "cachedOperationsFromResponse");
            ExceptionUtilities.CheckAllRequiredDependencies(this);

            this.Assert.AreEqual(responseData.IsBatchResponse, response.IsBatchResponse, "Verifying if it's a batch response.");
            this.Assert.AreEqual(responseData.BatchStatusCode, response.BatchStatusCode, "Verifying batch status code.");

            //// No batch headers verification
            //// Note: verifying order of operation responses as well as the content.

            this.Assert.AreEqual(responseData.Count, cachedOperationsFromResponse.Count, "Unexpected number of operation responses in data service response");

            for (int responseOrder = 0; responseOrder < responseData.Count; responseOrder++)
            {
                var operationResponseData = responseData[responseOrder];
                var currentResponse       = cachedOperationsFromResponse[responseOrder];

                ChangeOperationResponseData changeResponseData = operationResponseData as ChangeOperationResponseData;
                if (changeResponseData != null)
                {
                    ChangeOperationResponse changeResponse = currentResponse as ChangeOperationResponse;
                    this.Assert.IsNotNull(changeResponse, GetVerificationFailureMessage(responseOrder, "Unexpected type of the operation response.\r\nExpected: {0}\r\nActual:   {1}", typeof(ChangeOperationResponse).FullName, currentResponse));

                    this.VerifyChangeOperationResponse(changeResponseData, changeResponse, responseOrder);
                }
                else
                {
                    throw new TaupoNotSupportedException(
                              GetVerificationFailureMessage(responseOrder, "Verification for the operation response data of type '{0}' is not supported by this verifier.", operationResponseData.GetType().FullName));
                }
            }
        }
Beispiel #25
0
        public void BatchInsertTask()
        {
            CloudTableClient    tableClient = GenerateCloudTableClient();
            TableServiceContext ctx         = tableClient.GetTableServiceContext();

            // Insert Entities
            SortedDictionary <string, ComplexEntity> entities = new SortedDictionary <string, ComplexEntity>();

            for (int i = 0; i < 100; i++)
            {
                ComplexEntity insertEntity = new ComplexEntity("insert test", "foo" + i);
                entities.Add(insertEntity.RowKey, insertEntity);
                ctx.AddObject(currentTable.Name, insertEntity);
            }

            DataServiceResponse response = ctx.SaveChangesWithRetriesAsync(SaveChangesOptions.Batch).Result;

            Assert.AreEqual((int)HttpStatusCode.Accepted, response.BatchStatusCode);

            // Retrieve Entities
            List <ComplexEntity> retrievedEntities = (from ent in ctx.CreateQuery <ComplexEntity>(currentTable.Name)
                                                      where ent.PartitionKey == entities.First().Value.PartitionKey
                                                      select ent).AsTableServiceQuery(ctx).Execute().ToList();

            Assert.AreEqual(entities.Count, retrievedEntities.Count);

            foreach (ComplexEntity retrievedEntity in retrievedEntities)
            {
                ComplexEntity.AssertEquality(entities[retrievedEntity.RowKey], retrievedEntity);
                entities.Remove(retrievedEntity.RowKey);
            }

            Assert.AreEqual(0, entities.Count);
        }
Beispiel #26
0
        public async Task SendsIndividualErrorWhenOneOfTheRequestsFails()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            DefaultBatchProxy.Container client = new DefaultBatchProxy.Container(serviceUrl);
            client.Format.UseJson();

            DefaultBatchProxy.DefaultBatchCustomer validCustomer = new DefaultBatchProxy.DefaultBatchCustomer()
            {
                Id   = 10,
                Name = "Customer 10"
            };

            DefaultBatchProxy.DefaultBatchCustomer invalidCustomer = new DefaultBatchProxy.DefaultBatchCustomer()
            {
                Id   = -1,
                Name = "Customer -1"
            };

            client.AddToDefaultBatchCustomer(validCustomer);
            client.AddToDefaultBatchCustomer(invalidCustomer);
            var exception = await Assert.ThrowsAsync <DataServiceRequestException>(async() =>
            {
                DataServiceResponse response = await client.SaveChangesAsync(SaveChangesOptions.BatchWithSingleChangeset);
            });

            Assert.NotNull(exception);
            Assert.Equal(200, exception.Response.BatchStatusCode);
            Assert.Single(exception.Response);
        }
        private static void OnPositionEstimatesSaved(IAsyncResult result)
        {
            bool errorOccured = false;

            radiomapEntities context = result.AsyncState as radiomapEntities;

            try
            {
                // Complete the save changes operation and display the response.
                DataServiceResponse response = context.EndSaveChanges(result);

                foreach (ChangeOperationResponse changeResponse in response)
                {
                    if (changeResponse.Error != null)
                    {
                        errorOccured = true;
                    }
                }
                if (!errorOccured)
                {
                    //Maybe raise success event?
                }
            }
            catch (Exception ex)
            {
                Exception exCopy = ex;
            }
        }
Beispiel #28
0
        public async Task CanBatchQueriesWithDataServicesClient()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            DefaultBatchProxy.Container client = new DefaultBatchProxy.Container(serviceUrl);
            client.Format.UseJson();
            Uri customersRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer");
            DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer> customersRequest = new DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer>(customersRequestUri);
            Uri singleCustomerRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer(0)");
            DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer> singleCustomerRequest = new DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer>(singleCustomerRequestUri);

            DataServiceResponse batchResponse = await client.ExecuteBatchAsync(customersRequest, singleCustomerRequest);

            if (batchResponse.IsBatchResponse)
            {
                Assert.Equal(200, batchResponse.BatchStatusCode);
            }

            foreach (QueryOperationResponse response in batchResponse)
            {
                Assert.Equal(200, response.StatusCode);
                if (response.Query.RequestUri == customersRequestUri)
                {
                    // Previous test could modify the total count to be anywhere from, 10 to 14.
                    Assert.InRange(response.Cast <DefaultBatchProxy.DefaultBatchCustomer>().Count(), 10, 14);
                    continue;
                }
                if (response.Query.RequestUri == singleCustomerRequestUri)
                {
                    Assert.Single(response.Cast <DefaultBatchProxy.DefaultBatchCustomer>());
                    continue;
                }
            }
        }
Beispiel #29
0
 private void PostTestWorkRespose(IAsyncResult asyncResult)
 {
     try
     {
         DataServiceContext  asynchConnector = asyncResult.AsyncState as DataServiceContext;
         DataServiceResponse response        = asynchConnector.EndSaveChanges(asyncResult);
         foreach (ChangeOperationResponse changset in response)
         {
             if (changset.Error != null)
             {
                 throw changset.Error;
             }
         }
         SignalUI("TestStatus", "Sent Response");
     }
     catch (Exception exception)
     {
         string wrongError = "The context is already tracking a different entity with the same resource Uri.";
         if (!exception.InnerException.Message.Contains(wrongError))
         {
             SignalUI("TestStatus", "Failed : " + exception.StackTrace.ToString());
             SignalUI("TestStatus", "Failed : " + exception.InnerException.StackTrace.ToString());
             DataServiceContext dsc      = GetServiceContext();
             Message            response = new Message();
             response.ReturnValue = exception.ToString();
             response.WhoSentMe   = "SL";
             dsc.AddObject("Messages", response);
             dsc.BeginSaveChanges(PostTestWorkRespose, dsc);
         }
     }
 }
        public void CanBatchQueriesWithDataServicesClient()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            Default.Container client = new Default.Container(serviceUrl);
            client.Format.UseJson();
            Uri customersRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer");
            DataServiceRequest <Default.DefaultBatchCustomer> customersRequest = new DataServiceRequest <Default.DefaultBatchCustomer>(customersRequestUri);
            Uri singleCustomerRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer(0)");
            DataServiceRequest <Default.DefaultBatchCustomer> singleCustomerRequest = new DataServiceRequest <Default.DefaultBatchCustomer>(singleCustomerRequestUri);

            DataServiceResponse batchResponse = client.ExecuteBatch(customersRequest, singleCustomerRequest);

            if (batchResponse.IsBatchResponse)
            {
                Assert.Equal(202, batchResponse.BatchStatusCode);
            }

            foreach (QueryOperationResponse response in batchResponse)
            {
                Assert.Equal(200, response.StatusCode);
                if (response.Query.RequestUri == customersRequestUri)
                {
                    Assert.Equal(10, response.Cast <Default.DefaultBatchCustomer>().Count());
                    continue;
                }
                if (response.Query.RequestUri == singleCustomerRequestUri)
                {
                    Assert.Equal(1, response.Cast <Default.DefaultBatchCustomer>().Count());
                    continue;
                }
            }
        }
Beispiel #31
0
            public void QueryFailureUsingExecuteBatch()
            {
                DataServiceRequest <northwindClient.Customers> request  = new DataServiceRequest <northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('QUICK')"));
                DataServiceRequest <northwindClient.Customers> request1 = new DataServiceRequest <northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('NONEXIST')"));
                DataServiceResponse response = ctx.ExecuteBatch(request, request1);

                Utils.IsBatchResponse(response);

                List <QueryOperationResponse> responses = new List <QueryOperationResponse>();

                foreach (QueryOperationResponse queryResponse in response)
                {
                    responses.Add(queryResponse);
                }

                Assert.IsTrue(responses.Count == 2, "expecting 2 responses in batch query");

                // first one to succeed
                Utils.IsSuccessResponse(responses[0], HttpStatusCode.OK);
                Assert.IsTrue(responses[0].Query == request, "expecting the same request object");

                // expecting the second one to fail
                Utils.IsErrorResponse(responses[1], HttpStatusCode.NotFound, true);
                Assert.IsTrue(responses[1].Query == request1, "expecting the same request object1");
            }
        /// <summary>
        /// Get User details by User Id.
        /// </summary>
        /// <param name="userId"> User Id. </param>
        /// <returns> User details. </returns>
        public DataServiceResponse<UserDto> GetUserDetailsById(int userId)
        {
            var responseUserDto = new DataServiceResponse<UserDto>();
            try
            {
                responseUserDto.Response = this.userRepository.GetUserById(userId);
                responseUserDto.Error = null;
            }
            catch (NullReferenceException nullReferenceException)
            {
                responseUserDto.Response = null;
                responseUserDto.Error = nullReferenceException;
            }

            return responseUserDto;
        }
        /// <summary>
        /// The add user.
        /// </summary>
        /// <param name="user"> The user. </param>
        /// <returns> The data service response </returns>
        public DataServiceResponse<int> AddUser(UserDto user)
        {
            var responseUserDto = new DataServiceResponse<int>();
            try
            {
                responseUserDto.Response = this.userRepository.AddUser(user);
                responseUserDto.Error = null;
            }
            catch (NullReferenceException nullReferenceException)
            {
                responseUserDto.Response = 0;
                responseUserDto.Error = nullReferenceException;
            }

            return responseUserDto;
        }
Beispiel #34
0
        /// <summary>
        /// process the batch response
        /// </summary>
        /// <param name="batchReader">The batch reader to use for reading the batch response.</param>
        /// <returns>an instance of the DataServiceResponse, containing individual operation responses for this batch request.</returns>
        /// <remarks>
        /// The message reader for the entire batch response is stored in the this.batchMessageReader.
        /// The message reader is disposable, but this method should not dispose it itself. It will be either disposed by the caller (in case of exception)
        /// or the ownership will be passed to the returned response object (in case of success).
        /// In could also be diposed indirectly by this method when it enumerates through the responses.
        /// </remarks>
        private DataServiceResponse HandleBatchResponseInternal(ODataBatchReader batchReader)
        {
            Debug.Assert(this.batchMessageReader != null, "this.batchMessageReader != null");
            Debug.Assert(batchReader != null, "batchReader != null");

            DataServiceResponse response;
            HeaderCollection headers = new HeaderCollection(this.batchResponseMessage);

            IEnumerable<OperationResponse> responses = this.HandleBatchResponse(batchReader);
            if (this.Queries != null)
            {
                // ExecuteBatch, EndExecuteBatch
                response = new DataServiceResponse(
                    headers,
                    (int)this.batchResponseMessage.StatusCode,
                    responses,
                    true /*batchResponse*/);
            }
            else
            {
                List<OperationResponse> operationResponses = new List<OperationResponse>();
                response = new DataServiceResponse(headers, (int)this.batchResponseMessage.StatusCode, operationResponses, true /*batchResponse*/);
                Exception exception = null;

                // SaveChanges, EndSaveChanges
                // enumerate the entire response
                foreach (ChangeOperationResponse changeOperationResponse in responses)
                {
                    operationResponses.Add(changeOperationResponse);
                    if (Util.IsBatchWithSingleChangeset(this.Options) && exception == null && changeOperationResponse.Error != null)
                    {
                        exception = changeOperationResponse.Error;
                    }

                    // Note that this will dispose the enumerator and this release the batch message reader which is owned
                    // by the enumerable of responses by now.
                }

                // Note that if we encounter any error in a batch request with a single changeset, 
                // we throw here since all change operations in the changeset are rolled back on the server.  
                // If we encounter any error in a batch request with independent operations, we don't want to throw 
                // since some of the operations might succeed. 
                // Users need to inspect each OperationResponse to get the exception information from the failed operations.
                if (exception != null)
                {
                    throw new DataServiceRequestException(Strings.DataServiceException_GeneralError, exception, response);
                }
            }

            return response;
        }
        /// <summary>
        /// 本方法用以显示 ADO.NET Data Service 返回的详细信息。
        /// </summary>
        /// <param name="response"></param>
        private void WriteOperationResponse(DataServiceResponse response)
        {
            messageTextBlock.Text = string.Empty;
            int i = 1;

            if (response.IsBatchResponse)
            {
                messageTextBlock.Text = string.Format("批处理返回状态码: {0}\n",
                    response.BatchStatusCode);
            }
            foreach (ChangeOperationResponse change in response)
            {
                messageTextBlock.Text +=
                    string.Format("\t更改 {0} 状态码: {1}\n",
                    i.ToString(), change.StatusCode.ToString());
                if (change.Error != null)
                {
                    string.Format("\t更改 {0} 错误: {1}\n",
                        i.ToString(), change.Error.Message);
                }
                i++;
            }
        }
Beispiel #36
0
        /// <summary>
        /// process the batch response
        /// </summary>
        /// <returns>an instance of the DataServiceResponse, containing individual operation responses for this batch request.</returns>
        private DataServiceResponse HandleBatchResponse()
        {
            bool batchMessageReaderOwned = true;

            try
            {
                if ((this.batchResponseMessage == null) || (this.batchResponseMessage.StatusCode == (int)HttpStatusCode.NoContent))
                {   // we always expect a response to our batch POST request
                    throw Error.InvalidOperation(Strings.Batch_ExpectedResponse(1));
                }

                Func<Stream> getResponseStream = () => this.ResponseStream;

                // We are not going to use the responseVersion returned from this call, as the $batch request itself doesn't apply versioning
                // of the responses on the root level. The responses are versioned on the part level. (Note that the version on the $batch level 
                // is actually used to version the batch itself, but we for now we only recognize a single version so to keep it backward compatible
                // we don't check this here. Also note that the HandleResponse method will verify that we can support the version, that is it's
                // lower than the highest version we understand).
                Version responseVersion;
                BaseSaveResult.HandleResponse(
                    this.RequestInfo,
                    (HttpStatusCode)this.batchResponseMessage.StatusCode,                      // statusCode
                    this.batchResponseMessage.GetHeader(XmlConstants.HttpODataVersion),  // responseVersion
                    getResponseStream,                                                  // getResponseStream
                    true,                                                               // throwOnFailure
                    out responseVersion);

                if (this.ResponseStream == null)
                {
                    Error.ThrowBatchExpectedResponse(InternalError.NullResponseStream);
                }

                // Create the message and the message reader.
                this.batchResponseMessage = new HttpWebResponseMessage(new HeaderCollection(this.batchResponseMessage), this.batchResponseMessage.StatusCode, getResponseStream);
                ODataMessageReaderSettings messageReaderSettings = this.RequestInfo.GetDeserializationInfo(/*mergeOption*/ null).ReadHelper.CreateSettings();

                // No need to pass in any model to the batch reader.
                this.batchMessageReader = new ODataMessageReader(this.batchResponseMessage, messageReaderSettings);
                ODataBatchReader batchReader;
                try
                {
                    batchReader = this.batchMessageReader.CreateODataBatchReader();
                }
                catch (ODataContentTypeException contentTypeException)
                {
                    string mime;
                    Encoding encoding;
                    Exception inner = contentTypeException;
                    ContentTypeUtil.ReadContentType(this.batchResponseMessage.GetHeader(XmlConstants.HttpContentType), out mime, out encoding);
                    if (String.Equals(XmlConstants.MimeTextPlain, mime))
                    {
                        inner = GetResponseText(
                            this.batchResponseMessage.GetStream,
                            (HttpStatusCode)this.batchResponseMessage.StatusCode);
                    }

                    throw Error.InvalidOperation(Strings.Batch_ExpectedContentType(this.batchResponseMessage.GetHeader(XmlConstants.HttpContentType)), inner);
                }

                DataServiceResponse response = this.HandleBatchResponseInternal(batchReader);

                // In case of successful processing of at least the beginning of the batch, the message reader is owned by the returned response
                // (or rather by the IEnumerable of operation responses inside it).
                // It will be disposed once the operation responses are enumerated (since the IEnumerator should be disposed once used).
                // In that case we must NOT dispose it here, since that enumeration can exist long after we return from this method.
                batchMessageReaderOwned = false;

                return response;
            }
            catch (DataServiceRequestException)
            {
                throw;
            }
            catch (InvalidOperationException ex)
            {
                HeaderCollection headers = new HeaderCollection(this.batchResponseMessage);
                int statusCode = this.batchResponseMessage == null ? (int)HttpStatusCode.InternalServerError : (int)this.batchResponseMessage.StatusCode;
                DataServiceResponse response = new DataServiceResponse(headers, statusCode, new OperationResponse[0], this.IsBatchRequest);
                throw new DataServiceRequestException(Strings.DataServiceException_GeneralError, ex, response);
            }
            finally
            {
                if (batchMessageReaderOwned)
                {
                    Util.Dispose(ref this.batchMessageReader);
                }
            }
        }
Beispiel #37
0
 protected override DataServiceResponse HandleResponse()
 {
     List<OperationResponse> list = new List<OperationResponse>((this.cachedResponses != null) ? this.cachedResponses.Count : 0);
     DataServiceResponse response = new DataServiceResponse(null, -1, list, false);
     Exception innerException = null;
     try
     {
         foreach (CachedResponse response2 in this.cachedResponses)
         {
             Descriptor descriptor = response2.Descriptor;
             base.SaveResultProcessed(descriptor);
             OperationResponse item = new ChangeOperationResponse(response2.Headers, descriptor) {
                 StatusCode = (int) response2.StatusCode
             };
             if (response2.Exception != null)
             {
                 item.Error = response2.Exception;
                 if (innerException == null)
                 {
                     innerException = response2.Exception;
                 }
             }
             else
             {
                 this.cachedResponse = response2;
                 base.HandleOperationResponse(descriptor, response2.Headers);
             }
             list.Add(item);
         }
     }
     catch (InvalidOperationException exception2)
     {
         innerException = exception2;
     }
     if (innerException != null)
     {
         throw new DataServiceRequestException(System.Data.Services.Client.Strings.DataServiceException_GeneralError, innerException, response);
     }
     return response;
 }
 public MediaDataServiceResponse(DataServiceResponse response)
 {
     _response = response;
 }
 public SaveChangesEventArgs(DataServiceResponse response)
 {
     this.response = response;
 }
 /// <summary>
 /// Creates a new instance of DataServiceRequestException.
 /// </summary>
 /// <param name="message">error message for this exception.</param>
 /// <param name="innerException">Exception that caused this exception to be thrown.</param>
 /// <param name="response">response object for this exception.</param>
 public DataServiceRequestException(string message, Exception innerException, DataServiceResponse response)
     : base(message, innerException)
 {
     this.response = response;
 }
Beispiel #41
0
 private DataServiceResponse HandleBatchResponse()
 {
     Func<Stream> func2 = null;
     Func<Stream> getResponseStream = null;
     DataServiceResponse response3;
     bool flag = true;
     try
     {
         Version version;
         ODataBatchReader reader;
         if ((base.batchResponse == null) || (base.batchResponse.StatusCode == HttpStatusCode.NoContent))
         {
             throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Batch_ExpectedResponse(1));
         }
         if (func2 == null)
         {
             func2 = () => this.ResponseStream;
         }
         Func<Stream> func = func2;
         BaseSaveResult.HandleResponse(base.RequestInfo, base.batchResponse.StatusCode, base.batchResponse.Headers["DataServiceVersion"], func, true, out version);
         if (this.ResponseStream == null)
         {
             System.Data.Services.Client.Error.ThrowBatchExpectedResponse(InternalError.NullResponseStream);
         }
         HttpWebResponseMessage responseMessage = new HttpWebResponseMessage(base.batchResponse, func);
         ODataMessageReaderSettings settings = WebUtil.CreateODataMessageReaderSettings(base.RequestInfo.GetDeserializationInfo(null), null, false);
         this.batchMessageReader = new ODataMessageReader(responseMessage, settings);
         try
         {
             reader = this.batchMessageReader.CreateODataBatchReader();
         }
         catch (Exception responseText)
         {
             string str;
             Encoding encoding;
             HttpProcessUtility.ReadContentType(base.batchResponse.ContentType, out str, out encoding);
             if (string.Equals("text/plain", str))
             {
                 if (getResponseStream == null)
                 {
                     getResponseStream = () => WebUtil.GetResponseStream(base.batchResponse, (DataServiceContext) base.Source);
                 }
                 responseText = BaseSaveResult.GetResponseText(getResponseStream, base.batchResponse.StatusCode);
             }
             throw System.Data.Services.Client.Error.InvalidOperation(System.Data.Services.Client.Strings.Batch_ExpectedContentType(base.batchResponse.ContentType), responseText);
         }
         DataServiceResponse response = this.HandleBatchResponseInternal(reader);
         flag = false;
         response3 = response;
     }
     catch (DataServiceRequestException)
     {
         throw;
     }
     catch (InvalidOperationException exception3)
     {
         Dictionary<string, string> headers = WebUtil.WrapResponseHeaders(base.batchResponse);
         int statusCode = (base.batchResponse == null) ? 500 : ((int) base.batchResponse.StatusCode);
         DataServiceResponse response2 = new DataServiceResponse(headers, statusCode, null, this.IsBatch);
         throw new DataServiceRequestException(System.Data.Services.Client.Strings.DataServiceException_GeneralError, exception3, response2);
     }
     finally
     {
         if (flag)
         {
             Util.Dispose<ODataMessageReader>(ref this.batchMessageReader);
         }
     }
     return response3;
 }
Beispiel #42
0
 private DataServiceResponse HandleBatchResponseInternal(ODataBatchReader batchReader)
 {
     Dictionary<string, string> headers = WebUtil.WrapResponseHeaders(base.batchResponse);
     IEnumerable<OperationResponse> enumerable = this.HandleBatchResponse(batchReader);
     if (this.Queries != null)
     {
         return new DataServiceResponse(headers, (int) base.batchResponse.StatusCode, enumerable, true);
     }
     List<OperationResponse> list = new List<OperationResponse>();
     DataServiceResponse response = new DataServiceResponse(headers, (int) base.batchResponse.StatusCode, list, true);
     Exception innerException = null;
     foreach (ChangeOperationResponse response2 in enumerable)
     {
         list.Add(response2);
         if ((innerException == null) && (response2.Error != null))
         {
             innerException = response2.Error;
         }
     }
     if (innerException != null)
     {
         throw new DataServiceRequestException(System.Data.Services.Client.Strings.DataServiceException_GeneralError, innerException, response);
     }
     return response;
 }
Beispiel #43
0
        /// <summary>
        /// Handle the response.
        /// </summary>
        /// <returns>an instance of the DataServiceResponse, containing individual responses for all the requests made during this SaveChanges call.</returns>
        protected override DataServiceResponse HandleResponse()
        {
            List<OperationResponse> responses = new List<OperationResponse>(this.cachedResponses != null ? this.cachedResponses.Count : 0);
            DataServiceResponse service = new DataServiceResponse(null, -1, responses, false /*isBatch*/);
            Exception ex = null;

            try
            {
                foreach (CachedResponse response in this.cachedResponses)
                {
                    Descriptor descriptor = response.Descriptor;
                    this.SaveResultProcessed(descriptor);
                    OperationResponse operationResponse = new ChangeOperationResponse(response.Headers, descriptor);
                    operationResponse.StatusCode = (int)response.StatusCode;
                    if (response.Exception != null)
                    {
                        operationResponse.Error = response.Exception;

                        if (ex == null)
                        {
                            ex = response.Exception;
                        }
                    }
                    else
                    {
                        this.cachedResponse = response;
#if DEBUG
                        this.HandleOperationResponse(descriptor, response.Headers, response.StatusCode);
#else
                        this.HandleOperationResponse(descriptor, response.Headers);
#endif
                    }

                    responses.Add(operationResponse);
                }
            }
            catch (InvalidOperationException e)
            {
                ex = e;
            }

            if (ex != null)
            {
                throw new DataServiceRequestException(Strings.DataServiceException_GeneralError, ex, service);
            }

            return service;
        }
        private DataServiceResponse ParseDataServiceResponse(DataServiceResponse resp, RequestResult reqResult, TableCommand<DataServiceResponse, DataServiceResponse> cmd)
        {
            if (reqResult.Exception != null)
            {
                throw reqResult.Exception;
            }

            return resp;
        }
 /// <summary>
 /// Extracts the replica session key header from the serviceResponse.
 /// </summary>
 /// <param name="response">Data service serviceResponse (query or changeResponse).</param>
 public void ProcessResponseHeader(DataServiceResponse response)
 {
     foreach (ChangeOperationResponse change in response)
     {
         ProcessResponseHeader(change);
     }
 }