Exemple #1
0
        public void SuccessTest1()
        {
            using (var documentStore = NewDocumentStore())
            {
                dynamic expando = new ExpandoObject();

                using (var session = documentStore.OpenSession())
                {
                    session.Store(expando);

                    var metadata = session.Advanced.GetMetadataFor((ExpandoObject)expando);

                    metadata[PropertyName] = RavenJToken.FromObject(true);

                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    var loaded = session.Load <dynamic>((string)expando.Id);

                    var metadata = session.Advanced.GetMetadataFor((DynamicJsonObject)loaded);

                    var token = metadata[PropertyName];

                    Assert.NotNull(token);
                    Assert.True(token.Value <bool>());
                }
            }
        }
Exemple #2
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>();
            }
        }
Exemple #3
0
        public void CanUpdateByIndex()
        {
            var entity = new Company {
                Name = "Company"
            };

            using (var session = documentStore.OpenSession())
            {
                session.Store(entity);
                session.SaveChanges();

                session.Advanced.DocumentQuery <Company>().WaitForNonStaleResults().ToArray();// wait for the index to settle down
            }

            documentStore.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", new IndexQuery
            {
                Query = "Tag:[[Companies]]"
            }, new[]
            {
                new PatchRequest
                {
                    Type  = PatchCommandType.Set,
                    Name  = "Name",
                    Value = RavenJToken.FromObject("Another Company")
                },
            }, options: null).WaitForCompletion();

            using (var session = documentStore.OpenSession())
            {
                Assert.Equal("Another Company", session.Load <Company>(entity.Id).Name);
            }
        }
        public override void OnPut(string key, Stream data, RavenJObject metadata)
        {
            if (key.StartsWith("Raven/"))             // we don't deal with system attachment
            {
                return;
            }
            using (Database.DisableAllTriggersForCurrentThread())
            {
                var attachmentMetadata = GetAttachmentMetadata(key);
                if (attachmentMetadata != null)
                {
                    var history = attachmentMetadata.Value <RavenJArray>(Constants.RavenReplicationHistory) ?? new RavenJArray();
                    metadata[Constants.RavenReplicationHistory] = history;

                    if (attachmentMetadata.ContainsKey(Constants.RavenReplicationVersion) &&
                        attachmentMetadata.ContainsKey(Constants.RavenReplicationSource))
                    {
                        history.Add(new RavenJObject
                        {
                            { Constants.RavenReplicationVersion, attachmentMetadata[Constants.RavenReplicationVersion] },
                            { Constants.RavenReplicationSource, attachmentMetadata[Constants.RavenReplicationSource] }
                        });
                    }

                    if (history.Length > Constants.ChangeHistoryLength)
                    {
                        history.RemoveAt(0);
                    }
                }

                metadata[Constants.RavenReplicationVersion] = RavenJToken.FromObject(HiLo.NextId());
                metadata[Constants.RavenReplicationSource]  = RavenJToken.FromObject(Database.TransactionalStorage.Id);
            }
        }
Exemple #5
0
        public void can_update_a_doc_within_transaction_scope()
        {
            using (var documentStore = NewDocumentStore())
            {
                var          id1   = Guid.NewGuid();
                RavenJObject dummy = null;

                using (TransactionScope trnx = new TransactionScope())
                {
                    using (var session = documentStore.OpenSession())
                    {
                        dummy = new RavenJObject();
                        dummy.Add("Name", "This is the object content");
                        dummy.Add("Id", RavenJToken.FromObject(id1));
                        session.Store(dummy);
                        session.SaveChanges();
                    }
                    using (var session = documentStore.OpenSession())
                    {
                        session.Store(dummy);
                        session.SaveChanges();
                    }
                    trnx.Complete();
                }
            }
        }
Exemple #6
0
        public override IEnumerable <Row> Execute(IEnumerable <Row> rows)
        {
            int count = 0;

            foreach (var partitionedRows in rows.Partition(Constants.BatchSize))
            {
                List <PutCommandData> commands = new List <PutCommandData>();

                foreach (var row in partitionedRows)
                {
                    RavenJObject obj = new RavenJObject();

                    foreach (object key in row.Keys)
                    {
                        obj.Add((string)key, RavenJToken.FromObject(row[key]));
                    }

                    commands.Add(new PutCommandData()
                    {
                        Document = obj,
                        Metadata = new RavenJObject
                        {
                            { "Raven-Entity-Name", new RavenJValue(collection) }
                        },
                        Key = generateKey(obj)
                    });
                }

                count++;
                WriteCommandsTo(collection + " #" + count.ToString("00000") + ".json", commands);
            }
            yield break;
        }
Exemple #7
0
        public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            VersioningConfiguration versioningConfiguration;

            if (metadata.ContainsKey(Constants.RavenCreateVersion))
            {
                metadata.__ExternalState[Constants.RavenCreateVersion] = metadata[Constants.RavenCreateVersion];
                metadata.Remove(Constants.RavenCreateVersion);
            }

            if (TryGetVersioningConfiguration(key, metadata, out versioningConfiguration) == false)
            {
                return;
            }

            var revision = GetNextRevisionNumber(key);

            using (Database.DisableAllTriggersForCurrentThread())
            {
                RemoveOldRevisions(key, revision, versioningConfiguration, transactionInformation);
            }
            metadata.__ExternalState["Next-Revision"] = revision;

            metadata.__ExternalState["Parent-Revision"] = metadata.Value <string>(VersioningUtil.RavenDocumentRevision);

            metadata[VersioningUtil.RavenDocumentRevisionStatus] = RavenJToken.FromObject("Current");
            metadata[VersioningUtil.RavenDocumentRevision]       = RavenJToken.FromObject(revision);
        }
Exemple #8
0
        public override void OnPut(string name, RavenJObject headers)
        {
            if (headers.ContainsKey(Constants.RavenCreateVersion))
            {
                headers.__ExternalState[Constants.RavenCreateVersion] = headers[Constants.RavenCreateVersion];
                headers.Remove(Constants.RavenCreateVersion);
            }

            FileSystem.Storage.Batch(accessor =>
            {
                VersioningConfiguration versioningConfiguration;
                if (TryGetVersioningConfiguration(name, headers, accessor, out versioningConfiguration) == false)
                {
                    return;
                }

                var revision = GetNextRevisionNumber(name, accessor);

                using (FileSystem.DisableAllTriggersForCurrentThread())
                {
                    RemoveOldRevisions(name, revision, versioningConfiguration);
                }

                headers.__ExternalState["Next-Revision"]   = revision;
                headers.__ExternalState["Parent-Revision"] = headers.Value <string>(VersioningUtil.RavenFileRevision);

                headers[VersioningUtil.RavenFileRevisionStatus] = RavenJToken.FromObject("Current");
                headers[VersioningUtil.RavenFileRevision]       = RavenJToken.FromObject(revision);
            });
        }
Exemple #9
0
        public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            VersioningConfiguration versioningConfiguration;

            if (TryGetVersioningConfiguration(key, metadata, out versioningConfiguration) == false)
            {
                return;
            }

            int revision = 0;

            Database.TransactionalStorage.Batch(accessor =>
            {
                revision = (int)accessor.General.GetNextIdentityValue(key + "/revisions/");
            });
            using (Database.DisableAllTriggersForCurrentThread())
            {
                RemoveOldRevisions(key, revision, versioningConfiguration, transactionInformation);
            }
            metadata.__ExternalState["Next-Revision"] = revision;

            metadata.__ExternalState["Parent-Revision"] = metadata.Value <string>(VersioningUtil.RavenDocumentRevision);

            metadata[VersioningUtil.RavenDocumentRevisionStatus] = RavenJToken.FromObject("Current");
            metadata[VersioningUtil.RavenDocumentRevision]       = RavenJToken.FromObject(revision);
        }
Exemple #10
0
        public void Adding_DateTime_to_metadata_should_fetch_it_as_DateTime(string expectedDateTimeString)
        {
            using (var _documentStore = NewRemoteDocumentStore(fiddler: true, requestedStorage: "esent", runInMemory: false))
            {
                // Arrange
                string bookId;
                var    expectedDateTime = DateTime.Parse(expectedDateTimeString);

                using (var session = _documentStore.OpenSession())
                {
                    var entity = new Book {
                        Author = "dane"
                    };
                    session.Store(entity);
                    session.SaveChanges();
                    bookId = entity.Id;
                }

                // Act
                // Add metadata to the entity
                using (var session = _documentStore.OpenSession())
                {
                    var book     = session.Load <Book>(bookId);
                    var metadata = session.Advanced.GetMetadataFor(book);
                    metadata.Add("DateTime-ToCheck", RavenJToken.FromObject(expectedDateTime));
                    session.SaveChanges();
                }

                // Try get metadata
                using (var session = _documentStore.OpenSession())
                {
                    var entity   = session.Load <Book>(bookId);
                    var metadata = session.Advanced.GetMetadataFor(entity);
                    var result   = metadata.Value <DateTime>("DateTime-ToCheck");                  // No exception is thrown here
                    Assert.IsType <DateTime>(result);
                    Assert.Equal(expectedDateTime, result);
                }

                // Change the entity
                using (var session = _documentStore.OpenSession())
                {
                    var book = session.Load <Book>(bookId);
                    book.Author = "Jane Doe";
                    session.SaveChanges();
                }

                // Assert
                // Try to get the metadata back as DateTime
                using (var session = _documentStore.OpenSession())
                {
                    var entity   = session.Load <Book>(bookId);
                    var metadata = session.Advanced.GetMetadataFor(entity);

                    var result = new DateTime();
                    Assert.DoesNotThrow(() => result = metadata.Value <DateTime>("DateTime-ToCheck"));                    // An exception should not be thrown here, after changing the entity

                    Assert.Equal(expectedDateTime, result);
                }
            }
        }
Exemple #11
0
        public void AfterOptimizeUnCommittedDataIsStillThere()
        {
            for (int i = 0; i < 16; i++)
            {
                Table.Put(RavenJToken.FromObject(i), new byte[512]);
            }

            for (int i = 0; i < 16; i++)
            {
                Table.Remove(RavenJToken.FromObject(i));
            }

            //var txId2 = Guid.NewGuid();
            Table.Put(RavenJToken.FromObject("a"), new byte[512]);


            Commit();
            var oldSize = PersistentSource.Read(log => log.Length);

            PerformIdleTasks();

            Assert.True(oldSize > PersistentSource.Read(log => log.Length));

            Assert.NotNull(
                Table.Read(RavenJToken.FromObject("a"))
                );
        }
Exemple #12
0
        public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            if (key.StartsWith("Raven/"))             // we don't deal with system documents
            {
                return;
            }
            var doc = Database.Get(key, null);

            if (doc != null)
            {
                var history = doc.Metadata.Value <RavenJArray>(ReplicationConstants.RavenReplicationHistory) ?? new RavenJArray();
                metadata[ReplicationConstants.RavenReplicationHistory] = history;

                history.Add(new RavenJObject
                {
                    { ReplicationConstants.RavenReplicationVersion, doc.Metadata[ReplicationConstants.RavenReplicationVersion] },
                    { ReplicationConstants.RavenReplicationSource, doc.Metadata[ReplicationConstants.RavenReplicationSource] }
                });

                if (history.Length > ReplicationConstants.ChangeHistoryLength)
                {
                    history.RemoveAt(0);
                }
            }
            metadata[ReplicationConstants.RavenReplicationVersion] = RavenJToken.FromObject(hiLo.NextId());
            metadata[ReplicationConstants.RavenReplicationSource]  = RavenJToken.FromObject(Database.TransactionalStorage.Id);
        }
Exemple #13
0
        public void FailureTest()
        {
            using (var documentStore = NewDocumentStore())
            {
                dynamic expando = new ExpandoObject();

                using (var session = documentStore.OpenSession())
                {
                    session.Store(expando);

                    RavenJObject metadata =
                        session.Advanced.GetMetadataFor((ExpandoObject)expando);

                    metadata[PropertyName] = RavenJToken.FromObject(true);

                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    dynamic loaded =
                        session.Advanced.DocumentQuery <dynamic>().WhereEquals("@metadata." + PropertyName, true)
                        .FirstOrDefault();

                    Assert.NotNull(loaded);
                }
            }
        }
Exemple #14
0
        public void SuccessTest2()
        {
            using (var documentStore = NewDocumentStore())
            {
                dynamic expando = new ExpandoObject();

                using (var session = documentStore.OpenSession())
                {
                    session.Store(expando);

                    RavenJObject metadata =
                        session.Advanced.GetMetadataFor((ExpandoObject)expando);

                    metadata[PropertyName] = RavenJToken.FromObject(true);

                    session.SaveChanges();
                }

                using (var session = documentStore.OpenSession())
                {
                    dynamic loaded = session.Advanced.DocumentQuery <dynamic>()
                                     .WhereEquals("@metadata.Raven-Entity-Name",
                                                  documentStore.Conventions.GetTypeTagName(typeof(ExpandoObject)))
                                     .FirstOrDefault();

                    Assert.NotNull(loaded);
                }
            }
        }
        private void ReplicateDocument(IStorageActionsAccessor actions, string id, RavenJObject metadata, RavenJObject document, string src)
        {
            var existingDoc = actions.Documents.DocumentByKey(id, null);

            if (existingDoc == null)
            {
                log.DebugFormat("New document {0} replicated successfully from {1}", id, src);
                actions.Documents.AddDocument(id, Guid.Empty, document, metadata);
                return;
            }

            var existingDocumentIsInConflict = existingDoc.Metadata[ReplicationConstants.RavenReplicationConflict] != null;

            if (existingDocumentIsInConflict == false &&                 // if the current document is not in conflict, we can continue without having to keep conflict semantics
                (IsDirectChildOfCurrentDocument(existingDoc, metadata))) // this update is direct child of the existing doc, so we are fine with overwriting this
            {
                log.DebugFormat("Existing document {0} replicated successfully from {1}", id, src);
                actions.Documents.AddDocument(id, null, document, metadata);
                return;
            }


            var newDocumentConflictId = id + "/conflicts/" +
                                        metadata.Value <string>(ReplicationConstants.RavenReplicationSource) + "/" +
                                        metadata.Value <string>("@etag");

            metadata.Add(ReplicationConstants.RavenReplicationConflict, RavenJToken.FromObject(true));
            actions.Documents.AddDocument(newDocumentConflictId, null, document, metadata);

            if (existingDocumentIsInConflict) // the existing document is in conflict
            {
                log.DebugFormat("Conflicted document {0} has a new version from {1}, adding to conflicted documents", id, src);

                // just update the current doc with the new conflict document
                existingDoc.DataAsJson.Value <RavenJArray>("Conflicts").Add(RavenJToken.FromObject(newDocumentConflictId));
                actions.Documents.AddDocument(id, existingDoc.Etag, existingDoc.DataAsJson, existingDoc.Metadata);
                return;
            }
            log.DebugFormat("Existing document {0} is in conflict with replicated version from {1}, marking document as conflicted", id, src);

            // we have a new conflict
            // move the existing doc to a conflict and create a conflict document
            var existingDocumentConflictId = id + "/conflicts/" + Database.TransactionalStorage.Id + "/" + existingDoc.Etag;

            existingDoc.Metadata.Add(ReplicationConstants.RavenReplicationConflict, RavenJToken.FromObject(true));
            actions.Documents.AddDocument(existingDocumentConflictId, null, existingDoc.DataAsJson, existingDoc.Metadata);
            actions.Documents.AddDocument(id, null,
                                          new RavenJObject
            {
                {
                    "Conflicts", new RavenJArray(existingDocumentConflictId, newDocumentConflictId)
                }
            },
                                          new RavenJObject
            {
                { ReplicationConstants.RavenReplicationConflict, true },
                { "@Http-Status-Code", 409 },
                { "@Http-Status-Description", "Conflict" }
            });
        }
        public override void OnPut(string key,
                                   RavenJObject document,
                                   RavenJObject metadata,
                                   TransactionInformation transactionInformation)
        {
            Contract.Assume(!string.IsNullOrWhiteSpace(key));

            RavenJToken versionToken;

            if (!document.TryGetValue("Revision", out versionToken) || key.Contains(RevisionSegment))
            {
                return;
            }

            var newRevision     = versionToken.Value <int>();
            var currentRevision = metadata.ContainsKey(RavenDocumentRevision) ? metadata[RavenDocumentRevision].Value <int>() : 0;

            metadata[RavenDocumentRevisionStatus] = RavenJToken.FromObject("Current");

            //if we have a higher revision number than the existing then put a new revision
            if (newRevision > currentRevision)
            {
                metadata[RavenDocumentRevision] = RavenJToken.FromObject(versionToken.Value <int>());
                metadata.__ExternalState[RavenDocumentRevision] = metadata[RavenDocumentRevision];
            }
        }
Exemple #17
0
        public string PutRevisionFile(string name, long?size, RavenJObject metadata)
        {
            string revisionFile = null;

            fileSystem.Storage.Batch(accessor =>
            {
                FileVersioningConfiguration versioningConfiguration;
                if (TryGetVersioningConfiguration(name, metadata, accessor, out versioningConfiguration) == false)
                {
                    return;
                }

                using (fileSystem.DisableAllTriggersForCurrentThread())
                {
                    var copyHeaders = new RavenJObject(metadata);
                    copyHeaders[VersioningUtil.RavenFileRevisionStatus] = RavenJToken.FromObject("Historical");
                    copyHeaders[Constants.RavenReadOnly] = true;
                    copyHeaders.Remove(VersioningUtil.RavenFileRevision);
                    object parentRevision;
                    metadata.__ExternalState.TryGetValue("Parent-Revision", out parentRevision);
                    if (parentRevision != null)
                    {
                        copyHeaders[VersioningUtil.RavenFileParentRevision] = name + "/revisions/" + parentRevision;
                    }

                    object value;
                    metadata.__ExternalState.TryGetValue("Next-Revision", out value);

                    revisionFile = name + "/revisions/" + value;
                    accessor.PutFile(revisionFile, size, copyHeaders);
                }
            });

            return(revisionFile);
        }
Exemple #18
0
        public RavenJToken ApplyScript(AdminJsScript script)
        {
            Engine jintEngine;

            try
            {
                jintEngine = CreateEngine(script);
            }
            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 + script.Script, e);
            }

            var result = jintEngine.Invoke("ExecuteAdminScript", database).ToObject();

            return(RavenJToken.FromObject(result));
        }
Exemple #19
0
        public void CannotModifySnapshotUsingPatchAddToArray()
        {
            using (var _store = NewDocumentStore())
            {
                var item = new TestItem {
                    Items = new int[] { 1, 2, 3 }
                };
                using (var session = _store.OpenSession())
                {
                    session.Store(item);
                    session.SaveChanges();
                }

                using (var session = _store.OpenSession())
                {
                    session.Advanced.DocumentStore.DatabaseCommands.Patch(
                        item.Id,
                        new[] {
                        new PatchRequest()
                        {
                            Type  = PatchCommandType.Add,
                            Name  = "Items",
                            Value = RavenJToken.FromObject(1)
                        }
                    });
                    session.SaveChanges();
                }
            }
        }
        public void SuccessTest1()
        {
            using (IDocumentStore documentStore = new EmbeddableDocumentStore
            {
                RunInMemory = true
            }.Initialize())
            {
                dynamic expando = new ExpandoObject();

                using (IDocumentSession session = documentStore.OpenSession())
                {
                    session.Store(expando);

                    RavenJObject metadata =
                        session.Advanced.GetMetadataFor((ExpandoObject)expando);

                    metadata[PropertyName] = RavenJToken.FromObject(true);

                    session.SaveChanges();
                }

                using (IDocumentSession session = documentStore.OpenSession())
                {
                    var loaded =
                        session.Load <dynamic>((string)expando.Id);

                    RavenJObject metadata =
                        session.Advanced.GetMetadataFor((DynamicJsonObject)loaded);
                    RavenJToken token = metadata[PropertyName];

                    Assert.NotNull(token);
                    Assert.True(token.Value <bool>());
                }
            }
        }
Exemple #21
0
        public override void OnPut(string key, RavenJObject document, RavenJObject metadata, TransactionInformation transactionInformation)
        {
            if (key.StartsWith("Raven/", StringComparison.InvariantCultureIgnoreCase) &&             // we don't deal with system documents
                key.StartsWith("Raven/Hilo/", StringComparison.InvariantCultureIgnoreCase) == false) // except for hilos
            {
                return;
            }
            using (Database.DisableAllTriggersForCurrentThread())
            {
                var documentMetadata = GetDocumentMetadata(key);
                if (documentMetadata != null)
                {
                    var history = documentMetadata.Value <RavenJArray>(Constants.RavenReplicationHistory) ?? new RavenJArray();
                    metadata[Constants.RavenReplicationHistory] = history;

                    if (documentMetadata.ContainsKey(Constants.RavenReplicationVersion) &&
                        documentMetadata.ContainsKey(Constants.RavenReplicationSource))
                    {
                        history.Add(new RavenJObject
                        {
                            { Constants.RavenReplicationVersion, documentMetadata[Constants.RavenReplicationVersion] },
                            { Constants.RavenReplicationSource, documentMetadata[Constants.RavenReplicationSource] }
                        });
                    }

                    if (history.Length > Constants.ChangeHistoryLength)
                    {
                        history.RemoveAt(0);
                    }
                }

                metadata[Constants.RavenReplicationVersion] = RavenJToken.FromObject(HiLo.NextId());
                metadata[Constants.RavenReplicationSource]  = RavenJToken.FromObject(Database.TransactionalStorage.Id);
            }
        }
        public void FailureTest()
        {
            using (IDocumentStore documentStore = new EmbeddableDocumentStore
            {
                RunInMemory = true
            }.Initialize())
            {
                dynamic expando = new ExpandoObject();

                using (IDocumentSession session = documentStore.OpenSession())
                {
                    session.Store(expando);

                    RavenJObject metadata =
                        session.Advanced.GetMetadataFor((ExpandoObject)expando);

                    metadata[PropertyName] = RavenJToken.FromObject(true);

                    session.SaveChanges();
                }

                using (IDocumentSession session = documentStore.OpenSession())
                {
                    dynamic loaded =
                        session.Advanced.LuceneQuery <dynamic>().WhereEquals("@metadata." + PropertyName, true)
                        .FirstOrDefault();

                    Assert.NotNull(loaded);
                }
            }
        }
Exemple #23
0
        public override void OnPut(string key, byte[] data, RavenJObject metadata)
        {
            if (key.StartsWith("Raven/")) // we don't deal with system attachment
            {
                return;
            }
            var attachment = Database.GetStatic(key);

            if (attachment != null)
            {
                var history = attachment.Metadata.Value <RavenJArray>(ReplicationConstants.RavenReplicationHistory) ??
                              new RavenJArray();
                metadata[ReplicationConstants.RavenReplicationHistory] = history;

                history.Add(new RavenJObject
                {
                    { ReplicationConstants.RavenReplicationVersion, attachment.Metadata[ReplicationConstants.RavenReplicationVersion] },
                    { ReplicationConstants.RavenReplicationSource, attachment.Metadata[ReplicationConstants.RavenReplicationSource] }
                });

                if (history.Length > ReplicationConstants.ChangeHistoryLength)
                {
                    history.RemoveAt(0);
                }
            }
            metadata[ReplicationConstants.RavenReplicationVersion] = RavenJToken.FromObject(hiLo.NextId());
            metadata[ReplicationConstants.RavenReplicationSource]  = RavenJToken.FromObject(Database.TransactionalStorage.Id);
        }
        public async Task <CanJoinResult> SendJoinServerInternalAsync(NodeConnectionInfo leaderNode, NodeConnectionInfo newNode)
        {
            var url = leaderNode.GetAbsoluteUri() + "admin/cluster/join";

            using (var request = CreateRequest(leaderNode, url, HttpMethods.Post))
            {
                var response = await request.WriteAsync(() => new JsonContent(RavenJToken.FromObject(newNode))).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    return(CanJoinResult.CanJoin);
                }

                switch (response.StatusCode)
                {
                case HttpStatusCode.Conflict:
                    return(CanJoinResult.IsNonEmpty);

                case HttpStatusCode.NotModified:
                    return(CanJoinResult.AlreadyJoined);

                case HttpStatusCode.NotAcceptable:
                    return(CanJoinResult.InAnotherCluster);

                default:
                    throw await CreateErrorResponseExceptionAsync(response).ConfigureAwait(false);
                }
            }
        }
        public override void AfterPut(string key, RavenJObject document, RavenJObject metadata, Etag etag, TransactionInformation transactionInformation)
        {
            VersioningConfiguration versioningConfiguration;

            if (TryGetVersioningConfiguration(key, metadata, out versioningConfiguration) == false)
            {
                return;
            }

            using (Database.DisableAllTriggersForCurrentThread())
            {
                var copyMetadata = new RavenJObject(metadata);
                copyMetadata[VersioningUtil.RavenDocumentRevisionStatus] = RavenJToken.FromObject("Historical");
                copyMetadata[Constants.RavenReadOnly] = true;
                copyMetadata.Remove(VersioningUtil.RavenDocumentRevision);
                object parentRevision;
                metadata.__ExternalState.TryGetValue("Parent-Revision", out parentRevision);
                if (parentRevision != null)
                {
                    copyMetadata[VersioningUtil.RavenDocumentParentRevision] = key + "/revisions/" + parentRevision;
                    copyMetadata[VersioningUtil.RavenDocumentParentRevision] = key + "/revisions/" + parentRevision;
                }

                object value;
                metadata.__ExternalState.TryGetValue("Next-Revision", out value);
                Database.Put(key + "/revisions/" + value, null, (RavenJObject)document.CreateSnapshot(), copyMetadata,
                             transactionInformation);
            }
        }
        public override void Respond(IHttpContext context)
        {
            var src = context.Request.QueryString["from"];

            if (string.IsNullOrEmpty(src))
            {
                context.SetStatusToBadRequest();
                return;
            }
            while (src.EndsWith("/"))
            {
                src = src.Substring(0, src.Length - 1);                // remove last /, because that has special meaning for Raven
            }
            if (string.IsNullOrEmpty(src))
            {
                context.SetStatusToBadRequest();
                return;
            }
            var array = context.ReadJsonArray();

            using (Database.DisableAllTriggersForCurrentThread())
            {
                Database.TransactionalStorage.Batch(actions =>
                {
                    string lastEtag = Guid.Empty.ToString();
                    foreach (RavenJObject document in array)
                    {
                        var metadata = document.Value <RavenJObject>("@metadata");
                        if (metadata[ReplicationConstants.RavenReplicationSource] == null)
                        {
                            // not sure why, old document from when the user didn't have replciation
                            // that we suddenly decided to replicate, choose the source for that
                            metadata[ReplicationConstants.RavenReplicationSource] = RavenJToken.FromObject(src);
                        }
                        lastEtag = metadata.Value <string>("@etag");
                        var id   = metadata.Value <string>("@id");
                        document.Remove("@metadata");
                        ReplicateDocument(actions, id, metadata, document, src);
                    }

                    var replicationDocKey   = ReplicationConstants.RavenReplicationSourcesBasePath + "/" + src;
                    var replicationDocument = Database.Get(replicationDocKey, null);
                    var lastAttachmentId    = Guid.Empty;
                    if (replicationDocument != null)
                    {
                        lastAttachmentId =
                            replicationDocument.DataAsJson.JsonDeserialization <SourceReplicationInformation>().
                            LastAttachmentEtag;
                    }
                    Database.Put(replicationDocKey, null,
                                 RavenJObject.FromObject(new SourceReplicationInformation
                    {
                        LastDocumentEtag   = new Guid(lastEtag),
                        LastAttachmentEtag = lastAttachmentId,
                        ServerInstanceId   = Database.TransactionalStorage.Id
                    }),
                                 new RavenJObject(), null);
                });
            }
        }
Exemple #27
0
        public virtual HttpResponseMessage GetMessageWithObject(object item, HttpStatusCode code = HttpStatusCode.OK, Etag etag = null)
        {
            var token = item as RavenJToken;

            if (token == null && item != null)
            {
                token = RavenJToken.FromObject(item);
            }

            bool metadataOnly;

            if (bool.TryParse(GetQueryStringValue("metadata-only"), out metadataOnly) && metadataOnly)
            {
                token = Extensions.HttpExtensions.MinimizeToken(token);
            }

            var msg = new HttpResponseMessage(code)
            {
                Content = JsonContent(token),
            };

            WriteETag(etag, msg);

            return(msg);
        }
        protected override CreatedConflict CreateConflict(string id, string newDocumentConflictId, string existingDocumentConflictId, Attachment existingItem, RavenJObject existingMetadata)
        {
            existingItem.Metadata.Add(Constants.RavenReplicationConflict, RavenJToken.FromObject(true));
            Actions.Attachments.AddAttachment(existingDocumentConflictId, null, existingItem.Data(), existingItem.Metadata);
            Actions.Lists.Remove(Constants.RavenReplicationDocsTombstones, id);
            var conflictsArray     = new RavenJArray(existingDocumentConflictId, newDocumentConflictId);
            var conflictAttachment = new RavenJObject
            {
                { "Conflicts", conflictsArray }
            };
            var memoryStream = new MemoryStream();

            conflictAttachment.WriteTo(memoryStream);
            memoryStream.Position = 0;
            var etag    = existingMetadata.Value <bool>(Constants.RavenDeleteMarker) ? null : existingItem.Etag;
            var newEtag = Actions.Attachments.AddAttachment(id, etag,
                                                            memoryStream,
                                                            new RavenJObject
            {
                { Constants.RavenReplicationConflict, true },
                { "@Http-Status-Code", 409 },
                { "@Http-Status-Description", "Conflict" }
            });

            return(new CreatedConflict()
            {
                Etag = newEtag,
                ConflictedIds = conflictsArray.Select(x => x.Value <string>()).ToArray()
            });
        }
Exemple #29
0
        internal static string ReduceKeyToString(object reduceValue)
        {
            var reduceValueAsString = reduceValue as string;

            if (reduceValueAsString != null)
            {
                return(reduceValueAsString);
            }

            if (reduceValue is DateTime)
            {
                return(((DateTime)reduceValue).GetDefaultRavenFormat());
            }
            if (reduceValue is DateTimeOffset)
            {
                return(((DateTimeOffset)reduceValue).ToString(Default.DateTimeFormatsToWrite, CultureInfo.InvariantCulture));
            }
            if (reduceValue is ValueType)
            {
                return(reduceValue.ToString());
            }

            var dynamicJsonObject = reduceValue as IDynamicJsonObject;

            if (dynamicJsonObject != null)
            {
                return(dynamicJsonObject.Inner.ToString(Formatting.None));
            }

            return(RavenJToken.FromObject(reduceValue).ToString(Formatting.None));
        }
        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));
            }
        }