Example #1
0
        public void CloningTestsWorksCorrectly()
        {
            var f = new RavenJObject();

            f["1"] = new RavenJValue(1);
            f["2"] = new RavenJValue(2);

            var f1 = (RavenJObject)f.CloneToken();

            f1["2"] = new RavenJValue(3);

            var val = (RavenJValue)f["2"];

            Assert.Equal(2, val.Value);
            val = (RavenJValue)f1["2"];
            Assert.Equal(3, val.Value);

            var f2 = (RavenJObject)f1.CloneToken();

            val = (RavenJValue)f2["2"];
            Assert.Equal(3, val.Value);

            f["2"] = f2;
            f1     = (RavenJObject)f.CloneToken();
            f.Remove("2");
            Assert.Null(f["2"]);
            Assert.NotNull(f1["2"]);
        }
		private static void EnsureQuotasBundleActivated(RavenJObject settings)
		{
			RavenJToken value;
			if (settings.TryGetValue(Constants.ActiveBundles, out value) == false)
				settings[Constants.ActiveBundles] = value = new RavenJValue(string.Empty);

			var activeBundles = value.Value<string>();
			var bundles = activeBundles.GetSemicolonSeparatedValues();

			if (bundles.Contains("Quotas", StringComparer.OrdinalIgnoreCase) == false)
				bundles.Add("Quotas");

			int hardLimitInKb;
			if (int.TryParse(ConfigurationManager.AppSettings["Raven/Bundles/LiveTest/Quotas/Size/HardLimitInKB"], out hardLimitInKb) == false) 
				hardLimitInKb = QuotasHardLimitInKb;

			int softMarginInKb;
			if (int.TryParse(ConfigurationManager.AppSettings["Raven/Bundles/LiveTest/Quotas/Size/SoftLimitInKB"], out softMarginInKb) == false)
				softMarginInKb = QuotasSoftMarginInKb;

			settings[Constants.ActiveBundles] = string.Join(";", bundles);
			settings[Constants.SizeHardLimitInKB] = hardLimitInKb;
			settings[Constants.SizeSoftLimitInKB] = softMarginInKb;
			settings[Constants.DocsHardLimit] = null;
			settings[Constants.DocsSoftLimit] = null;
		}
Example #3
0
        //===============================================================
        public void Update(String json, UpdateType updateType = UpdateType.Set)
        {
            if (Object == null)
            {
                return;
            }

            var error = "";

            if (!IsValidUpdate(json, updateType, typeof(T), ref error))
            {
                throw new ArgumentException(error, "json");
            }

            var obj     = JObject.Parse(json);
            var patches = obj.Properties().Where(x => Object.GetType().GetProperty(x.Name) != null)
                          .Select(x => new PatchRequest {
                Type = ToPatchType(updateType), Name = x.Name, Value = RavenJValue.FromObject(x.Value)
            }).ToArray();

            Session.Advanced.Defer(new PatchCommandData {
                Key = KeyGenerator(Object), Patches = patches
            });
            Session.SaveChanges();
        }
        public virtual void ScheduleDispatch(Commit commit, string databaseName)
        {
            _dispatcher.Dispatch(commit);
            if (string.IsNullOrWhiteSpace(databaseName))
            {
                //using (var t = new TransactionScope(TransactionScopeOption.Suppress))
                //{
                _store.DatabaseCommands.Patch(commit.AggregateId.ToStringId <EventStream>(),
                                              new ScriptedPatchRequest
                {
                    Script = "this.Commits[CommitId].IsDispatched=true",
                    Values = { { "CommitId", RavenJValue.FromObject(commit.CommitId.ToString()) } }
                });
                //t.Complete();
                //}
            }
            else
            {
                //using (var t = new TransactionScope(TransactionScopeOption.Suppress))
                //{
                var db = _store.DatabaseCommands.ForDatabase(databaseName);
                db.Patch(commit.AggregateId.ToStringId <EventStream>(),
                         new ScriptedPatchRequest
                {
                    Script = "this.Commits[CommitId].IsDispatched=true",
                    Values = { { "CommitId", RavenJValue.FromObject(commit.CommitId.ToString()) } }
                });

                //t.Complete();
                //}
            }
        }
Example #5
0
        /// <summary>
        /// Puts the attachment with the specified key asynchronously
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="etag">The etag.</param>
        /// <param name="data">The data.</param>
        /// <param name="metadata">The metadata.</param>
        public Task PutAttachmentAsync(string key, Guid?etag, byte[] data, RavenJObject metadata)
        {
            if (metadata == null)
            {
                metadata = new RavenJObject();
            }

            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }

            var request = jsonRequestFactory.CreateHttpJsonRequest(this, url.Static(key), "PUT", metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);

            return(request
                   .WriteAsync(data)
                   .ContinueWith(write =>
            {
                if (write.Exception != null)
                {
                    throw new InvalidOperationException("Unable to write to server");
                }

                return request.ReadResponseStringAsync();
            }).Unwrap());
        }
 public override void OnRead(string key, RavenJObject document, RavenJObject metadata, ReadOperation operation, TransactionInformation transactionInformation)
 {
     var name = document["name"];
     if (name != null)
     {
         document["name"] = new RavenJValue(name.Value<string>().ToUpper());
     }
 }
Example #7
0
            public override void OnRead(string key, RavenJObject document, RavenJObject metadata, ReadOperation operation, TransactionInformation transactionInformation)
            {
                var name = document["name"];

                if (name != null)
                {
                    document["name"] = new RavenJValue(name.Value <string>().ToUpper());
                }
            }
Example #8
0
 private void SetProperty(PatchRequest patchCmd, string propName, RavenJValue property)
 {
     EnsurePreviousValueMatchCurrentValue(patchCmd, property);
     if (property == null)
     {
         document[propName] = patchCmd.Value;
         return;
     }
     property.Value = ((RavenJValue)patchCmd.Value).Value;
 }
        private RavenJObject RetrieveMetadata()
        {
            var metadataAsString = Api.RetrieveColumnAsString(session, Files, tableColumnsCache.FilesColumns["metadata"], Encoding.Unicode);

            var metadata = RavenJObject.Parse(metadataAsString);

            metadata["ETag"] = new RavenJValue(Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]).TransfromToGuidWithProperSorting());

            return(metadata);
        }
Example #10
0
        private static void AddTransactionInformation(RavenJObject metadata)
        {
            if (Transaction.Current == null)
            {
                return;
            }

            string txInfo = string.Format("{0}, {1}", Transaction.Current.TransactionInformation.DistributedIdentifier, TransactionManager.DefaultTimeout);

            metadata["Raven-Transaction-Information"] = new RavenJValue(txInfo);
        }
Example #11
0
        /// <summary>
        /// Puts the document with the specified key in the database
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="etag">The etag.</param>
        /// <param name="document">The document.</param>
        /// <param name="metadata">The metadata.</param>
        public Task <PutResult> PutAsync(string key, Guid?etag, RavenJObject document, RavenJObject metadata)
        {
            if (metadata == null)
            {
                metadata = new RavenJObject();
            }
            var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";

            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }
            var request = jsonRequestFactory.CreateHttpJsonRequest(this, url + "/docs/" + key, method, metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);

            return(request.WriteAsync(document.ToString())
                   .ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    throw new InvalidOperationException("Unable to write to server", task.Exception);
                }

                return request.ReadResponseStringAsync()
                .ContinueWith(task1 =>
                {
                    try
                    {
                        return JsonConvert.DeserializeObject <PutResult>(task1.Result, new JsonEnumConverter(), new JsonToJsonConverter());
                    }
                    catch (AggregateException e)
                    {
                        var webexception = e.ExtractSingleInnerException() as WebException;
                        if (ShouldThrowForPutAsync(webexception))
                        {
                            throw;
                        }
                        throw ThrowConcurrencyException(webexception);
                    }
                    catch (WebException e)
                    {
                        if (ShouldThrowForPutAsync(e))
                        {
                            throw;
                        }
                        throw ThrowConcurrencyException(e);
                    }
                });
            })
                   .Unwrap());
        }
Example #12
0
        private static void AddTransactionInformation(RavenJObject metadata)
        {
            var transactionInformation = RavenTransactionAccessor.GetTransactionInformation();

            if (transactionInformation == null)
            {
                return;
            }

            string txInfo = string.Format("{0}, {1}", transactionInformation.Id, transactionInformation.Timeout);

            metadata["Raven-Transaction-Information"] = new RavenJValue(txInfo);
        }
Example #13
0
        /// <summary>
        /// Puts the document with the specified key in the database
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="etag">The etag.</param>
        /// <param name="document">The document.</param>
        /// <param name="metadata">The metadata.</param>
        public Task <PutResult> PutAsync(string key, Guid?etag, RavenJObject document, RavenJObject metadata)
        {
            if (metadata == null)
            {
                metadata = new RavenJObject();
            }
            var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";

            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }
            var request = jsonRequestFactory.CreateHttpJsonRequest(this, url + "/docs/" + key, method, metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);


            return(Task.Factory.FromAsync(request.BeginWrite, request.EndWrite, document.ToString(), null)
                   .ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    throw new InvalidOperationException("Unable to write to server");
                }

                return request.ReadResponseJsonAsync()
                .ContinueWith(task1 =>
                {
                    try
                    {
                        return convention.CreateSerializer().Deserialize <PutResult>(new RavenJTokenReader(task1.Result));
                    }
                    catch (AggregateException e)
                    {
                        var we = e.ExtractSingleInnerException() as WebException;
                        if (we == null)
                        {
                            throw;
                        }
                        var httpWebResponse = we.Response as HttpWebResponse;
                        if (httpWebResponse == null ||
                            httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                        {
                            throw;
                        }
                        throw ThrowConcurrencyException(we);
                    }
                });
            })
                   .Unwrap());
        }
Example #14
0
        /// <summary>
        /// Deletes the attachment with the specified key asynchronously
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="etag">The etag.</param>
        public Task DeleteAttachmentAsync(string key, Guid?etag)
        {
            var metadata = new RavenJObject();

            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }

            var request = jsonRequestFactory.CreateHttpJsonRequest(this, url.Static(key), "DELETE", metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);

            return(request.ReadResponseStringAsync());
        }
Example #15
0
        public async Task <HttpResponseMessage> Console(string id)
        {
            var database = await DatabasesLandlord.GetResourceInternal(id).ConfigureAwait(false);

            var script = await ReadJsonObjectAsync <AdminJsScript>().ConfigureAwait(false);

            var console = new AdminJsConsole(database);

            var result = console.ApplyScript(script);

            if (result.Type == JTokenType.Null)
            {
                result = new RavenJValue("OK");
            }
            return(GetMessageWithObject(result));
        }
Example #16
0
        /// <summary>
        /// Puts the document with the specified key in the database
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="etag">The etag.</param>
        /// <param name="document">The document.</param>
        /// <param name="metadata">The metadata.</param>
        public Task <PutResult> PutAsync(string key, Guid?etag, RavenJObject document, RavenJObject metadata)
        {
            if (metadata == null)
            {
                metadata = new RavenJObject();
            }
            var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";

            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }
            var request = jsonRequestFactory.CreateHttpJsonRequest(this, url + "/docs/" + key, method, metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);

            var bytes = Encoding.UTF8.GetBytes(document.ToString());

            return(Task.Factory.FromAsync(request.BeginWrite, request.EndWrite, bytes, null)
                   .ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    throw new InvalidOperationException("Unable to write to server");
                }

                return Task.Factory.FromAsync <string>(request.BeginReadResponseString, request.EndReadResponseString, null)
                .ContinueWith(task1 =>
                {
                    try
                    {
                        return JsonConvert.DeserializeObject <PutResult>(task1.Result, Default.Converters);
                    }
                    catch (WebException e)
                    {
                        var httpWebResponse = e.Response as HttpWebResponse;
                        if (httpWebResponse == null ||
                            httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                        {
                            throw;
                        }
                        throw ThrowConcurrencyException(e);
                    }
                });
            })
                   .Unwrap());
        }
    public bool BeforeStore(string key, object entityInstance, RavenJObject metadata, RavenJObject original)
    {
        if (entityInstance.GetType().Name != "OutboxRecord")
        {
            return(false);
        }

        var dispatched = entityInstance.GetPropertyValue <bool>("Dispatched");

        if (dispatched)
        {
            var dispatchedAt = entityInstance.GetPropertyValue <DateTime>("DispatchedAt");
            var expiry       = dispatchedAt.AddDays(10);
            metadata["Raven-Expiration-Date"] = new RavenJValue(expiry);
        }
        return(false);
    }
        public void UpdateFileMetadata(string filename, RavenJObject metadata)
        {
            var key = CreateKey(filename);

            ushort version;
            var    file = LoadJson(storage.Files, key, writeBatch.Value, out version);

            if (file == null)
            {
                throw new FileNotFoundException(filename);
            }

            if (!metadata.ContainsKey(RavenConstants.MetadataEtagField))
            {
                throw new InvalidOperationException(string.Format("Metadata of file {0} does not contain 'ETag' key", filename));
            }

            var innerMetadata = new RavenJObject(metadata);
            var etag          = innerMetadata.Value <Guid>(RavenConstants.MetadataEtagField);

            innerMetadata.Remove(RavenConstants.MetadataEtagField);

            var existingMetadata = (RavenJObject)file["metadata"];

            if (!innerMetadata.ContainsKey("Content-MD5") && existingMetadata.ContainsKey("Content-MD5"))
            {
                innerMetadata["Content-MD5"] = existingMetadata["Content-MD5"];
            }
            if (!innerMetadata.ContainsKey("RavenFS-Size") && existingMetadata.ContainsKey("RavenFS-Size"))
            {
                innerMetadata["RavenFS-Size"] = existingMetadata["RavenFS-Size"];
            }

            var oldEtag = file.Value <Guid>("etag");

            file["etag"]     = new RavenJValue(etag);
            file["metadata"] = innerMetadata;

            storage.Files.Add(writeBatch.Value, key, file, version);

            var filesByEtag = storage.Files.GetIndex(Tables.Files.Indices.ByEtag);

            filesByEtag.Delete(writeBatch.Value, CreateKey(oldEtag));
            filesByEtag.Add(writeBatch.Value, CreateKey(etag), key);
        }
Example #19
0
        /// <summary>
        /// Persists the provided range of <paramref name="invocations"/> for the provided <paramref name="productName">product</paramref> and <paramref name="version"/>.
        /// </summary>
        /// <param name="productName">Name of the product to store the invocations for.</param>
        /// <param name="version">Version of the product to store the invocations for.</param>
        /// <param name="invocations">A range of <see cref="DbInvocation"/> instances representing the invocations to persist.</param>
        public async Task PersistDbInvocationsAsync(string productName, string version, IEnumerable <DbInvocation> invocations)
        {
            var configuration = await ConfigurationManager.GetOrCreateConfigurationAsync();

            using (var session = Database.DocumentStore.OpenAsyncSession())
            {
                foreach (var invocation in invocations)
                {
                    await session.StoreAsync(invocation, $"{productName}/{version}/{invocation.Signature}");

                    session.SetExpirationIfEnabled(invocation, version, configuration);
                    var metadata = session.Advanced.GetMetadataFor(invocation);
                    metadata["Product"] = new RavenJValue(productName);
                    metadata["Version"] = new RavenJValue(version);
                }

                await session.SaveChangesAsync();
            }
        }
Example #20
0
        private void HandleInternalMetadata(RavenJObject result)
        {
            // Implant a property with "id" value ... if not exists
            var metadata = result.Value <RavenJObject>("@metadata");

            if (metadata == null || string.IsNullOrEmpty(metadata.Value <string>("@id")))
            {
                // if the item has metadata, then nested items will not have it, so we can skip recursing down
                foreach (var nested in result.Select(property => property.Value))
                {
                    var jObject = nested as RavenJObject;
                    if (jObject != null)
                    {
                        HandleInternalMetadata(jObject);
                    }
                    var jArray = nested as RavenJArray;
                    if (jArray == null)
                    {
                        continue;
                    }
                    foreach (var item in jArray.OfType <RavenJObject>())
                    {
                        HandleInternalMetadata(item);
                    }
                }
                return;
            }

            var entityName = metadata.Value <string>(Constants.RavenEntityName);

            var idPropName = sessionOperations.Conventions.FindIdentityPropertyNameFromEntityName(entityName);

            if (result.ContainsKey(idPropName))
            {
                return;
            }

            result[idPropName] = new RavenJValue(metadata.Value <string>("@id"));
        }
        public override void OnPut(string key, RavenJObject document, RavenJObject metadata, Raven.Abstractions.Data.TransactionInformation transactionInformation)
        {
            string databaseName = null;

            if (TryGetDatabase(key, out databaseName))
            {
                var dataDirectory = StorageProvider.GetDirectoryForDatabase(databaseName);

                RavenJToken settingsToken = null;

                if (document.TryGetValue("Settings", out settingsToken))
                {
                    var settingsObject = settingsToken as RavenJObject;

                    if (settingsObject != null)
                    {
                        settingsObject["Raven/DataDir"] = new RavenJValue(dataDirectory.FullName);
                    }
                }
            }

            base.OnPut(key, document, metadata, transactionInformation);
        }
Example #22
0
        private static void EnsureQuotasBundleActivated(RavenJObject settings)
        {
            RavenJToken value;

            if (settings.TryGetValue(Constants.ActiveBundles, out value) == false)
            {
                settings[Constants.ActiveBundles] = value = new RavenJValue(string.Empty);
            }

            var activeBundles = value.Value <string>();
            var bundles       = activeBundles.GetSemicolonSeparatedValues();

            if (bundles.Contains("Quotas", StringComparer.OrdinalIgnoreCase) == false)
            {
                bundles.Add("Quotas");
            }

            int hardLimitInKb;

            if (int.TryParse(ConfigurationManager.AppSettings["Raven/Bundles/LiveTest/Quotas/Size/HardLimitInKB"], out hardLimitInKb) == false)
            {
                hardLimitInKb = QuotasHardLimitInKb;
            }

            int softMarginInKb;

            if (int.TryParse(ConfigurationManager.AppSettings["Raven/Bundles/LiveTest/Quotas/Size/SoftLimitInKB"], out softMarginInKb) == false)
            {
                softMarginInKb = QuotasSoftMarginInKb;
            }

            settings[Constants.ActiveBundles]     = string.Join(";", bundles);
            settings[Constants.SizeHardLimitInKB] = hardLimitInKb;
            settings[Constants.SizeSoftLimitInKB] = softMarginInKb;
            settings[Constants.DocsHardLimit]     = null;
            settings[Constants.DocsSoftLimit]     = null;
        }
Example #23
0
        private PutResult DirectPut(RavenJObject metadata, string key, Guid?etag, RavenJObject document, string operationUrl)
        {
            if (metadata == null)
            {
                metadata = new RavenJObject();
            }
            var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";

            AddTransactionInformation(metadata);
            if (etag != null)
            {
                metadata["ETag"] = new RavenJValue(etag.Value.ToString());
            }
            var request = jsonRequestFactory.CreateHttpJsonRequest(this, operationUrl + "/docs/" + key, method, metadata, credentials, convention);

            request.AddOperationHeaders(OperationsHeaders);
            request.Write(document.ToString());

            string readResponseString;

            try
            {
                readResponseString = request.ReadResponseString();
            }
            catch (WebException e)
            {
                var httpWebResponse = e.Response as HttpWebResponse;
                if (httpWebResponse == null ||
                    httpWebResponse.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
                throw ThrowConcurrencyException(e);
            }
            return(JsonConvert.DeserializeObject <PutResult>(readResponseString, Default.Converters));
        }
Example #24
0
		public void CloningTestsWorksCorrectly()
		{
			var f = new RavenJObject();
			f["1"] = new RavenJValue(1);
			f["2"] = new RavenJValue(2);

			var f1 = (RavenJObject)f.CloneToken();
			f1["2"] = new RavenJValue(3);

			var val = (RavenJValue) f["2"];
			Assert.Equal(2, val.Value);
			val = (RavenJValue)f1["2"];
			Assert.Equal(3, val.Value);

			var f2 = (RavenJObject)f1.CloneToken();
			val = (RavenJValue)f2["2"];
			Assert.Equal(3, val.Value);

			f["2"] = f2;
			f1 = (RavenJObject) f.CloneToken();
			f.Remove("2");
			Assert.Null(f["2"]);
			Assert.NotNull(f1["2"]);
		}
Example #25
0
		private static void AddTransactionInformation(RavenJObject metadata)
		{
			if (Transaction.Current == null)
				return;

			string txInfo = string.Format("{0}, {1}", Transaction.Current.TransactionInformation.DistributedIdentifier, TransactionManager.DefaultTimeout);
			metadata["Raven-Transaction-Information"] = new RavenJValue(txInfo);
		}
Example #26
0
		/// <summary>
		/// Puts the document with the specified key in the database
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="etag">The etag.</param>
		/// <param name="document">The document.</param>
		/// <param name="metadata">The metadata.</param>
		public Task<PutResult> PutAsync(string key, Guid? etag, RavenJObject document, RavenJObject metadata)
		{
			if (metadata == null)
				metadata = new RavenJObject();
			var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";
			if (etag != null)
				metadata["ETag"] = new RavenJValue(etag.Value.ToString());
			var request = jsonRequestFactory.CreateHttpJsonRequest(
					new CreateHttpJsonRequestParams(this, url + "/docs/" + key, method, metadata, credentials, convention)
						.AddOperationHeaders(OperationsHeaders));
			
			return Task.Factory.FromAsync(request.BeginWrite,request.EndWrite,document.ToString(), null)
				.ContinueWith(task =>
				{
					if (task.Exception != null)
						throw new InvalidOperationException("Unable to write to server");

					return request.ReadResponseJsonAsync()
						.ContinueWith(task1 =>
						{
							try
							{
								return convention.CreateSerializer().Deserialize<PutResult>(new RavenJTokenReader(task1.Result));
							}
							catch (AggregateException e)
							{
								var we = e.ExtractSingleInnerException() as WebException;
								if (we == null)
									throw;
								var httpWebResponse = we.Response as HttpWebResponse;
								if (httpWebResponse == null ||
									httpWebResponse.StatusCode != HttpStatusCode.Conflict)
									throw;
								throw ThrowConcurrencyException(we);
							}
						});
				})
				.Unwrap();
		}
 public override void OnPut(string key, byte[] data, RavenJObject metadata)
 {
     metadata["created_at"] = new RavenJValue(new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
 }
Example #28
0
		/// <summary>
		/// Puts the document with the specified key in the database
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="etag">The etag.</param>
		/// <param name="document">The document.</param>
		/// <param name="metadata">The metadata.</param>
		public Task<PutResult> PutAsync(string key, Guid? etag, RavenJObject document, RavenJObject metadata)
		{
			if (metadata == null)
				metadata = new RavenJObject();
			var method = String.IsNullOrEmpty(key) ? "POST" : "PUT";
			if (etag != null)
				metadata["ETag"] = new RavenJValue(etag.Value.ToString());
			var request = jsonRequestFactory.CreateHttpJsonRequest(this, url + "/docs/" + key, method, metadata, credentials, convention);
			request.AddOperationHeaders(OperationsHeaders);

			
			return Task.Factory.FromAsync(request.BeginWrite,request.EndWrite,document.ToString(), null)
				.ContinueWith(task =>
				{
					if (task.Exception != null)
						throw new InvalidOperationException("Unable to write to server");

					return Task.Factory.FromAsync<string>(request.BeginReadResponseString,request.EndReadResponseString, null)
						.ContinueWith(task1 =>
						{
							try
							{
								return JsonConvert.DeserializeObject<PutResult>(task1.Result, Default.Converters);
							}
							catch (WebException e)
							{
								var httpWebResponse = e.Response as HttpWebResponse;
								if (httpWebResponse == null ||
									httpWebResponse.StatusCode != HttpStatusCode.Conflict)
									throw;
								throw ThrowConcurrencyException(e);
							}
						});
				})
				.Unwrap();
		}
Example #29
0
		internal void AddValue(RavenJValue value, JsonToken token)
		{
            if (_tokenStack.Count != 0)
            {
                var currentToken = this.CurrentToken;
                switch (currentToken.Type)
                {
                    case JTokenType.Object:
                        ((RavenJObject)currentToken)[_tempPropName] = value;
                        _tempPropName = null;
                        break;
                    case JTokenType.Array:
                        ((RavenJArray)currentToken).Add(value);
                        break;
                    default:
                        throw new JsonWriterException("Unexpected token: " + token);
                }
            }
            else _value = value;
		}
Example #30
0
		public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
		{
			document["created_at"] = new RavenJValue(new DateTime(2010, 2, 13, 18, 26, 48, 506, DateTimeKind.Utc));
		}
Example #31
0
 public void UpdateLastModified(RavenJObject metadata)
 {
     // internally keep last modified date with millisecond precision
     metadata["Last-Modified"] = DateTime.UtcNow.ToString("d MMM yyyy H:m:s.fffff 'GMT'", CultureInfo.InvariantCulture);
     metadata["ETag"] = new RavenJValue(uuidGenerator.CreateSequentialUuid());
 }
Example #32
0
 public void UpdateLastModified(RavenJObject metadata)
 {
     // internally keep last modified date with millisecond precision
     metadata["Last-Modified"] = DateTime.UtcNow.ToString("d MMM yyyy H:m:s.fffff 'GMT'", CultureInfo.InvariantCulture);
     metadata["ETag"]          = new RavenJValue(uuidGenerator.CreateSequentialUuid());
 }
Example #33
0
		private void SetProperty(PatchRequest patchCmd, string propName, RavenJValue property)
		{
			EnsurePreviousValueMatchCurrentValue(patchCmd, property);
			if (property == null)
			{
				document[propName] = patchCmd.Value;
				return;
			}
			property.Value = (patchCmd.Value as RavenJValue).Value;
		}
        public void UpdateFileMetadata(string filename, RavenJObject metadata)
        {           
            var key = CreateKey(filename);

            ushort version;
            var file = LoadJson(storage.Files, key, writeBatch.Value, out version);
            if (file == null)
                throw new FileNotFoundException(filename);

            if (!metadata.ContainsKey("ETag"))
                throw new InvalidOperationException(string.Format("Metadata of file {0} does not contain 'ETag' key", filename));

            var innerMetadata = new RavenJObject(metadata);
            var etag = innerMetadata.Value<Guid>("ETag");
            innerMetadata.Remove("ETag");

            var existingMetadata = (RavenJObject) file["metadata"];
            if (existingMetadata.ContainsKey("Content-MD5"))
                innerMetadata["Content-MD5"] = existingMetadata["Content-MD5"];

            var oldEtag = file.Value<Guid>("etag");

            file["etag"] = new RavenJValue(etag);
            file["metadata"] = innerMetadata;

            storage.Files.Add(writeBatch.Value, key, file, version);

            var filesByEtag = storage.Files.GetIndex(Tables.Files.Indices.ByEtag);

            filesByEtag.Delete(writeBatch.Value, CreateKey(oldEtag));
            filesByEtag.Add(writeBatch.Value, CreateKey(etag), key);
        }
		public override void OnPut(string key, byte[] data, RavenJObject metadata)
		{
			metadata["created_at"] = new RavenJValue(new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
		}
Example #36
0
 public static RavenJObject WithETag(this RavenJObject metadata, Guid etag)
 {
     metadata["ETag"] = new RavenJValue(etag);
     return(metadata);
 }
Example #37
0
        //===============================================================
        public void Update(String pathToProperty, String json, UpdateType updateType = UpdateType.Set)
        {
            if (Object == null)
            {
                return;
            }

            if (String.IsNullOrEmpty(pathToProperty))
            {
                Update(json, updateType);
                return;
            }

            var patchCommandType = ToPatchType(updateType);
            var propertyNames    = pathToProperty.Split('.');
            var baseRequest      = new PatchRequest
            {
                Type   = PatchCommandType.Modify,
                Name   = propertyNames.First(),
                Nested = new PatchRequest[1],
            };

            var currRequest  = baseRequest;
            var currProperty = Object.GetType().GetProperty(propertyNames.First());

            foreach (var propertyName in propertyNames.Skip(1).Take(propertyNames.Length - 2))
            {
                if (currProperty == null)
                {
                    return;
                }

                currRequest.Nested[0] = new PatchRequest
                {
                    Type   = PatchCommandType.Modify,
                    Name   = propertyName,
                    Nested = new PatchRequest[1],
                };

                currRequest  = currRequest.Nested[0];
                currProperty = currProperty.PropertyType.GetProperty(propertyName);
            }

            var error = "";

            if (!IsValidUpdate(json, updateType, currProperty.PropertyType, ref error))
            {
                throw new ArgumentException(error, "json");
            }

            var obj     = JObject.Parse(json);
            var patches = obj.Properties().Where(x => currProperty.PropertyType.GetProperty(x.Name) != null)
                          .Select(x => new PatchRequest
            {
                Type  = patchCommandType,
                Name  = x.Name,
                Value = RavenJValue.FromObject(x.Value)
            }).ToArray();

            currRequest.Nested = patches;

            Session.Advanced.Defer(new PatchCommandData {
                Key = KeyGenerator(Object), Patches = new[] { baseRequest }
            });
            Session.SaveChanges();
        }
        /// <summary>
        /// If the newItem parameter is true, the SetAndReleaseItemExclusive method inserts a new item into the data store with the supplied values.
        /// Otherwise, the existing item in the data store is updated with the supplied values, and any lock on the data is released.
        /// </summary>
        /// <param name="context">The HttpContext instance for the current request.</param>
        /// <param name="id">The session identifier.</param>
        /// <param name="item">The current session values to be stored.</param>
        /// <param name="lockId">The lock identifier for the current request.</param>
        /// <param name="newItem">If true, a new item is inserted into the store. Otherwise, the existing item in
        /// the data store is updated with the supplied values, and any lock on the data is released.</param>
        public override void SetAndReleaseItemExclusive(
            HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            try
            {
                Logger.Debug(
                    " Beginning SetAndReleaseItemExclusive. SessionId={0}, LockId={1}, newItem={2}", id, lockId, newItem);

                var serializedItems = Serialize((SessionStateItemCollection)item.Items);

                var store = storeLocator();
                using (var documentSession = store.OpenSession())
                {
                    // if we get a concurrency conflict, then we want to know about it
                    documentSession.Advanced.UseOptimisticConcurrency = true;

                    SessionState sessionState;
                    if (newItem)
                    {
                        sessionState = documentSession.Query<SessionState>()
                            .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
                            .SingleOrDefault(x => x.SessionId == id && x.ApplicationName == ApplicationName && x.Expires < DateTime.UtcNow);

                        if (sessionState != null)
                            throw new InvalidOperationException(string.Format("Item aleady exist with SessionId={0} and ApplicationName={1}", id, lockId));

                        sessionState = new SessionState(id, ApplicationName);
                        documentSession.Store(sessionState);
                    }
                    else
                    {
                        sessionState = documentSession.Query<SessionState>()
                            .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
                            .Single(x => x.SessionId == id && x.ApplicationName == ApplicationName && x.LockId == (int)lockId);
                    }

                    var expiryDate = DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes);
                    var ravenJObject = documentSession.Advanced.GetMetadataFor(sessionState);
                    ravenJObject["Raven-Expiration-Date"] = new RavenJValue(expiryDate);
                    sessionState.Expires = expiryDate;
                    sessionState.SessionItems = serializedItems;
                    sessionState.Locked = false;

                    documentSession.SaveChanges();
                }

                Logger.Debug("Completed SetAndReleaseItemExclusive. SessionId={0}, LockId={1}, newItem={2}", id, lockId, newItem);
            }
            catch (Exception ex)
            {
                Logger.ErrorException(string.Format("Error during SetAndReleaseItemExclusive. SessionId={0}, LockId={1}, newItem={2}", id, lockId, newItem), ex);
                throw;
            }
        }
Example #39
0
		internal void AddValue(RavenJValue value, JsonToken token)
		{
			if (_tokenStack.Count == 0)
				_value = value;
			else
			{
				switch (CurrentToken.Type)
				{
					case JTokenType.Object:
						if (string.IsNullOrEmpty(_tempPropName))
							throw new JsonWriterException("Unexpected value token");
						((RavenJObject)CurrentToken)[_tempPropName] = value;
						_tempPropName = null;
						break;
					case JTokenType.Array:
						if (!string.IsNullOrEmpty(_tempPropName))
							throw new JsonWriterException("Unexpected property token");
						((RavenJArray)CurrentToken).Add(value);
						break;
					default:
						throw new JsonWriterException("Unexpected token: " + token);
				}
			}
		}
Example #40
0
 public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
 {
     document["created_at"] = new RavenJValue(new DateTime(2010, 2, 13, 18, 26, 48, 506, DateTimeKind.Utc));
 }
        private RavenJObject RetrieveMetadata()
        {
            var metadataAsString = Api.RetrieveColumnAsString(session, Files, tableColumnsCache.FilesColumns["metadata"], Encoding.Unicode);

            var metadata = RavenJObject.Parse(metadataAsString);
            metadata["ETag"] = new RavenJValue(Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]).TransfromToGuidWithProperSorting());
            
            return metadata;
        }