Example #1
0
		public void CheckinScript(ScriptedPatchRequest request, Jint.JintEngine context)
		{
			CachedResult value;
			if (cacheDic.TryGetValue(request, out value))
			{
				if (value.Queue.Count > 20)
					return;
				value.Queue.Enqueue(context);
				return;
			}
			cacheDic.AddOrUpdate(request, patchRequest =>
			{
				var queue = new ConcurrentQueue<Jint.JintEngine>();
				queue.Enqueue(context);
				return new CachedResult
				{
					Queue = queue,
					Timestamp = SystemTime.UtcNow,
					Usage = 1
				};
			}, (patchRequest, result) =>
			{
				result.Queue.Enqueue(context);
				return result;
			});
		}
Example #2
0
        public void PatcherCanOutputObjectsCorrectly()
        {
            var doc = RavenJObject.Parse("{}");
            const string script = @"output(undefined);
                                output(true);
                                output(2);
                                output(2.5);
                                output('string');
                                output(null);
                                output([2, 'c']);
                                output({'a': 'c', 'f': { 'x' : 2}});"
                                ;

            var patch = new ScriptedPatchRequest()
            {
                Script = script
            };
            using (var scope = new DefaultScriptedJsonPatcherOperationScope())
            {
                var patcher = new ScriptedJsonPatcher();
                patcher.Apply(scope, doc, patch);
                Assert.Equal(8, patcher.Debug.Count);
                Assert.Equal("undefined", patcher.Debug[0]);
                Assert.Equal("True", patcher.Debug[1]);
                Assert.Equal("2", patcher.Debug[2]);
                Assert.Equal("2.5", patcher.Debug[3]);
                Assert.Equal("string", patcher.Debug[4]);
                Assert.Equal("null", patcher.Debug[5]);
                Assert.Equal("[2,\"c\"]", patcher.Debug[6]);
                Assert.Equal("{\"a\":\"c\",\"f\":{\"x\":2}}", patcher.Debug[7]);
            }
        }
Example #3
0
        public void CheckinScript(ScriptedPatchRequest request, Engine context, RavenJObject customFunctions)
        {
            CachedResult cacheByCustomFunctions;

            var patchRequestAndCustomFunctionsTuple = new ScriptedPatchRequestAndCustomFunctionsToken(request, customFunctions);
            if (cacheDic.TryGetValue(patchRequestAndCustomFunctionsTuple, out cacheByCustomFunctions))
            {
                if (cacheByCustomFunctions.Queue.Count > 20)
                    return;
                cacheByCustomFunctions.Queue.Enqueue(context);
                return;
            }
            cacheDic.AddOrUpdate(patchRequestAndCustomFunctionsTuple, patchRequest =>
            {
                var queue = new ConcurrentQueue<Engine>();

                return new CachedResult
                {
                    Queue = queue,
                    Timestamp = SystemTime.UtcNow,
                    Usage = 1
                };
            }, (patchRequest, result) =>
            {
                result.Queue.Enqueue(context);
                return result;
            });
        }
		private RavenJObject ApplySingleScript(RavenJObject doc, ScriptedPatchRequest patch, int size, string docId, ScriptedJsonPatcherOperationScope scope)
		{
			Engine jintEngine;
			try
			{
				jintEngine = ScriptsCache.CheckoutScript(CreateEngine, patch);
			}
			catch (NotSupportedException e)
			{
				throw new ParseException("Could not parse script", e);
			}
			catch (JavaScriptException e)
			{
				throw new ParseException("Could not parse script", e);
			}
			catch (Exception e)
			{
				throw new ParseException("Could not parse: " + Environment.NewLine + patch.Script, e);
			}

			try
			{
				PrepareEngine(patch, docId, size, scope, jintEngine);

				var jsObject = scope.ToJsObject(jintEngine, doc);
			    jintEngine.Invoke("ExecutePatchScript", jsObject);

			    CleanupEngine(patch, jintEngine);

				OutputLog(jintEngine);

			    ScriptsCache.CheckinScript(patch, jintEngine);

				return scope.ConvertReturnValue(jsObject);
			}
			catch (ConcurrencyException)
			{
			    throw;
			}
			catch (Exception errorEx)
			{
				jintEngine.ResetStatementsCount();

				OutputLog(jintEngine);
				var errorMsg = "Unable to execute JavaScript: " + Environment.NewLine + patch.Script;
				var error = errorEx as JavaScriptException;
				if (error != null)
					errorMsg += Environment.NewLine + "Error: " + Environment.NewLine + string.Join(Environment.NewLine, error.Error);
				if (Debug.Count != 0)
					errorMsg += Environment.NewLine + "Debug information: " + Environment.NewLine +
								string.Join(Environment.NewLine, Debug);

				var targetEx = errorEx as TargetInvocationException;
				if (targetEx != null && targetEx.InnerException != null)
					throw new InvalidOperationException(errorMsg, targetEx.InnerException);

				throw new InvalidOperationException(errorMsg, errorEx);
			}
		}
        public RavenJArray UpdateByIndex(string indexName, IndexQuery queryToUpdate, ScriptedPatchRequest patch, BulkOperationOptions options = null)
		{
            return PerformBulkOperation(indexName, queryToUpdate, options, (docId, tx) =>
			{
				var patchResult = database.Patches.ApplyPatch(docId, null, patch, tx);
				return new { Document = docId, Result = patchResult.Item1, Debug = patchResult.Item2 };
			});
		}
Example #6
0
		private RavenJObject ApplySingleScript(RavenJObject doc, ScriptedPatchRequest patch)
		{
			JintEngine ctx;
			try
			{
				ctx = scriptsCache.CheckoutScript(patch);
			}
			catch (NotSupportedException)
			{
				throw;
			}
			catch (Exception e)
			{
				throw new InvalidOperationException("Could not parse: " + Environment.NewLine + patch.Script, e);
			}

			loadDocumentStatic = loadDocument;
			try
			{
				foreach (var kvp in patch.Values)
				{
					if(kvp.Value is RavenJToken)
					{
						ctx.SetParameter(kvp.Key, ToJsInstance(ctx.Global, (RavenJToken)kvp.Value));
					}
					else
					{
						var rjt = RavenJToken.FromObject(kvp.Value);
						var jsInstance = ToJsInstance(ctx.Global, rjt);
						ctx.SetParameter(kvp.Key, jsInstance);
					}
				}
				var jsObject = ToJsObject(ctx.Global, doc);
				ctx.CallFunction("ExecutePatchScript", jsObject);
				foreach (var kvp in patch.Values)
				{
					ctx.RemoveParameter(kvp.Key);
				}
				OutputLog(ctx);

				scriptsCache.CheckinScript(patch, ctx);

				return ToRavenJObject(jsObject);
			}
			catch (Exception errorEx)
			{
				OutputLog(ctx);
				throw new InvalidOperationException("Unable to execute JavaScript: " + Environment.NewLine + patch.Script +
					Environment.NewLine + "Debug information: " + Environment.NewLine + string.Join(Environment.NewLine, Debug), errorEx);
			}
			finally
			{
				loadDocumentStatic = null;
			}
		}
Example #7
0
		public void CanUseTrim()
		{
			var doc = RavenJObject.Parse("{\"Email\":' [email protected] '}");
			const string script = "this.Email = this.Email.trim();";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
			};
			var result = new ScriptedJsonPatcher().Apply(doc, patch);
			Assert.Equal(result["Email"].Value<string>(), "*****@*****.**");
		}
Example #8
0
		public void ComplexVariableTest()
		{
			const string email = "*****@*****.**";
			var doc = RavenJObject.Parse("{\"Email\":null}");
			const string script = "this.Email = data.Email;";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
				Values = { { "data", new { Email = email } } }
			};
			var result = new ScriptedJsonPatcher().Apply(doc, patch);
			Assert.Equal(result["Email"].Value<string>(),email);
		}
Example #9
0
		public RavenJObject Apply(RavenJObject document, ScriptedPatchRequest patch)
		{
			if (document == null)
				return null;

			if (String.IsNullOrEmpty(patch.Script))
				throw new InvalidOperationException("Patch script must be non-null and not empty");

			var resultDocument = ApplySingleScript(document, patch);
			if (resultDocument != null)
				document = resultDocument;
			return document;
		}
Example #10
0
		public void ComplexVariableTest2()
		{
			const string email = "*****@*****.**";
			var doc = RavenJObject.Parse("{\"Contact\":null}");
			const string script = "this.Contact = contact;";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
				Values = { { "contact", new { Email = email } } }
			};
			var result = new ScriptedJsonPatcher().Apply(doc, patch);
			Assert.NotNull(result["Contact"]);
		}
	    public virtual RavenJObject Apply(ScriptedJsonPatcherOperationScope scope, RavenJObject document, ScriptedPatchRequest patch, int size = 0, string docId = null)
		{
			if (document == null)
				return null;

			if (String.IsNullOrEmpty(patch.Script))
				throw new InvalidOperationException("Patch script must be non-null and not empty");

				var resultDocument = ApplySingleScript(document, patch, size, docId, scope);
				if (resultDocument != null)
					document = resultDocument;
			
			return document;
		}
Example #12
0
		public Engine CheckoutScript(Func<ScriptedPatchRequest, Engine> createEngine, ScriptedPatchRequest request)
		{
			CachedResult value;
			if (cacheDic.TryGetValue(request, out value))
			{
				Interlocked.Increment(ref value.Usage);
				Engine context;
				if (value.Queue.TryDequeue(out context))
				{
					return context;
				}
			}
			var result = createEngine(request);

			var cachedResult = new CachedResult
			{
				Usage = 1,
				Queue = new ConcurrentQueue<Engine>(),
				Timestamp = SystemTime.UtcNow
			};

			cacheDic.AddOrUpdate(request, cachedResult, (_, existing) =>
			{
				Interlocked.Increment(ref existing.Usage);
				return existing;
			});
			if (cacheDic.Count > CacheMaxSize)
			{
				foreach (var source in cacheDic
					.Where(x=>x.Value !=null)
					.OrderByDescending(x => x.Value.Usage)
					.ThenBy(x => x.Value.Timestamp)
					.Skip(CacheMaxSize - CacheMaxSize/10))
				{
					if (Equals(source.Key, request))
						continue; // we don't want to remove the one we just added
					CachedResult ignored;
					cacheDic.TryRemove(source.Key, out ignored);
				}
				foreach (var source in cacheDic.Where(x => x.Value == null))
				{
					CachedResult ignored;
					cacheDic.TryRemove(source.Key, out ignored);
				}
			}

			return result;
		}
Example #13
0
        public void PatchRequestShouldCreateDocIfNotExists()
        {
            using (var store = NewDocumentStore())
            {
                var patchExisting = new ScriptedPatchRequest
                {
                    Script = "this.Counter++;",
                };
                var patchDefault = new ScriptedPatchRequest
                {
                    Script = "this.Counter=100;",
                };
                var docId = "Docs/1";

                store.DatabaseCommands.Patch(docId, patchExisting, patchDefault, new RavenJObject());

                using (var session = store.OpenSession())
                {
                    Assert.NotNull(session.Load<TestDoc>(docId));
                }
            }
        }
Example #14
0
		internal static JintEngine CreateEngine(ScriptedPatchRequest patch)
		{
			var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}{1}
  }}).apply(docInner);
}};
", patch.Script, patch.Script.EndsWith(";") ? String.Empty : ";");

			var jintEngine = new JintEngine()
				.AllowClr(false)
				.SetDebugMode(false)
				.SetMaxRecursions(50)
				.SetMaxSteps(10*1000);


			jintEngine.Run(GetFromResources("Raven.Database.Json.Map.js"));

			jintEngine.Run(GetFromResources("Raven.Database.Json.lodash.js"));

			jintEngine.Run(GetFromResources("Raven.Database.Json.RavenDB.js"));

			jintEngine.SetFunction("LoadDocument", ((Func<string, object>)(value =>
			{
				var loadedDoc = loadDocumentStatic(value);
				if (loadedDoc == null)
					return null;
				loadedDoc[Constants.DocumentIdFieldName] = value;
				return ToJsObject(jintEngine.Global, loadedDoc);
			})));

			jintEngine.Run(wrapperScript);

			return jintEngine;
		}
Example #15
0
		private RavenJObject ApplySingleScript(RavenJObject doc, ScriptedPatchRequest patch, int size)
		{
			JintEngine jintEngine;
			try
			{
				jintEngine = scriptsCache.CheckoutScript(CreateEngine, patch);
			}
			catch (NotSupportedException)
			{
				throw;
			}
			catch (JintException)
			{
				throw;
			}
			catch (Exception e)
			{
				throw new InvalidOperationException("Could not parse: " + Environment.NewLine + patch.Script, e);
			}

			loadDocumentStatic = loadDocument;
			try
			{
				CustomizeEngine(jintEngine);
				
				foreach (var kvp in patch.Values)
				{
					if (kvp.Value is RavenJToken)
					{
						jintEngine.SetParameter(kvp.Key, ToJsInstance(jintEngine.Global, (RavenJToken)kvp.Value));
					}
					else
					{
						var rjt = RavenJToken.FromObject(kvp.Value);
						var jsInstance = ToJsInstance(jintEngine.Global, rjt);
						jintEngine.SetParameter(kvp.Key, jsInstance);
					}
				}
				var jsObject = ToJsObject(jintEngine.Global, doc);
				jintEngine.ResetSteps();
				if (size != 0)
				{
					jintEngine.SetMaxSteps(10*1000 + (size*5));
				}
				jintEngine.CallFunction("ExecutePatchScript", jsObject);
				foreach (var kvp in patch.Values)
				{
					jintEngine.RemoveParameter(kvp.Key);
				}
				RemoveEngineCustomizations(jintEngine);
				OutputLog(jintEngine);

				scriptsCache.CheckinScript(patch, jintEngine);

				return ConvertReturnValue(jsObject);
			}
			catch (Exception errorEx)
			{
				OutputLog(jintEngine);
				var errorMsg = "Unable to execute JavaScript: " + Environment.NewLine + patch.Script;
				var error = errorEx as JsException;
				if (error != null)
					errorMsg += Environment.NewLine + "Error: " + Environment.NewLine + string.Join(Environment.NewLine, error.Value);
				if (Debug.Count != 0)
					errorMsg += Environment.NewLine + "Debug information: " + Environment.NewLine +
								string.Join(Environment.NewLine, Debug);

				throw new InvalidOperationException(errorMsg, errorEx);
			}
			finally
			{
				loadDocumentStatic = null;
			}
		}
Example #16
0
		public Tuple<PatchResultData, List<string>> ApplyPatch(string docId, Etag etag, ScriptedPatchRequest patch, TransactionInformation transactionInformation, bool debugMode = false)
		{
			ScriptedJsonPatcher scriptedJsonPatcher = null;
			var applyPatchInternal = ApplyPatchInternal(docId, etag, transactionInformation,
				(jsonDoc, size) =>
				{
					scriptedJsonPatcher = new ScriptedJsonPatcher(this);
					return scriptedJsonPatcher.Apply(jsonDoc, patch);
				}, debugMode);
			return Tuple.Create(applyPatchInternal, scriptedJsonPatcher == null ? new List<string>() : scriptedJsonPatcher.Debug);
		}
Example #17
0
		private JintEngine CreateEngine(ScriptedPatchRequest patch)
		{
			var scriptWithProperLines = NormalizeLineEnding(patch.Script);
			var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}
  }}).apply(docInner);
}};
", scriptWithProperLines);

			var jintEngine = new JintEngine()
				.AllowClr(false)
#if DEBUG
				.SetDebugMode(true)
#else
                .SetDebugMode(false)
#endif
                .SetMaxRecursions(50)
				.SetMaxSteps(maxSteps);

            AddScript(jintEngine, "Raven.Database.Json.lodash.js");
			AddScript(jintEngine, "Raven.Database.Json.ToJson.js");
			AddScript(jintEngine, "Raven.Database.Json.RavenDB.js");

			jintEngine.SetFunction("LoadDocument", ((Func<string, object>)(value =>
			{
				var loadedDoc = loadDocumentStatic(value);
				if (loadedDoc == null)
					return null;
				loadedDoc[Constants.DocumentIdFieldName] = value;
				return ToJsObject(jintEngine.Global, loadedDoc);
			})));

            jintEngine.Run(wrapperScript);

			return jintEngine;
		}
Example #18
0
		public override void Execute(object parameter)
		{
            patchModel.ClearQueryError();

			var values = patchModel.GetValues();
			if (values == null)
				return;
			var request = new ScriptedPatchRequest {Script = patchModel.Script.CurrentSnapshot.Text, Values = values};
			var commands = new ICommandData[1];

			switch (patchModel.PatchOn)
			{
				case PatchOnOptions.Document:
					ApplicationModel.Database.Value.AsyncDatabaseCommands.GetAsync(patchModel.SelectedItem).
						ContinueOnSuccessInTheUIThread(doc => patchModel.OriginalDoc.SetText(doc.ToJson().ToString()));

					commands[0] = new ScriptedPatchCommandData
					{
						Patch = request,
						Key = patchModel.SelectedItem,
						DebugMode = true
					};

					break;

				case PatchOnOptions.Collection:
				case PatchOnOptions.Index:
			        var selectedItem = patchModel.QueryResults.ItemSelection.GetSelectedItems().FirstOrDefault();
                    if (selectedItem == null || !selectedItem.IsRealized)
                    {
                        return;
                    }

                    patchModel.OriginalDoc.SetText(selectedItem.Item.Document.ToJson().ToString());
			        var docId = selectedItem.Item.Document.Key;

					commands[0] = new ScriptedPatchCommandData
					{
						Patch = request,
						Key = docId,
						DebugMode = true
					};

					break;
			}

			patchModel.InProcess.Value = true;

			ApplicationModel.Database.Value.AsyncDatabaseCommands.BatchAsync(commands)
				.ContinueOnSuccessInTheUIThread(batch => patchModel.NewDoc.SetText(batch[0].AdditionalData.ToString()))
				.ContinueOnUIThread(t => { if (t.IsFaulted) patchModel.HandlePatchError(t.Exception); })
				.Finally(() => patchModel.InProcess.Value = false);

		    patchModel.ShowBeforeAndAfterPrompt = false;
			patchModel.ShowAfterPrompt = false;
		}
Example #19
0
        public Tuple<PatchResultData, List<string>> ApplyPatch(string docId, Etag etag,
                                                               ScriptedPatchRequest patchExisting, ScriptedPatchRequest patchDefault, RavenJObject defaultMetadata,
                                                               TransactionInformation transactionInformation, bool debugMode = false)
        {
            ScriptedJsonPatcher scriptedJsonPatcher = null;
            var applyPatchInternal = ApplyPatchInternal(docId, etag, transactionInformation,
                jsonDoc =>
                {
                    scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
                    return scriptedJsonPatcher.Apply(jsonDoc.ToJson(), patchExisting, jsonDoc.SerializedSizeOnDisk, jsonDoc.Key);
                },
                () =>
                {
                    if (patchDefault == null)
                        return null;

                    scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
                    var jsonDoc = new RavenJObject();
                    jsonDoc[Constants.Metadata] = defaultMetadata ?? new RavenJObject();
                    return scriptedJsonPatcher.Apply(new RavenJObject(), patchDefault, 0, docId);
                },
                () =>
                {
                    if (scriptedJsonPatcher == null)
                        return null;
                    return scriptedJsonPatcher
                        .GetPutOperations()
                        .ToList();
                }, debugMode);
            return Tuple.Create(applyPatchInternal, scriptedJsonPatcher == null ? new List<string>() : scriptedJsonPatcher.Debug);
        }
		private void PrepareEngine(ScriptedPatchRequest patch, string docId, int size, ScriptedJsonPatcherOperationScope scope, Engine jintEngine)
		{
			jintEngine.Global.Delete("PutDocument", false);
			jintEngine.Global.Delete("LoadDocument", false);
			jintEngine.Global.Delete("DeleteDocument", false);

			CustomizeEngine(jintEngine, scope);

			jintEngine.SetValue("PutDocument", (Action<string, object, object>)((key, document, metadata) => scope.PutDocument(key, document, metadata, jintEngine)));
			jintEngine.SetValue("LoadDocument", (Func<string, JsValue>)(key => scope.LoadDocument(key, jintEngine)));
			jintEngine.SetValue("DeleteDocument", (Action<string>)(scope.DeleteDocument));
			jintEngine.SetValue("__document_id", docId);

			foreach (var kvp in patch.Values)
			{
				var token = kvp.Value as RavenJToken;
				if (token != null)
				{
					jintEngine.SetValue(kvp.Key, scope.ToJsInstance(jintEngine, token));
				}
				else
				{
					var rjt = RavenJToken.FromObject(kvp.Value);
					var jsInstance = scope.ToJsInstance(jintEngine, rjt);
					jintEngine.SetValue(kvp.Key, jsInstance);
				}
			}

			jintEngine.ResetStatementsCount();
			if (size != 0)
				jintEngine.Options.MaxStatements(maxSteps + (size * additionalStepsPerSize));
		}
Example #21
0
		protected bool Equals(ScriptedPatchRequest other)
		{
			if(other == null)
				return false;
			return string.Equals(Script, other.Script) && Values.Keys.SequenceEqual(other.Values.Keys);
		}
Example #22
0
		public void CanUseSplit()
		{
			var doc = RavenJObject.Parse("{\"Email\":'*****@*****.**'}");
			const string script = @"
this.Parts = this.Email.split('@');";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
			};
			var scriptedJsonPatcher = new ScriptedJsonPatcher();
			var result = scriptedJsonPatcher.Apply(doc, patch);
			Assert.Equal(result["Parts"].Value<RavenJArray>()[0], "somebody");
			Assert.Equal(result["Parts"].Value<RavenJArray>()[1], "somewhere.com");
		}
Example #23
0
		public void CanUseMathFloor()
		{
			var doc = RavenJObject.Parse("{\"Email\":' [email protected] '}");
			const string script = "this.Age =  Math.floor(1.6);";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
			};
			var result = new ScriptedJsonPatcher().Apply(doc, patch);
			Assert.Equal(result["Age"].Value<int>(), 1);
		}
Example #24
0
		public override void Execute(object parameter)
		{
		    AskUser.ConfirmationAsync("Patch Documents", "Are you sure you want to apply this patch to all matching documents?")
                .ContinueWhenTrueInTheUIThread(() =>
                {
                    patchModel.ClearQueryError();

					var values = patchModel.GetValues();
					if (values == null)
						return;
                    var request = new ScriptedPatchRequest { Script = patchModel.Script.CurrentSnapshot.Text, Values = values};
					patchModel.InProcess.Value = true;

                    switch (patchModel.PatchOn)
                    {
                        case PatchOnOptions.Document:
                            var commands = new ICommandData[1];
                            commands[0] = new ScriptedPatchCommandData
                            {
                                Patch = request,
                                Key = patchModel.SelectedItem
                            };

		                    ApplicationModel.Database.Value.AsyncDatabaseCommands.BatchAsync(commands)
			                    .ContinueOnUIThread(t => { if (t.IsFaulted) patchModel.HandlePatchError(t.Exception); })
			                    .ContinueOnSuccessInTheUIThread(
				                    () => ApplicationModel.Database.Value.AsyncDatabaseCommands.GetAsync(patchModel.SelectedItem).
					                          ContinueOnSuccessInTheUIThread(doc =>
					                          {
						                          patchModel.OriginalDoc.SetText(doc.ToJson().ToString());
						                          patchModel.NewDoc.SetText("");
						                          patchModel.ShowAfterPrompt = true;
					                          }))
			                    .Finally(() => patchModel.InProcess.Value = false);
                            break;

                        case PatchOnOptions.Collection:
                            ApplicationModel.Database.Value.AsyncDatabaseCommands.UpdateByIndex(PatchModel.CollectionsIndex,
                                                                                                new IndexQuery { Query = "Tag:" + patchModel.SelectedItem }, request)
																								.ContinueOnSuccessInTheUIThread(() => patchModel.UpdateCollectionSource())
                                                                                                 .ContinueOnUIThread(t => { if (t.IsFaulted) patchModel.HandlePatchError(t.Exception); })
																								 .Finally(() => patchModel.InProcess.Value = false);
                            break;

                        case PatchOnOptions.Index:
                            ApplicationModel.Database.Value.AsyncDatabaseCommands.UpdateByIndex(patchModel.SelectedItem, new IndexQuery { Query = patchModel.QueryDoc.CurrentSnapshot.Text },
                                                                                                request)
																								.ContinueOnSuccessInTheUIThread(() => patchModel.UpdateCollectionSource())
                                                                                                 .ContinueOnUIThread(t => { if (t.IsFaulted) patchModel.HandlePatchError(t.Exception); })
																								 .Finally(() => patchModel.InProcess.Value = false);
                            break;
                    }

					
                });
		}
		private void CleanupEngine(ScriptedPatchRequest patch, Engine jintEngine)
		{
			foreach (var kvp in patch.Values)
				jintEngine.Global.Delete(kvp.Key, true);

			jintEngine.Global.Delete("__document_id", true);
			RemoveEngineCustomizations(jintEngine);
		}
Example #26
0
		public void CanUseLoDash()
		{
			const string email = "*****@*****.**";
			var doc = RavenJObject.Parse("{\"Contact\":null}");
			const string script = "this.Emails = _(3).times(function(i) { return contact.Email + i; });";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
				Values = { { "contact", new { Email = email } } }
			};
			var result = new ScriptedJsonPatcher().Apply(doc, patch);
			Assert.Equal(new [] { "[email protected]", "[email protected]", "[email protected]" }, result.Value<RavenJArray>("Emails").Select(x => x.Value<string>()));
		}
Example #27
0
		public override void Execute(object parameter)
		{
            patchModel.ClearQueryError();

			AskUser.ConfirmationAsync("Patch Documents", "Are you sure you want to apply this patch to all selected documents?")
				.ContinueWhenTrueInTheUIThread(() =>
				{
					var values = patchModel.GetValues();
					if (values == null)
						return;
					var request = new ScriptedPatchRequest {Script = patchModel.Script.CurrentSnapshot.Text, Values = values};
					var selectedItems = patchModel.QueryResults.ItemSelection.GetSelectedItems();
					var commands = new ICommandData[selectedItems.Count()];
					var counter = 0;

					foreach (var item in selectedItems)
					{
						commands[counter] = new ScriptedPatchCommandData
						{
							Patch = request,
							Key = item.Item.Id
						};

						counter++;
					}

					ApplicationModel.Database.Value.AsyncDatabaseCommands
						.BatchAsync(commands)
                         .ContinueOnUIThread(t => { if (t.IsFaulted) patchModel.HandlePatchError(t.Exception); })
						.ContinueOnSuccessInTheUIThread(() => ApplicationModel.Database.Value
							.AsyncDatabaseCommands
							.GetAsync(patchModel.SelectedItem)
							.ContinueOnSuccessInTheUIThread(doc =>
							{
								if (doc != null)
								{
									patchModel.OriginalDoc.SetText(doc.ToJson().ToString());
									patchModel.NewDoc.SetText("");
									patchModel.ShowAfterPrompt = true;
								}
								else
								{
									patchModel.OriginalDoc.SetText("");
									patchModel.NewDoc.SetText("");
									patchModel.ShowAfterPrompt = true;
									patchModel.ShowBeforeAndAfterPrompt = true;
								}
							}));
				});
		}
Example #28
0
 public Tuple<PatchResultData, List<string>> ApplyPatch(string docId, Etag etag, ScriptedPatchRequest patch,
                                                TransactionInformation transactionInformation, bool debugMode = false)
 {
     ScriptedJsonPatcher scriptedJsonPatcher = null;
     var applyPatchInternal = ApplyPatchInternal(docId, etag, transactionInformation,
         jsonDoc =>
         {
             scriptedJsonPatcher = new ScriptedJsonPatcher(Database);
             return scriptedJsonPatcher.Apply(jsonDoc.ToJson(), patch, jsonDoc.SerializedSizeOnDisk, jsonDoc.Key);
         },
         () => null,
         () =>
         {
             if (scriptedJsonPatcher == null)
                 return null;
             return scriptedJsonPatcher
                 .GetPutOperations()
                 .ToList();
         }, debugMode);
     return Tuple.Create(applyPatchInternal, scriptedJsonPatcher == null ? new List<string>() : scriptedJsonPatcher.Debug);
 }
Example #29
0
		public void CanPatchUsingRavenJObjectVars()
		{
			var doc = RavenJObject.FromObject(test);
			var variableSource = new { NewComment = "New Comment" };
			var variable = RavenJObject.FromObject(variableSource);
			var script = "this.Comments[0] = variable.NewComment;";
			var patch = new ScriptedPatchRequest()
			{
				Script = script,
				Values = { { "variable", variable } }
			};

			var resultJson = new ScriptedJsonPatcher().Apply(doc, patch);
			var result = JsonConvert.DeserializeObject<CustomType>(resultJson.ToString());

			Assert.Equal(variableSource.NewComment, result.Comments[0]);
		}
		private Engine CreateEngine(ScriptedPatchRequest patch)
		{
			var scriptWithProperLines = NormalizeLineEnding(patch.Script);
			var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}
  }}).apply(docInner);
}};
", scriptWithProperLines);

			var jintEngine = new Engine(cfg =>
			{
#if DEBUG
				cfg.AllowDebuggerStatement();
#else
				cfg.AllowDebuggerStatement(false);
#endif
				cfg.MaxStatements(maxSteps);
			});

            AddScript(jintEngine, "Raven.Database.Json.lodash.js");
            AddScript(jintEngine, "Raven.Database.Json.ToJson.js");
            AddScript(jintEngine, "Raven.Database.Json.RavenDB.js");

            jintEngine.Execute(wrapperScript);

			return jintEngine;
		}