public static Plan CreateBillingPlan(string name, string description, string baseUrl)
        {
            var returnUrl = baseUrl + "/Home/SubscribeSuccess";
            var cancelUrl = baseUrl + "/Home/SubscribeCancel";

            // Plan Details
            var plan = CreatePlanObject("Test Plan", "Plan for Tuts+", returnUrl, cancelUrl, 
                PlanInterval.Month, 1, (decimal)19.90, trial: true, trialLength: 1, trialPrice: 0);

            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Create plan
            plan = plan.Create(apiContext);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op = "replace",
                    path = "/",
                    value = new Plan() { state = "ACTIVE" }
                }
            };
            plan.Update(apiContext, patchRequest);

            return plan;
        }
        protected override void RunSample()
        {
            // ### Api Context
            // Pass in a `APIContext` object to authenticate 
            // the call and to send a unique request id 
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly. 
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = Configuration.GetAPIContext();

            // A resource representing a credit card that can be used to fund a payment.
            var card = new CreditCard()
            {
                expire_month = 11,
                expire_year = 2018,
                number = "4877274905927862",
                type = "visa"
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Create credit card", card);
            //--------------------
            #endregion

            // Creates the credit card as a resource in the PayPal vault. The response contains an 'id' that you can use to refer to it in the future payments.
            var createdCard = card.Create(apiContext);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(createdCard);
            //--------------------
            #endregion

            // Create a `PatchRequest` that will define the fields to be updated in the credit card resource.
            var patchRequest = new PatchRequest
            {
                new Patch
                {
                    op = "replace",
                    path = "/expire_month",
                    value = 12
                }
            };

            #region Track Workflow
            //--------------------
            this.flow.AddNewRequest("Update credit card", patchRequest);
            //--------------------
            #endregion

            // Update the credit card.
            var updatedCard = createdCard.Update(apiContext, patchRequest);

            #region Track Workflow
            //--------------------
            this.flow.RecordResponse(updatedCard);
            //--------------------
            #endregion
        }
Exemplo n.º 3
0
		public void CanConvertToAndFromJsonWithNestedPatchRequests()
		{
			var patch = new PatchRequest
							{
								Name = "Comments",
								Type = PatchCommandType.Modify,
								Position = 0,
								Nested = new[]
											 {
												 new PatchRequest
													 {
														 Name = "AuthorId",
														 Type = PatchCommandType.Set,
														 Value = "authors/456"
													 },
													new PatchRequest
													 {
														 Name = "AuthorName",
														 Type = PatchCommandType.Set,
														 Value = "Tolkien"
													 },
											 }
							};

			var jsonPatch = patch.ToJson();
			var backToPatch = PatchRequest.FromJson(jsonPatch);
			Assert.Equal(patch.Name, backToPatch.Name);
			Assert.Equal(patch.Nested.Length, backToPatch.Nested.Length);
		}		
Exemplo n.º 4
0
		public RavenJArray UpdateByIndex(string indexName, IndexQuery queryToUpdate, PatchRequest[] patchRequests, bool allowStale)
		{
			return PerformBulkOperation(indexName, queryToUpdate, allowStale, (docId, tx) =>
			{
				var patchResult = database.ApplyPatch(docId, null, patchRequests, tx);
				return new { Document = docId, Result = patchResult };
			});
		}
Exemplo n.º 5
0
		public RavenJObject Apply(PatchRequest[] patch)
		{
			foreach (var patchCmd in patch)
			{
				Apply(patchCmd);
			}
			return document;
		}
Exemplo n.º 6
0
 public HttpResponseMessage PatchUser(Int32 userId, PatchRequest<UserDto> patchRequest)
 {
     return GetUsersFromCache()
         .Bind(users => GetUserById(userId)
             .Bind(user => patchRequest.Patch(user))
             .Let(patchResult => UpdateUserCollection(users)))
         .ToHttpResponseMessage(Request, HttpStatusCode.NoContent);
 }
        public RavenJArray UpdateByIndex(string indexName, IndexQuery queryToUpdate, PatchRequest[] patchRequests, BulkOperationOptions options = null)
		{
            return PerformBulkOperation(indexName, queryToUpdate, options, (docId, tx) =>
			{
				var patchResult = database.Patches.ApplyPatch(docId, null, patchRequests, tx);
				return new { Document = docId, Result = patchResult };
			});
		}
Exemplo n.º 8
0
		private void RenameProperty(PatchRequest patchCmd, string propName, RavenJToken property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			if (property == null)
				return;

			document[patchCmd.Value.Value<string>()] = property;
			document.Remove(propName);
		}
Exemplo n.º 9
0
 public PatchResultData ApplyPatch(string docId, Etag etag, PatchRequest[] patchDoc,
                           TransactionInformation transactionInformation, bool debugMode = false)
 {
     if (docId == null)
         throw new ArgumentNullException("docId");
     return ApplyPatchInternal(docId, etag, transactionInformation,
                               jsonDoc => new JsonPatcher(jsonDoc.ToJson()).Apply(patchDoc),
                               () => null, () => null, debugMode);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Partially update the Payment resource for the given identifier
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="paymentId">ID of the payment to update.</param>
        /// <param name="patchRequest">PatchRequest</param>
        public static void Update(APIContext apiContext, string paymentId, PatchRequest patchRequest)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(paymentId, "paymentId");
            ArgumentValidator.Validate(patchRequest, "patchRequest");

            // Configure and send the request
            var pattern      = "v1/payments/payment/{0}";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { paymentId });

            PayPalResource.ConfigureAndExecute(apiContext, HttpMethod.PATCH, resourcePath, patchRequest.ConvertToJson());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Updates the Webhook identified by webhook_id for the application associated with access token.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="webhookId">ID of the webhook to be updated.</param>
        /// <param name="patchRequest">PatchRequest</param>
        /// <returns>Webhook</returns>
        public static Webhook Update(APIContext apiContext, string webhookId, PatchRequest patchRequest)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(webhookId, "webhookId");
            ArgumentValidator.Validate(patchRequest, "patchRequest");

            // Configure and send the request
            var pattern      = "v1/notifications/webhooks/{0}";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { webhookId });

            return(PayPalResource.ConfigureAndExecute <Webhook>(apiContext, HttpMethod.PATCH, resourcePath, patchRequest.ConvertToJson()));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Update information in a previously saved card. Only the modified fields need to be passed in the request.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="creditCardId">ID fo the credit card to update.</param>
        /// <param name="patchRequest">PatchRequest</param>
        /// <returns>CreditCard</returns>
        public static CreditCard Update(APIContext apiContext, string creditCardId, PatchRequest patchRequest)
        {
            // Validate the arguments to be used in the request
            ArgumentValidator.ValidateAndSetupAPIContext(apiContext);
            ArgumentValidator.Validate(creditCardId, "creditCardId");
            ArgumentValidator.Validate(patchRequest, "patchRequest");

            // Configure and send the request
            var pattern      = "v1/vault/credit-cards/{0}";
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { creditCardId });

            return(PayPalResource.ConfigureAndExecute <CreditCard>(apiContext, HttpMethod.PATCH, resourcePath, patchRequest.ConvertToJson()));
        }
Exemplo n.º 13
0
        public ActionResult Create(BillingPlan billingPlan)
        {
            if (ModelState.IsValid)
            {
                var apiContext = Common.GetApiContext();

                var plan = new Plan();
                plan.description = billingPlan.Description;
                plan.name = billingPlan.Name;
                plan.type = billingPlan.PlanType;

                plan.merchant_preferences = new MerchantPreferences
                {
                    initial_fail_amount_action = "CANCEL",
                    max_fail_attempts = "3",
                    cancel_url = "http://localhost:50728/plans",
                    return_url = "http://localhost:50728/plans"
                };

                plan.payment_definitions = new List<PaymentDefinition>();

                var paymentDefinition = new PaymentDefinition();
                paymentDefinition.name = "Standard Plan";
                paymentDefinition.amount = new Currency { currency = "USD", value = billingPlan.Amount.ToString() };
                paymentDefinition.frequency = billingPlan.Frequency.ToString();
                paymentDefinition.type = "REGULAR";
                paymentDefinition.frequency_interval = "1";

                if (billingPlan.NumberOfCycles.HasValue)
                {
                    paymentDefinition.cycles = billingPlan.NumberOfCycles.Value.ToString();
                }

                plan.payment_definitions.Add(paymentDefinition);

                var created = plan.Create(apiContext);

                if (created.state == "CREATED")
                {
                    var patchRequest = new PatchRequest();
                    patchRequest.Add(new Patch { path = "/", op = "replace", value = new Plan() { state = "ACTIVE" } });
                    created.Update(apiContext, patchRequest);
                }

                TempData["success"] = "Billing plan created.";
                return RedirectToAction("Index");
            }

            AddDropdowns();
            return View(billingPlan);
        }
Exemplo n.º 14
0
        public async Task PatchByIndex_WhenFinish_ShouldFreeInternalUsageMemory()
        {
            using (var store = GetDocumentStore())
            {
                var database = await GetDatabase(store.Database);

                var index = new IndexDefinition
                {
                    Name = "Users_ByName",
                    Maps = { "from user in docs.Users select new { user.Name }" },
                    Type = IndexType.Map
                };

                await store
                .Maintenance
                .SendAsync(new PutIndexesOperation(new[] { index }));

                using (var session = store.OpenAsyncSession())
                {
                    for (var i = 0; i < 100; i++)
                    {
                        await session.StoreAsync(new User { Name = "John" });
                    }
                    await session.SaveChangesAsync();
                }
                WaitForIndexing(store);

                using (var context = DocumentsOperationContext.ShortTermSingleUse(database))
                {
                    var query = new IndexQueryServerSide($"FROM index '{index.Name}'");
                    var patch = new PatchRequest("var u = this; u.is = true;", PatchRequestType.Patch, query.Metadata.DeclaredFunctions);

                    var before = context.AllocatedMemory;
                    await database.QueryRunner.ExecutePatchQuery(
                        query,
                        new QueryOperationOptions { RetrieveDetails = true },
                        patch,
                        query.QueryParameters,
                        context,
                        p => { },
                        new OperationCancelToken(CancelAfter, CancellationToken.None));

                    var after = context.AllocatedMemory;

                    //In a case of fragmentation, we don't immediately freeing memory so the memory can be a little bit higher
                    const long threshold = 256;
                    Assert.True(Math.Abs(before - after) < threshold);
                }
            }
        }
Exemplo n.º 15
0
        public void WebhookUpdateTest()
        {
            try
            {
                var webhook = WebhookTest.GetWebhook();
                webhook.url = "https://" + Guid.NewGuid().ToString() + ".com/paypal_webhooks";
                var createdWebhook = webhook.Create(TestingUtil.GetApiContext());

                var newUrl           = "https://update.com/paypal_webhooks/" + Guid.NewGuid().ToString();
                var newEventTypeName = "PAYMENT.SALE.REFUNDED";

                var patchRequest = new PatchRequest
                {
                    new Patch
                    {
                        op    = "replace",
                        path  = "/url",
                        value = newUrl
                    },
                    new Patch
                    {
                        op    = "replace",
                        path  = "/event_types",
                        value = new List <WebhookEventType>
                        {
                            new WebhookEventType
                            {
                                name = newEventTypeName
                            }
                        }
                    }
                };

                var updatedWebhook = createdWebhook.Update(TestingUtil.GetApiContext(), patchRequest);
                Assert.IsNotNull(updatedWebhook);
                Assert.AreEqual(createdWebhook.id, updatedWebhook.id);
                Assert.AreEqual(newUrl, updatedWebhook.url);
                Assert.IsNotNull(updatedWebhook.event_types);
                Assert.AreEqual(1, updatedWebhook.event_types.Count);
                Assert.AreEqual(newEventTypeName, updatedWebhook.event_types[0].name);

                // Cleanup
                updatedWebhook.Delete(TestingUtil.GetApiContext());
            }
            catch (ConnectionException ex)
            {
                TestingUtil.WriteConnectionExceptionDetails(ex);
                throw;
            }
        }
Exemplo n.º 16
0
        public Task PatchAsync(string id, PatchRequest patch, bool ignoreMissing)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (patch == null)
            {
                throw new ArgumentNullException(nameof(patch));
            }

            return(_commands.PatchAsync(id, new[] { patch }, ignoreMissing));
        }
        public void ModifyRequest_DefaultOptions()
        {
            var request = new PatchRequest(null, null, "bucket", "object");
            var options = new PatchObjectOptions();

            options.ModifyRequest(request);
            Assert.Null(request.Generation);
            Assert.Null(request.IfGenerationMatch);
            Assert.Null(request.IfGenerationNotMatch);
            Assert.Null(request.IfMetagenerationMatch);
            Assert.Null(request.IfMetagenerationNotMatch);
            Assert.Null(request.PredefinedAcl);
            Assert.Null(request.Projection);
        }
Exemplo n.º 18
0
        public Task <IList <string> > PatchAsync <T>(IRavenQueryable <T> query, PatchRequest patch, bool allowStale)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            if (patch == null)
            {
                throw new ArgumentNullException(nameof(patch));
            }

            return(PatchAsync(query, new[] { patch }, allowStale));
        }
Exemplo n.º 19
0
        public void CreditCardUpdateTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                var creditCard = GetCreditCard().Create(apiContext);
                this.RecordConnectionDetails();

                // Create a patch request to update the credit card.
                var patchRequest = new PatchRequest
                {
                    new Patch
                    {
                        op    = "replace",
                        path  = "/billing_address",
                        value = new Address
                        {
                            line1        = "111 First Street",
                            city         = "Saratoga",
                            country_code = "US",
                            state        = "CA",
                            postal_code  = "95070"
                        }
                    }
                };

                var updatedCreditCard = creditCard.Update(apiContext, patchRequest);
                this.RecordConnectionDetails();

                // Retrieve the credit card details from the vault and verify the
                // billing address was updated properly.
                var retrievedCreditCard = CreditCard.Get(apiContext, updatedCreditCard.id);
                this.RecordConnectionDetails();

                Assert.IsNotNull(retrievedCreditCard);
                Assert.IsNotNull(retrievedCreditCard.billing_address);
                Assert.AreEqual("111 First Street", retrievedCreditCard.billing_address.line1);
                Assert.AreEqual("Saratoga", retrievedCreditCard.billing_address.city);
                Assert.AreEqual("US", retrievedCreditCard.billing_address.country_code);
                Assert.AreEqual("CA", retrievedCreditCard.billing_address.state);
                Assert.AreEqual("95070", retrievedCreditCard.billing_address.postal_code);
            }
            catch (ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
Exemplo n.º 20
0
        public async Task PatchResult_ConstructResultData()
        {
            AddApplicationGridRouting();
            AddClusterComputeGridRouting();

            var siteModel = BuildModelForSingleCellPatch(HEIGHT_INCREMENT_0_5);

            var request = new PatchRequest();
            var result  = await request.ExecuteAndConvertToResult(SimplePatchRequestArgument(siteModel.ID));

            var bytes = result.ConstructResultData();

            bytes.Should().NotBeNull();
        }
Exemplo n.º 21
0
            public ScriptInput(Transformation transformation)
            {
                DefaultCollections = new HashSet <string>(transformation.Collections, StringComparer.OrdinalIgnoreCase);

                if (string.IsNullOrEmpty(transformation.Script))
                {
                    return;
                }

                Transformation = new PatchRequest(transformation.Script, PatchRequestType.RavenEtl);

                if (transformation.CollectionToLoadCounterBehaviorFunction != null)
                {
                    _collectionToLoadCounterBehaviorFunction = transformation.CollectionToLoadCounterBehaviorFunction;
                }

                if (transformation.CollectionToDeleteDocumentsBehaviorFunction != null)
                {
                    _collectionToDeleteDocumentBehaviorFunction = transformation.CollectionToDeleteDocumentsBehaviorFunction;
                }

                if (HasLoadCounterBehaviors || HasDeleteDocumentsBehaviors)
                {
                    BehaviorFunctions = new PatchRequest(transformation.Script, PatchRequestType.EtlBehaviorFunctions);
                }

                LoadToCollections = transformation.GetCollectionsFromScript();

                foreach (var collection in LoadToCollections)
                {
                    IdPrefixForCollection[collection] = DocumentConventions.DefaultTransformCollectionNameToDocumentIdPrefix(collection);
                }

                if (transformation.Collections == null)
                {
                    return;
                }

                _collectionNameComparisons = new Dictionary <string, Dictionary <string, bool> >(transformation.Collections.Count);

                foreach (var sourceCollection in transformation.Collections)
                {
                    _collectionNameComparisons[sourceCollection] = new Dictionary <string, bool>(transformation.Collections.Count);

                    foreach (var loadToCollection in LoadToCollections)
                    {
                        _collectionNameComparisons[sourceCollection][loadToCollection] = string.Compare(sourceCollection, loadToCollection, StringComparison.OrdinalIgnoreCase) == 0;
                    }
                }
            }
Exemplo n.º 22
0
        public async Task PatchRequest_Invalid_TRex_NoResult()
        {
            var projectId       = 999;
            var projectUid      = Guid.NewGuid();
            var bBox            = new BoundingBox2DGrid(1, 200, 10, 210);
            var mockConfigStore = new Mock <IConfigurationStore>();

            var filterResult = new FilterResult();

            filterResult.SetBoundary(new List <Point>()
            {
                new Point(bBox.BottomleftY, bBox.BottomLeftX),
                new Point(bBox.BottomleftY, bBox.TopRightX),
                new Point(bBox.TopRightY, bBox.TopRightX),
                new Point(bBox.TopRightY, bBox.BottomLeftX)
            });
            var patchRequest = new PatchRequest(
                projectId,
                projectUid,
                new Guid(),
                DisplayMode.Height,
                null,
                new LiftBuildSettings(),
                false,
                VolumesType.None,
                VelociraptorConstants.VOLUME_CHANGE_TOLERANCE,
                null, filterResult, null, FilterLayerMethod.AutoMapReset,
                0, 1000, true);

            patchRequest.Validate();

            var exception = new ServiceException(HttpStatusCode.InternalServerError,
                                                 new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError,
                                                                             $"Patch request failed somehow. ProjectUid: {projectUid}"));

            var tRexProxy = new Mock <ITRexCompactionDataProxy>();

            tRexProxy.Setup(x => x.SendDataPostRequestWithStreamResponse(It.IsAny <PatchDataRequest>(), "/patches", It.IsAny <IHeaderDictionary>()))
            .Throws(exception);

            var executor = RequestExecutorContainerFactory
                           .Build <PatchExecutor>(_logger, mockConfigStore.Object,
                                                  trexCompactionDataProxy: tRexProxy.Object);
            var result = await Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(patchRequest));

            result.Code.Should().Be(HttpStatusCode.InternalServerError);
            result.GetResult.Code.Should().Be(ContractExecutionStatesEnum.InternalProcessingError);
            result.GetResult.Message.Should().Be(exception.GetResult.Message);
        }
Exemplo n.º 23
0
        public async Task Patch()
        {
            var layer = new SalesforceLayer <MyContact>(_forceClient, new MyContactObjectDescriptor());

            var contact = new MyContact
            {
                Forename   = Guid.NewGuid().ToString(),
                Surname    = Guid.NewGuid().ToString(),
                Street     = Guid.NewGuid().ToString(),
                City       = "Glasgow",
                Country    = "United Kingdom",
                PostalCode = "G12AB",
                CanEmail   = true
            };

            var postBasket = new PostBasket <MyContact, string>(contact);
            await layer.AddResultAsync(postBasket, new Visit("Post", VisitDirections.Down)).ConfigureAwait(false);

            var id = postBasket.AscentPayload;

            Assert.False(string.IsNullOrWhiteSpace(id));

            var patchRequest = new PatchRequest <string, MyContact>(
                new Delta <string, MyContact>(id, new Dictionary <string, object>
            {
                { nameof(MyContact.Forename), "Jimmy" },
                { nameof(MyContact.Surname), "Riddle" }
            }));
            var patchBasket = new PatchBasket <string, MyContact, int>(patchRequest);
            await layer.AddResultAsync(patchBasket, new Visit("Patch", VisitDirections.Down)).ConfigureAwait(false);

            Assert.Equal(1, patchBasket.AscentPayload);

            var getBasket = new GetBasket <string, MyContact>(id);
            await layer.AddResultAsync(getBasket, new Visit("Get", VisitDirections.Down)).ConfigureAwait(false);

            var readContact = getBasket.AscentPayload;

            Assert.Equal(id, readContact.Id);
            Assert.Equal("Jimmy", readContact.Forename);
            Assert.Equal("Riddle", readContact.Surname);
            Assert.Equal(contact.Street, readContact.Street);
            Assert.Equal(contact.City, readContact.City);
            Assert.Equal(contact.Country, readContact.Country);
            Assert.Equal(contact.PostalCode, readContact.PostalCode);
            Assert.Equal(contact.CanMailshot, readContact.CanMailshot);
            Assert.Equal(contact.CanEmail, readContact.CanEmail);
            Assert.Equal(contact.CanPhone, readContact.CanPhone);
        }
Exemplo n.º 24
0
        private uint ConvertColor(PatchRequest request, float elevationOffsetDelta)
        {
            if (request.RenderColorValues && Math.Abs(elevationOffsetDelta - CONST_MIN_ELEVATION) > 0.001)
            {
                for (var i = request.Palettes.Count - 1; i >= 0; i--)
                {
                    if (elevationOffsetDelta >= request.Palettes[i].Value)
                    {
                        return(request.Palettes[i].Color);
                    }
                }
            }

            return((uint)Color.Empty.ToArgb());
        }
Exemplo n.º 25
0
        public PatchByIndexCommand CreateRequest(string indexName, IndexQuery queryToUpdate, QueryOperationOptions options,
                                                 PatchRequest patch, DocumentStore documentStore)
        {
            var entityToBlittable = new EntityToBlittable(null);
            var requestData       = entityToBlittable.ConvertEntityToBlittable(patch, documentStore.Conventions, _context);

            return(new PatchByIndexCommand()
            {
                Script = requestData,
                IndexName = indexName,
                QueryToUpdate = queryToUpdate,
                Options = options,
                Context = _context
            });
        }
Exemplo n.º 26
0
		public void CanConvertToAndFromJsonWithEmptyNestedPatchRequests()
		{
			var patch = new PatchRequest
							{
								Name = "Comments",
								Type = PatchCommandType.Modify,
								Position = 0,
								Nested = new PatchRequest[] { }
							};

			var jsonPatch = patch.ToJson();
			var backToPatch = PatchRequest.FromJson(jsonPatch);
			Assert.Equal(patch.Name, backToPatch.Name);
			Assert.Equal(patch.Nested.Length, backToPatch.Nested.Length);
		}
Exemplo n.º 27
0
        public JsPatch(string patchScript, DocumentsOperationContext context)
        {
            if (string.IsNullOrWhiteSpace(patchScript))
            {
                return;
            }

            _context = context;

            var req = new PatchRequest(patchScript, PatchRequestType.None);

            _context.DocumentDatabase.Scripts.GetScriptRunner(req, true, out _runner);

            _hasScript = true;
        }
Exemplo n.º 28
0
        public void AgreementCreateTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                // Create a new plan.
                var plan        = PlanTest.GetPlan();
                var createdPlan = plan.Create(apiContext);
                this.RecordConnectionDetails();

                // Activate the plan.
                var patchRequest = new PatchRequest()
                {
                    new Patch()
                    {
                        op    = "replace",
                        path  = "/",
                        value = new Plan()
                        {
                            state = "ACTIVE"
                        }
                    }
                };
                createdPlan.Update(apiContext, patchRequest);
                this.RecordConnectionDetails();

                // Create an agreement using the activated plan.
                var agreement = GetAgreement();
                agreement.plan = new Plan()
                {
                    id = createdPlan.id
                };
                agreement.shipping_address = null;
                var createdAgreement = agreement.Create(apiContext);
                this.RecordConnectionDetails();

                Assert.Null(createdAgreement.id);
                Assert.NotNull(createdAgreement.token);
                Assert.Equal(agreement.name, createdAgreement.name);
            }
            catch (ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // In order to update the plan, you must define one or more
                // patches to be applied to the plan. The patches will be
                // applied in the order in which they're specified.
                //
                // The 'value' of each Patch object will need to be a Plan object
                // that contains the fields that will be modified.
                // More Information: https://developer.paypal.com/webapps/developer/docs/api/#patchrequest-object
                var tempPlan = new Plan();
                tempPlan.description = "Some updated description (" + Guid.NewGuid().ToString() + ").";

                // NOTE: Only the 'replace' operation is supported when updating
                //       billing plans.
                var patch = new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = tempPlan
                };
                var patchRequest = new PatchRequest();
                patchRequest.Add(patch);

                HttpContext.Current.Items.Add("RequestJson", Common.FormatJsonString(patchRequest.ConvertToJson()));

                // Get the plan we want to update.
                var apiContext = Configuration.GetAPIContext();
                var planId     = "P-23P27073KJ353233VHEXQM4Y";
                var plan       = Plan.Get(apiContext, planId);

                // Update the plan.
                plan.Update(apiContext, patchRequest);

                // After it's been updated, get it again to make sure it was updated properly (and so we can see what it looks like afterwards).
                var updatedPlan = Plan.Get(apiContext, planId);

                HttpContext.Current.Items.Add("ResponseTitle", "Updated Billing Plan Details");
                HttpContext.Current.Items.Add("ResponseJson", Common.FormatJsonString(updatedPlan.ConvertToJson()));
            }
            catch (Exception ex)
            {
                HttpContext.Current.Items.Add("Error", ex.Message);
            }

            Server.Transfer("~/Response.aspx");
        }
Exemplo n.º 30
0
        public static void ActivatePlan(Plan plan)
        {
            var apiContext = GetApiContext();

            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = "/",
                    value = plan.state = "ACTIVE"
                }
            };

            plan.Update(apiContext, patchRequest);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Deletes the specified billing plan.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="planId">ID of the billing plan to delete.</param>
        public static void Delete(APIContext apiContext, string planId)
        {
            var patchRequest = new PatchRequest
            {
                new Patch
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan {
                        state = "DELETED"
                    }
                }
            };

            Plan.Update(apiContext, planId, patchRequest);
        }
Exemplo n.º 32
0
        public void CanConvertToAndFromJsonWithEmptyNestedPatchRequests()
        {
            var patch = new PatchRequest
            {
                Name     = "Comments",
                Type     = PatchCommandType.Modify,
                Position = 0,
                Nested   = new PatchRequest[] { }
            };

            var jsonPatch   = patch.ToJson();
            var backToPatch = PatchRequest.FromJson(jsonPatch);

            Assert.Equal(patch.Name, backToPatch.Name);
            Assert.Equal(patch.Nested.Length, backToPatch.Nested.Length);
        }
Exemplo n.º 33
0
        public async Task SerializeAndDeserialize_PatchDocumentCommandTest()
        {
            using (var database = CreateDocumentDatabase())
                using (database.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                {
                    //Arrange
                    var data         = new { ParentProperty = new { NestedProperty = "Some Value" } };
                    var arg          = DocumentConventions.Default.Serialization.DefaultConverter.ToBlittable(data, context);
                    var patchRequest = new PatchRequest("", PatchRequestType.None);

                    var expected = new PatchDocumentCommand(
                        context,
                        "Some Id",
                        context.GetLazyString("Some Lazy String"),
                        false,
                        (patchRequest, arg),
                        (null, null),
                        null,
                        database,
                        false, false, false, false);

                    //Action
                    var jsonSerializer = GetJsonSerializer();
                    BlittableJsonReaderObject blitCommand;
                    using (var writer = new BlittableJsonWriter(context))
                    {
                        var dto = expected.ToDto(context);
                        jsonSerializer.Serialize(writer, dto);
                        writer.FinalizeDocument();

                        blitCommand = writer.CreateReader();
                    }
                    var fromStream = await SerializeTestHelper.SimulateSavingToFileAndLoadingAsync(context, blitCommand);

                    PatchDocumentCommand actual;
                    using (var reader = new BlittableJsonReader(context))
                    {
                        reader.Initialize(fromStream);

                        var dto = jsonSerializer.Deserialize <PatchDocumentCommandDto>(reader);
                        actual = dto.ToCommand(context, database);
                    }

                    //Assert
                    Assert.Equal(expected, actual, new CustomComparer <PatchDocumentCommand>(context));
                }
        }
Exemplo n.º 34
0
        // https://docs.microsoft.com/en-us/rest/api/vsts/wit/WorkItemBatchUpdate?view=vsts-rest-4.1
        private static string HttpContentComposer()
        {
            // Update request No. 1, with 2 operations
            UpdateOperation updateOperation1 = new UpdateOperation(
                UpdateOperation.OPERATION_NAME_ADD,
                "/fields/MicrosoftTeamsCMMI.GPMOwner",
                "*****@*****.**"
                );
            UpdateOperation updateOperation2 = new UpdateOperation(
                UpdateOperation.OPERATION_NAME_ADD,
                "/fields/MicrosoftTeamsCMMI.GEMOwner",
                "*****@*****.**"
                );
            List <UpdateOperation> updateOperations1 = new List <UpdateOperation>();

            updateOperations1.Add(updateOperation1);
            updateOperations1.Add(updateOperation2);
            PatchRequest patchRequest1 = new PatchRequest(289194, updateOperations1);

            // Update request No. 1, with 2 operations
            UpdateOperation updateOperation3 = new UpdateOperation(
                UpdateOperation.OPERATION_NAME_ADD,
                "/fields/MicrosoftTeamsCMMI.GPMOwner",
                "*****@*****.**"
                );
            UpdateOperation updateOperation4 = new UpdateOperation(
                UpdateOperation.OPERATION_NAME_ADD,
                "/fields/MicrosoftTeamsCMMI.GEMOwner",
                "*****@*****.**"
                );
            List <UpdateOperation> updateOperations2 = new List <UpdateOperation>();

            updateOperations2.Add(updateOperation1);
            updateOperations2.Add(updateOperation2);
            PatchRequest patchRequest2 = new PatchRequest(289192, updateOperations2);

            List <PatchRequest> patchRequests = new List <PatchRequest>();

            patchRequests.Add(patchRequest1);
            patchRequests.Add(patchRequest2);

            string output = JsonConvert.SerializeObject(patchRequests);

            Console.WriteLine(output);

            return(output);
        }
Exemplo n.º 35
0
        internal void ModifyRequest(PatchRequest request)
        {
            // Note the use of ArgumentException here, as this will basically be the result of invalid
            // options being passed to a public method.
            if (IfGenerationMatch != null && IfGenerationNotMatch != null)
            {
                throw new ArgumentException($"Cannot specify {nameof(IfGenerationMatch)} and {nameof(IfGenerationNotMatch)} in the same options", "options");
            }
            if (IfMetagenerationMatch != null && IfMetagenerationNotMatch != null)
            {
                throw new ArgumentException($"Cannot specify {nameof(IfMetagenerationMatch)} and {nameof(IfMetagenerationNotMatch)} in the same options", "options");
            }

            if (Generation != null)
            {
                request.Generation = Generation;
            }
            if (IfGenerationMatch != null)
            {
                request.IfGenerationMatch = IfGenerationMatch;
            }
            if (IfGenerationNotMatch != null)
            {
                request.IfGenerationNotMatch = IfGenerationNotMatch;
            }
            if (IfMetagenerationMatch != null)
            {
                request.IfMetagenerationMatch = IfMetagenerationMatch;
            }
            if (IfMetagenerationNotMatch != null)
            {
                request.IfMetagenerationNotMatch = IfMetagenerationNotMatch;
            }
            if (Projection != null)
            {
                request.Projection = GaxPreconditions.CheckEnumValue((ProjectionEnum)Projection, nameof(Projection));
            }
            if (PredefinedAcl != null)
            {
                request.PredefinedAcl =
                    GaxPreconditions.CheckEnumValue((PredefinedAclEnum)PredefinedAcl, nameof(PredefinedAcl));
            }
            if (UserProject != null)
            {
                request.UserProject = UserProject;
            }
        }
Exemplo n.º 36
0
        public void Patch <T, U>(string id, Expression <Func <T, U> > path, U value)
        {
            var pathScript = path.CompileToJavascript(_javascriptCompilationOptions);

            var patchRequest = new PatchRequest
            {
                Script = $"this.{pathScript} = args.val_{_valsCount};",
                Values = { [$"val_{_valsCount}"] = value }
            };

            _valsCount++;

            if (TryMergePatches(id, patchRequest) == false)
            {
                Defer(new PatchCommandData(id, null, patchRequest, null));
            }
        }
Exemplo n.º 37
0
        public void Increment <T, U>(string id, Expression <Func <T, U> > path, U valToAdd)
        {
            var pathScript = path.CompileToJavascript();

            var patchRequest = new PatchRequest
            {
                Script = $"this.{pathScript} += args.val_{_valsCount};",
                Values = { [$"val_{_valsCount}"] = valToAdd }
            };

            _valsCount++;

            if (TryMergePatches(id, patchRequest) == false)
            {
                Advanced.Defer(new PatchCommandData(id, null, patchRequest, null));
            }
        }
Exemplo n.º 38
0
        public async Task Test_PatchRequest_Execute_SingleCellSiteModel()
        {
            AddApplicationGridRouting();
            AddClusterComputeGridRouting();

            var siteModel = BuildModelForSingleCellPatch(HEIGHT_INCREMENT_0_5);

            var request  = new PatchRequest();
            var response = await request.ExecuteAsync(SimplePatchRequestArgument(siteModel.ID));

            response.Should().NotBeNull();
            response.SubGrids.Should().NotBeNull();
            response.SubGrids.Count.Should().Be(1);
            response.SubGrids[0].CountNonNullCells().Should().Be(1);
            response.SubGrids[0].Should().BeOfType <ClientHeightAndTimeLeafSubGrid>();
            ((ClientHeightAndTimeLeafSubGrid)response.SubGrids[0]).Cells[0, 0].Should().BeApproximately(5.5f, 0.000001f);
        }
Exemplo n.º 39
0
        public async Task ExecuteAndConvertToResult()
        {
            AddApplicationGridRouting();
            AddClusterComputeGridRouting();

            var siteModel = BuildModelForSingleCellPatch(HEIGHT_INCREMENT_0_5);

            var request = new PatchRequest();
            var result  = await request.ExecuteAndConvertToResult(SimplePatchRequestArgument(siteModel.ID));

            result.Should().NotBeNull();
            result.Patch.Should().NotBeNull();
            result.Patch.Length.Should().Be(1);

            result.Patch[0].ElevationOrigin.Should().Be(5.5f);
            result.Patch[0].Data[0, 0].ElevationOffset.Should().Be(0);
        }
Exemplo n.º 40
0
        public void Test()
        {
            InvitationRequest request = new InvitationRequest(1111);

            this.TestFactory(request);

            InvitationAck ack = new InvitationAck(2222);

            this.TestFactory(ack);

            byte[]           data         = { 12, 34, 56 };
            FileDataResponse dataResponse = new FileDataResponse(data, 3333);

            this.TestFactory(dataResponse);

            FileEvent e1 = new FileEvent();

            e1.Name = "1234";
            List <FileEvent> lf = new List <FileEvent>();

            lf.Add(e1);
            PatchRequest patchRequest = new PatchRequest(lf, 4444);

            this.TestFactory(patchRequest);

            PeerList peerList = PeerList.GetPeerList("abc");

            peerList.AddPeer(new Peer("127.0.0.1", 5555));
            PeerListMessage pm = new PeerListMessage(peerList, 6666);

            this.TestFactory(pm);

            SyncAck syncAck = new SyncAck(7777);

            this.TestFactory(syncAck);

            SyncRequest syncRequest = new SyncRequest(8888);

            this.TestFactory(syncRequest);

            File.WriteAllText(".Distribox/VersionList.txt", "[]");
            VersionList        vl = new VersionList();
            VersionListMessage vm = new VersionListMessage(vl, 9999);

            this.TestFactory(vm);
        }
Exemplo n.º 41
0
		private void Apply(PatchRequest patchCmd)
		{
			if (patchCmd.Name == null)
				throw new InvalidOperationException("Patch property must have a name property");
			foreach (var result in document.SelectTokenWithRavenSyntaxReturningFlatStructure( patchCmd.Name ))
			{
			    var token = result.Item1;
			    var parent = result.Item2;
				switch (patchCmd.Type)
				{
					case PatchCommandType.Set:
						SetProperty(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Unset:
						RemoveProperty(patchCmd, patchCmd.Name, token, parent);
						break;
					case PatchCommandType.Add:
						AddValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Insert:
						InsertValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Remove:
						RemoveValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Modify:
                        // create snapshot of property 
                        token.EnsureCannotBeChangeAndEnableSnapshotting();    
				        token = token.CreateSnapshot();
				        document[patchCmd.Name] = token;
						ModifyValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Inc:
						IncrementProperty(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Copy:
						CopyProperty(patchCmd, token);
						break;
					case PatchCommandType.Rename:
						RenameProperty(patchCmd, patchCmd.Name, token);
						break;
					default:
						throw new ArgumentException(string.Format("Cannot understand command: '{0}'", patchCmd.Type));
				}
			}
		}
Exemplo n.º 42
0
        public void PlanUpdateTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                // Get a test plan for updating purposes.
                var plan        = GetPlan();
                var createdPlan = plan.Create(apiContext);
                this.RecordConnectionDetails();

                var planId = createdPlan.id;

                // Create the patch request and update the description to a random value.
                var updatedDescription = Guid.NewGuid().ToString();
                var patch = new Patch
                {
                    op    = "replace",
                    path  = "/",
                    value = new Plan {
                        description = updatedDescription
                    }
                };

                var patchRequest = new PatchRequest {
                    patch
                };

                // Update the plan.
                createdPlan.Update(apiContext, patchRequest);
                this.RecordConnectionDetails();

                // Verify the plan was updated successfully.
                var updatedPlan = Plan.Get(apiContext, planId);
                this.RecordConnectionDetails();

                Assert.AreEqual(planId, updatedPlan.id);
                Assert.AreEqual(updatedDescription, updatedPlan.description);
            }
            catch (ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
Exemplo n.º 43
0
        public PatchResultData ApplyPatch(string docId, Etag etag,
                                          PatchRequest[] patchExistingDoc, PatchRequest[] patchDefaultDoc, RavenJObject defaultMetadata,
                                          TransactionInformation transactionInformation, bool debugMode = false)
        {
            if (docId == null)
                throw new ArgumentNullException("docId");
            return ApplyPatchInternal(docId, etag, transactionInformation,
                                      jsonDoc => new JsonPatcher(jsonDoc.ToJson()).Apply(patchExistingDoc),
                                      () =>
                                      {
                                          if (patchDefaultDoc == null || patchDefaultDoc.Length == 0)
                                              return null;

                                          var jsonDoc = new RavenJObject();
                                          jsonDoc[Constants.Metadata] = defaultMetadata ?? new RavenJObject();
                                          return new JsonPatcher(jsonDoc).Apply(patchDefaultDoc);
                                      },
                                      () => null, debugMode);
        }
Exemplo n.º 44
0
		private void Apply(PatchRequest patchCmd)
		{
			if (patchCmd.Name == null)
				throw new InvalidOperationException("Patch property must have a name property");
			foreach (var result in document.SelectTokenWithRavenSyntaxReturningFlatStructure( patchCmd.Name ))
			{
			    var token = result.Item1;
			    var parent = result.Item2;
				switch (patchCmd.Type)
				{
					case PatchCommandType.Set:
						SetProperty(patchCmd, patchCmd.Name, token as RavenJValue);
						break;
					case PatchCommandType.Unset:
                        RemoveProperty(patchCmd, patchCmd.Name, token, parent);
						break;
					case PatchCommandType.Add:
						AddValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Insert:
						InsertValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Remove:
						RemoveValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Modify:
						ModifyValue(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Inc:
						IncrementProperty(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Copy:
						CopyProperty(patchCmd, patchCmd.Name, token);
						break;
					case PatchCommandType.Rename:
						RenameProperty(patchCmd, patchCmd.Name, token);
						break;
					default:
						throw new ArgumentException("Cannot understand command: " + patchCmd.Type);
				}
			}
		}
Exemplo n.º 45
0
        public void AgreementCreateTest()
        {
            try
            {
                var apiContext = TestingUtil.GetApiContext();
                this.RecordConnectionDetails();

                // Create a new plan.
                var plan = PlanTest.GetPlan();
                var createdPlan = plan.Create(apiContext);
                this.RecordConnectionDetails();

                // Activate the plan.
                var patchRequest = new PatchRequest()
                {
                    new Patch()
                    {
                        op = "replace",
                        path = "/",
                        value = new Plan() { state = "ACTIVE" }
                    }
                };
                createdPlan.Update(apiContext, patchRequest);
                this.RecordConnectionDetails();

                // Create an agreement using the activated plan.
                var agreement = GetAgreement();
                agreement.plan = new Plan() { id = createdPlan.id };
                agreement.shipping_address = null;
                var createdAgreement = agreement.Create(apiContext);
                this.RecordConnectionDetails();

                Assert.IsNull(createdAgreement.id);
                Assert.IsNotNull(createdAgreement.token);
                Assert.AreEqual(agreement.name, createdAgreement.name);
            }
            catch(ConnectionException)
            {
                this.RecordConnectionDetails(false);
                throw;
            }
        }
        public static void UpdateBillingPlan(string planId, string path, object value)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfiguration.GetAPIContext();

            // Retrieve Plan
            var plan = Plan.Get(apiContext, planId);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op = "replace", // Only the 'replace' operation is supported when updating billing plans.
                    path = path,
                    value = value
                }
            };
            plan.Update(apiContext, patchRequest);
        }
Exemplo n.º 47
0
        public ActionResult Activate(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var apiContext = Common.GetApiContext();
                var plan = Plan.Get(apiContext, id);
                if (plan != null && plan.state == "CREATED")
                {
                    var patchRequest = new PatchRequest();
                    var tempPlan = new Plan();
                    tempPlan.state = "ACTIVE";
                    patchRequest.Add(new Patch { path = "/", op = "replace", value = tempPlan });
                    plan.Update(apiContext, patchRequest);

                    TempData["success"] = "Plan activated";
                }
            }

            return RedirectToAction("Index");
        }
Exemplo n.º 48
0
        public void AgreementUpdateTest()
        {
            // Get the agreement to be used for verifying the update functionality
            var apiContext = TestingUtil.GetApiContext();
            var agreementId = "I-HP4H4YJFCN07";
            var agreement = Agreement.Get(apiContext, agreementId);

            // Create an update for the agreement
            var updatedDescription = Guid.NewGuid().ToString();
            var patch = new Patch();
            patch.op = "replace";
            patch.path = "/";
            patch.value = new Agreement() { description = updatedDescription };
            var patchRequest = new PatchRequest();
            patchRequest.Add(patch);

            // Update the agreement
            agreement.Update(apiContext, patchRequest);

            // Verify the agreement was successfully updated
            var updatedAgreement = Agreement.Get(apiContext, agreementId);
            Assert.AreEqual(agreementId, updatedAgreement.id);
            Assert.AreEqual(updatedDescription, updatedAgreement.description);
        }
Exemplo n.º 49
0
		private void IncrementProperty(PatchRequest patchCmd, string propName, RavenJToken property)
		{
			if (patchCmd.Value.Type != JTokenType.Integer)
				throw new InvalidOperationException("Cannot increment when value is not an integer");

			var valToSet = patchCmd.Value as RavenJValue; // never null since we made sure it's JTokenType.Integer

			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			var val = property as RavenJValue;
			if (val == null)
			{
				document[propName] = valToSet.Value<int>();
				return;
			}
			if (val.Value == null || val.Type == JTokenType.Null)
				val.Value = valToSet.Value<int>();
			else
				val.Value = RavenJToken.FromObject(val.Value<int>() + valToSet.Value<int>()).Value<int>();
		}
Exemplo n.º 50
0
		private void RemoveValue(PatchRequest patchCmd, string propName, RavenJToken token)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, token);
			if (token == null)
			{
				token = new RavenJArray();
				document[propName] = token;
			}
			var array = GetArray(token, propName);

			var position = patchCmd.Position;
			var value = patchCmd.Value;
			if (position == null && (value == null || value.Type == JTokenType.Null))
				throw new InvalidOperationException("Cannot remove value from  '" + propName + "' because position element does not exists or not an integer and no value was present");
			if (position != null && value != null && value.Type != JTokenType.Null)
				throw new InvalidOperationException("Cannot remove value from  '" + propName + "' because both a position and a value are set");
			if (position != null && (position.Value < 0 || position.Value >= array.Length))
				throw new IndexOutOfRangeException("Cannot remove value from  '" + propName +
												   "' because position element is out of bound bounds");

			if (value != null && value.Type != JTokenType.Null)
			{
				foreach (var ravenJToken in array.Where(x => RavenJToken.DeepEquals(x, value)).ToList())
				{
					array.Remove(ravenJToken);
				}

				return;
			}

			if(position!=null)
				array.RemoveAt(position.Value);
		}
Exemplo n.º 51
0
 /// <summary>
 /// Replaces webhook fields with new values. Pass a `json_patch` object with `replace` operation and `path`, which is `/url` for a URL or `/event_types` for events. The `value` is either the URL or a list of events.
 /// </summary>
 /// <param name="apiContext">APIContext used for the API call.</param>
 /// <param name="patchRequest">PatchRequest</param>
 /// <returns>Webhook</returns>
 public Webhook Update(APIContext apiContext, PatchRequest patchRequest)
 {
     return Webhook.Update(apiContext, this.id, patchRequest);
 }
Exemplo n.º 52
0
		private void AddValue(PatchRequest patchCmd, string propName, RavenJToken token)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, token);
			if (token == null)
			{
				token = new RavenJArray();
				document[propName] = token;
			}
			var array = GetArray(token, propName);

			array.Add(patchCmd.Value);
		}
Exemplo n.º 53
0
		private void InsertValue(PatchRequest patchCmd, string propName, RavenJToken property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			if (!(property is RavenJArray))
			{
				property = new RavenJArray();
				document[propName] = property;
			}
			var array = property as RavenJArray;
			if (array == null)
				throw new InvalidOperationException("Cannot remove value from '" + propName + "' because it is not an array");
			var position = patchCmd.Position;
			if (position == null)
				throw new InvalidOperationException("Cannot remove value from '" + propName + "' because position element does not exists or not an integer");
			if (position < 0 || position >= array.Length)
				throw new IndexOutOfRangeException("Cannot remove value from '" + propName +
												   "' because position element is out of bound bounds");
			array.Insert(position.Value, patchCmd.Value);
		}
Exemplo n.º 54
0
		private void SetProperty(PatchRequest patchCmd, string propName, RavenJToken property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			document[propName] = patchCmd.Value;
		}
Exemplo n.º 55
0
		private static void RemoveProperty(PatchRequest patchCmd, string propName, RavenJToken token, RavenJToken parent)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, token);
			var o = parent as RavenJObject;
			if (o != null)
				o.Remove(propName);
		}
Exemplo n.º 56
0
        public async Task<HttpResponseMessage> Patch(string userId, PatchRequest<ScimUser> patchRequest)
        {
            if (patchRequest == null ||
                patchRequest.Operations == null || 
                patchRequest.Operations.Operations.Any(a => a.OperationType == Patching.Operations.OperationType.Invalid))
            {
                return new ScimErrorResponse<ScimUser>(
                    new ScimError(
                        HttpStatusCode.BadRequest,
                        ScimErrorType.InvalidSyntax,
                        "The patch request body is un-parsable, syntactically incorrect, or violates schema."))
                    .ToHttpResponseMessage(Request);
            }

            return (await (await _UserService.RetrieveUser(userId))
                .Bind(user =>
                {
                    try
                    {
                        // TODO: (DG) Finish patch support
                        var result = patchRequest.Operations.ApplyTo(
                            user, 
                            new ScimObjectAdapter<ScimUser2>(ServerConfiguration, new CamelCasePropertyNamesContractResolver()));

                        return (IScimResponse<ScimUser>)new ScimDataResponse<ScimUser>(user);
                    }
                    catch (ScimPatchException ex)
                    {
                        return (IScimResponse<ScimUser>)new ScimErrorResponse<ScimUser>(ex.ToScimError());
                    }
                })
                .BindAsync(user => _UserService.UpdateUser(user)))
                .Let(user => SetMetaLocation(user, RetrieveUserRouteName, new { userId = user.Id }))
                .Let(PopulateUserGroupRef)
                .ToHttpResponseMessage(Request, (user, response) =>
                {
                    SetContentLocationHeader(response, RetrieveUserRouteName, new { userId = user.Id });
                    SetETagHeader(response, user);
                });
        }
Exemplo n.º 57
0
		public PatchResult ApplyPatch(string docId, Guid? etag, PatchRequest[] patchDoc, TransactionInformation transactionInformation)
		{
			var result = PatchResult.Patched;
			bool shouldRetry = false;
			int retries = 128;
			do
			{
				TransactionalStorage.Batch(actions =>
				{
					var doc = actions.Documents.DocumentByKey(docId, transactionInformation);
					if (doc == null)
					{
						result = PatchResult.DocumentDoesNotExists;
					}
					else if (etag != null && doc.Etag != etag.Value)
					{
						Debug.Assert(doc.Etag != null);
						throw new ConcurrencyException("Could not patch document '" + docId + "' because non current etag was used")
						{
							ActualETag = doc.Etag.Value,
							ExpectedETag = etag.Value,
						};
					}
					else
					{
						var jsonDoc = doc.ToJson();
						new JsonPatcher(jsonDoc).Apply(patchDoc);
						try
						{
							Put(doc.Key, doc.Etag, jsonDoc, jsonDoc.Value<RavenJObject>("@metadata"), transactionInformation);
						}
						catch (ConcurrencyException)
						{
							if(retries-- > 0)
							{
								shouldRetry = true;
								return;
							}
							throw;
						}
						result = PatchResult.Patched;
					}
					if (shouldRetry == false)
						workContext.ShouldNotifyAboutWork();
				});

			} while (shouldRetry);
			return result;
		}
Exemplo n.º 58
0
		private static void EnsurePreviousValueMatchCurrentValue(PatchRequest patchCmd, RavenJToken property)
		{
			var prevVal = patchCmd.PrevVal;
			if (prevVal == null)
				return;
			switch (prevVal.Type)
			{
				case JTokenType.Undefined:
					if (property != null)
						throw new ConcurrencyException();
					break;
				default:
					if (property == null)
						throw new ConcurrencyException();
					if (RavenJToken.DeepEquals(property, prevVal) == false)
						throw new ConcurrencyException();
					break;
			}
		}
Exemplo n.º 59
0
		private void CopyProperty(PatchRequest patchCmd, RavenJToken property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			if (property == null)
				return;

			document[patchCmd.Value.Value<string>()] = property;
		}
Exemplo n.º 60
0
		private static void ModifyValue(PatchRequest patchCmd, string propName, RavenJToken property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			if (property == null)
				throw new InvalidOperationException("Cannot modify value from '" + propName + "' because it was not found");

			var nestedCommands = patchCmd.Nested;
			if (nestedCommands == null)
				throw new InvalidOperationException("Cannot understand modified value from '" + propName +
													"' because could not find nested array of commands");

			var arrayOrValue = TryGetArray(property) ?? property;
			switch (arrayOrValue.Type)
			{
				case JTokenType.Object:
					foreach (var cmd in nestedCommands)
					{
						var nestedDoc = property.Value<RavenJObject>();
						new JsonPatcher(nestedDoc).Apply(cmd);
					}
					break;
				case JTokenType.Array:
					var position = patchCmd.Position;
					var allPositionsIsSelected = patchCmd.AllPositions.HasValue ? patchCmd.AllPositions.Value : false;
					if (position == null && !allPositionsIsSelected)
						throw new InvalidOperationException("Cannot modify value from  '" + propName +
						                                    "' because position element does not exists or not an integer and allPositions is not set");
					var valueList = new List<RavenJToken>();
					if (allPositionsIsSelected)
					{
						valueList.AddRange(arrayOrValue.Values<RavenJToken>());
					}
					else
					{
						valueList.Add(((RavenJArray)arrayOrValue)[position.Value]);
					}

					foreach (var value in valueList)
					{
						foreach (var cmd in nestedCommands)
						{
							new JsonPatcher(value.Value<RavenJObject>()).Apply(cmd);
						}
					}
					break;
				default:
					throw new InvalidOperationException("Can't understand how to deal with: " + property.Type);
			}
		}