The set of conventions used by the DocumentStore which allow the users to customize the way the Raven client API behaves
Ejemplo n.º 1
0
 public ThinClient(string serverUrl, string databaseName)
 {
     baseUrl = serverUrl;
     databaseUrl = serverUrl + "/databases/" + databaseName;
     httpClient = new HttpClient();
     convention = new DocumentConvention();
 }
Ejemplo n.º 2
0
        public static void SetupConventions(DocumentConvention conventions)
        {
            conventions.TransformTypeTagNameToDocumentKeyPrefix = typeTagName => typeTagName;

            conventions.RegisterIdConvention<SiddurSnippet>((commands, snippet) => string.Format("{0}/{1}", conventions.GetTypeTagName(snippet.GetType()), snippet.Slug));
            conventions.RegisterIdConvention<SiddurPrayer>((commands, prayer) => string.Format("{0}/{1}", conventions.GetTypeTagName(prayer.GetType()), prayer.Slug));
        }
Ejemplo n.º 3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="convention">The convention.</param>
		/// <param name="credentials">The credentials.</param>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory)
		{
			this.url = url;
			this.jsonRequestFactory = jsonRequestFactory;
			this.convention = convention;
			this.credentials = credentials;
		}
 public EmbeddableDocumentStore()
 {
     Conventions = new DocumentConvention();
     Listeners = new DocumentSessionListeners();
     Configuration = new RavenConfiguration();
     EnlistInDistributedTransactions = true;
 }
Ejemplo n.º 5
0
		public void can_use_RavenDB_in_a_remote_process_for_batch_operations()
		{
			var documentConvention = new DocumentConvention();

			using (var driver = new RavenDBDriver("HelloShard", documentConvention))
			{
				driver.Start();

				using (var store = new DocumentStore()
				{
					Url = driver.Url,
					Conventions = documentConvention
				})
				{
					store.Initialize();

					using (var session = store.OpenSession())
					{
						session.Advanced.DatabaseCommands.Batch(new[] {GetPutCommand()});
						session.SaveChanges();
					}
				}

				using (var store = driver.GetDocumentStore())
				{
					should_find_expected_value_in(store);
				}
			}
		}
Ejemplo n.º 6
0
		internal HttpJsonRequest(
			CreateHttpJsonRequestParams requestParams,
			HttpJsonRequestFactory factory)
		{
			Url = requestParams.Url;
			this.factory = factory;
			owner = requestParams.Owner;
			conventions = requestParams.Convention;
			Method = requestParams.Method;
			webRequest = (HttpWebRequest)WebRequest.Create(requestParams.Url);
			webRequest.UseDefaultCredentials = true;
			webRequest.Credentials = requestParams.Credentials;
			webRequest.Method = requestParams.Method;
			if (factory.DisableRequestCompression == false && requestParams.DisableRequestCompression == false)
			{
				if (requestParams.Method == "POST" || requestParams.Method == "PUT" ||
					requestParams.Method == "PATCH" || requestParams.Method == "EVAL")
					webRequest.Headers["Content-Encoding"] = "gzip";

				webRequest.Headers["Accept-Encoding"] = "gzip";
			}
			webRequest.ContentType = "application/json; charset=utf-8";
			webRequest.Headers.Add("Raven-Client-Version", ClientVersion);
			WriteMetadata(requestParams.Metadata);
			requestParams.UpdateHeaders(webRequest);
		}
        public DatabaseModule()
        {
            var documentConvention =
                new DocumentConvention
                {
                    FindTypeTagName =
                        type =>
                        {
                            if (typeof(Favorite).IsAssignableFrom(type))
                            {
                                return "favorites";
                            }

                            return DocumentConvention.DefaultTypeTagName(type);
                        },
                    FindClrTypeName =
                        type => type.AssemblyQualifiedName,
                    CustomizeJsonSerializer =
                        serializer =>
                        {
                            serializer.Binder = new CustomSerializationBinder();
                        }
                };

            _documentStore = new EmbeddableDocumentStore();
            _documentStore.Conventions = documentConvention;
            _documentStore.DataDirectory = Path.Combine(AppConstants.AppDataFolder, "Database");

            #if DEBUG
            _documentStore.UseEmbeddedHttpServer = true;
            #endif
        }
Ejemplo n.º 8
0
		/// <summary>
		/// Initializes a new instance of the <see cref="DocumentStore"/> class.
		/// </summary>
		public DocumentStore()
		{
            ResourceManagerId = new Guid("E749BAA6-6F76-4EEF-A069-40A4378954F8");

			SharedOperationsHeaders = new NameValueCollection();
			Conventions = new DocumentConvention();
		}
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="conventions">The conventions.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, object entity)
		{
         var typeTagName = conventions.GetDynamicTagName(entity);
			if (string.IsNullOrEmpty(typeTagName)) //ignore empty tags
				return null;
			var tag = conventions.TransformTypeTagNameToDocumentKeyPrefix(typeTagName);
			HiLoKeyGenerator value;
			if (keyGeneratorsByTag.TryGetValue(tag, out value))
				return value.GenerateDocumentKey(databaseCommands, conventions, entity);

			lock(generatorLock)
			{
				if (keyGeneratorsByTag.TryGetValue(tag, out value))
					return value.GenerateDocumentKey(databaseCommands, conventions, entity);

				value = new HiLoKeyGenerator(tag, capacity);
				// doing it this way for thread safety
				keyGeneratorsByTag = new Dictionary<string, HiLoKeyGenerator>(keyGeneratorsByTag)
				{
					{tag, value}
				};
			}

			return value.GenerateDocumentKey(databaseCommands, conventions, entity);
		}
		public Task<string> GenerateDocumentKeyAsync(IAsyncDatabaseCommands databaseCommands, DocumentConvention conventions, object entity)
		{
			var shardId = shardedDocumentStore.ShardStrategy.ShardResolutionStrategy.MetadataShardIdFor(entity);
			if (shardId == null)
				throw new InvalidOperationException(string.Format(
					"ShardResolutionStrategy.MetadataShardIdFor cannot return null. You must specify where to store the metadata documents for the entity type '{0}'.", entity.GetType().FullName));

			AsyncMultiTypeHiLoKeyGenerator value;
			if (generatorsByShard.TryGetValue(shardId, out value))
				return value.GenerateDocumentKeyAsync(databaseCommands, conventions, entity);

			lock (this)
			{
				if (generatorsByShard.TryGetValue(shardId, out value) == false)
				{
					value = new AsyncMultiTypeHiLoKeyGenerator(capacity);
					generatorsByShard = new Dictionary<string, AsyncMultiTypeHiLoKeyGenerator>(generatorsByShard)
					                    	{
					                    		{shardId, value}
					                    	};
				}
			}

			return value.GenerateDocumentKeyAsync(databaseCommands, conventions, entity);
		}
Ejemplo n.º 11
0
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="conventions">The conventions.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(DocumentConvention conventions, object entity)
		{
		    var typeTagName = conventions.GetTypeTagName(entity.GetType());
			if (string.IsNullOrEmpty(typeTagName)) //ignore empty tags
				return null; 
		    var tag = typeTagName.ToLowerInvariant();
			HiLoKeyGenerator value;
			if (keyGeneratorsByTag.TryGetValue(tag, out value))
				return value.GenerateDocumentKey(conventions, entity);

			lock(generatorLock)
			{
				if (keyGeneratorsByTag.TryGetValue(tag, out value))
					return value.GenerateDocumentKey(conventions, entity);

				value = new HiLoKeyGenerator(documentStore, tag, capacity);
				// doing it this way for thread safety
				keyGeneratorsByTag = new Dictionary<string, HiLoKeyGenerator>(keyGeneratorsByTag)
				{
					{tag, value}
				};
			}

			return value.GenerateDocumentKey(conventions, entity);
		}
Ejemplo n.º 12
0
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="convention">The convention.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(DocumentConvention convention, object entity)
		{
			return string.Format("{0}{1}{2}",
								 tag,
								 convention.IdentityPartsSeparator,
								 NextId());
		}
Ejemplo n.º 13
0
        public void Widgets_in_database_are_produced_by_factory()
        {
            var conventions = new DocumentConvention
            {
                FindTypeTagName = type =>
                                  {
                                      if (typeof(Widget).IsAssignableFrom(type))
                                      {
                                          return Widget.IdPrefix.TrimSuffix("/");
                                      }
                                      return DocumentConvention.DefaultTypeTagName(type);
                                  }
            };

            var testableStore = new TestableStore(conventions);

            var fooWidget = new CustomWidget { Markup = "foo" };
            var barWidget = new CustomWidget { Markup = "bar" };

            using (var session = testableStore.OpenSession())
            {
                session.Store(fooWidget);
                session.Store(barWidget);
                session.SaveChanges();

                var widgetFactory = new WidgetFactory(session);
                var widgets = widgetFactory.GetWidgets();

                Assert.Contains(fooWidget, widgets);
                Assert.Contains(barWidget, widgets);
            }
        }
Ejemplo n.º 14
0
		public void can_use_RavenDB_in_a_remote_process()
		{
			var documentConvention = new DocumentConvention();

			using (var driver = new RavenDBDriver("HelloShard", documentConvention))
			{
				driver.Start();

				using (var store = new DocumentStore()
				{
					Url = driver.Url,
					Conventions = documentConvention
				})
				{
					store.Initialize();

					using (var session = store.OpenSession())
					{
						session.Store(new Tuple<string, string>("hello", "world"));
						session.SaveChanges();
					}
				}

				using (var store = driver.GetDocumentStore())
				{
					should_find_expected_value_in(store);
				}
			}
		}
Ejemplo n.º 15
0
        public void query_for_object_with_byte_array_with_default_TypeNameHandling()
        {
            using (var store = NewRemoteDocumentStore())
            {

                var json = GetResourceText("DocumentWithBytes.txt");
                var jsonSerializer = new DocumentConvention().CreateSerializer();
                var item = jsonSerializer.Deserialize<DesignResources>(new JsonTextReader(new StringReader(json)));

                using (var session = store.OpenSession())
                {
                    item.Id = "resources/123";
                    item.DesignId = "designs/123";
                    session.Store(item);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    session
                        .Query<DesignResources>()
                        .Customize(x => x.WaitForNonStaleResultsAsOfNow())
                        .Where(x => x.DesignId == "designs/123")
                        .ToList();
                }
            }
        }
Ejemplo n.º 16
0
		/// <summary>
		/// Creates the indexes found in the specified catalog
		/// </summary>
		/// <param name="catalogToGetnIndexingTasksFrom">The catalog to get indexing tasks from.</param>
		public static void CreateIndexes(ExportProvider catalogToGetnIndexingTasksFrom, IDatabaseCommands databaseCommands, DocumentConvention conventions)
		{
			var tasks = catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractIndexCreationTask>();
			foreach (var task in tasks)
			{
				task.Execute(databaseCommands, conventions);
			}
		}
Ejemplo n.º 17
0
		/// <summary>
		/// Creates the HTTP json request.
		/// </summary>
		/// <param name="self">The self.</param>
		/// <param name="url">The URL.</param>
		/// <param name="method">The method.</param>
		/// <param name="metadata">The metadata.</param>
		/// <param name="credentials">The credentials.</param>
		/// <param name="convention">The document conventions governing this request</param>
		/// <returns></returns>
		public HttpJsonRequest CreateHttpJsonRequest(object self, string url, string method, JObject metadata,
													 ICredentials credentials, DocumentConvention convention)
		{
			var request = new HttpJsonRequest(url, method, metadata, credentials, this);
			ConfigureCaching(url, method, convention, request);
			ConfigureRequest(self, new WebRequestEventArgs { Request = request.WebRequest });
			return request;
		}
Ejemplo n.º 18
0
		public CreateHttpJsonRequestParams(object self, string url, string method, ICredentials credentials, DocumentConvention convention)
		{
			Self = self;
			Url = url;
			Method = method;
			Credentials = credentials;
			Convention = convention;
		}
Ejemplo n.º 19
0
		protected string GetDocumentKeyFromId(DocumentConvention convention, long nextId)
		{
			return string.Format("{0}{1}{2}{3}",
								 tag,
								 convention.IdentityPartsSeparator,
								 lastServerPrefix,
								 nextId);
		}
Ejemplo n.º 20
0
		public void WillNotSerializeFields()
		{
			var serializer = new DocumentConvention().CreateSerializer();
			var stringWriter = new StringWriter();
			serializer.Serialize(stringWriter, new Company("Hibernating Rhinos", "Middle East"));
			var s = stringWriter.GetStringBuilder().ToString();
			Assert.DoesNotContain("k__BackingField", s);
		}
Ejemplo n.º 21
0
		/// <summary>
		/// Creates the indexes found in the specified catalog
		/// </summary>
		public static Task CreateIndexesAsync(ExportProvider catalogToGetnIndexingTasksFrom, IAsyncDatabaseCommands asyncDatabaseCommands, DocumentConvention conventions)
		{
			var tasks = catalogToGetnIndexingTasksFrom.GetExportedValues<AbstractIndexCreationTask>();

			Task[] array = tasks.Select(task => task.ExecuteAsync(asyncDatabaseCommands, conventions)).ToArray();
			var indexesAsync = new Task(() => Task.WaitAll(array));
			indexesAsync.Start();
			return indexesAsync;
		}
Ejemplo n.º 22
0
 private DocumentConvention SetConventions(DocumentConvention convention)
 {
     convention.JsonContractResolver = new PropertiesOnlyContractResolver();
     convention.FindTypeTagName = x => "Snapshots";
     convention.CustomizeJsonSerializer = serializer => {
         serializer.Converters.Add(new VersionConverter());
     };
     return convention;
 }
Ejemplo n.º 23
0
		/// <summary>
		/// Generates the document key.
		/// </summary>
		/// <param name="convention">The convention.</param>
		/// <param name="entity">The entity.</param>
		/// <returns></returns>
		public string GenerateDocumentKey(DocumentConvention convention, object entity)
		{
			var nextId = NextId();
			return string.Format("{0}{1}{2}{3}",
								 tag,
								 convention.IdentityPartsSeparator,
								 lastServerPrefix,
								 nextId);
		}
Ejemplo n.º 24
0
		public void CanSerializeToJsonCorrectly()
		{
			var serializer = new DocumentConvention().CreateSerializer();
			var stringWriter = new StringWriter();
			serializer.Serialize(stringWriter, new Company("Hibernating Rhinos", "Middle East"));
			var deserializeObject = serializer.Deserialize<Company>(new JsonTextReader(new StringReader(stringWriter.GetStringBuilder().ToString())));
			Assert.Equal("Hibernating Rhinos", deserializeObject.Name);
			Assert.Equal("Middle East", deserializeObject.Region);
		}
Ejemplo n.º 25
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="convention">The convention.</param>
		/// <param name="credentials">The credentials.</param>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid? sessionId)
		{
			profilingInformation = ProfilingInformation.CreateProfilingInformation(sessionId);
			this.url = url;
			this.jsonRequestFactory = jsonRequestFactory;
			this.sessionId = sessionId;
			this.convention = convention;
			this.credentials = credentials;
		}
        public void Can_read_date_time_offset_from_lucene_query()
        {
            var jsonSerializer = new DocumentConvention().CreateSerializer();

            using (var reader = new JsonTextReader(new StringReader(@"{""Item"": ""20090402193554412""}")))
            {
                var deserialize = jsonSerializer.Deserialize<Test>(reader);
                Assert.Equal(2009, deserialize.Item.Year);
            }
        }
Ejemplo n.º 27
0
		public CreateHttpJsonRequestParams(IHoldProfilingInformation self, string url, string method, RavenJObject metadata, ICredentials credentials, DocumentConvention convention)
		{
			Owner = self;
			Url = url;
			Method = method;
			Metadata = metadata;
			Credentials = credentials;
			Convention = convention;
			operationsHeadersColletion = new NameValueCollection();
		}
Ejemplo n.º 28
0
        public TestableStore(DocumentConvention conventions = null)
        {
            this.RunInMemory = true;

            if (conventions != null)
            {
                this.Conventions = conventions;
            }

            this.Initialize();
        }
		public void ListOnDynamicJsonObjectFromJsonWillFailToBeAJsonList()
		{
			var conventions = new DocumentConvention();

			var jObject = RavenJObject.FromObject(page, conventions.CreateSerializer());

			dynamic dynamicObject = new DynamicJsonObject(jObject);
			Assert.NotNull(dynamicObject.CoAuthors as IEnumerable);
			Assert.NotNull(dynamicObject.CoAuthors.Length);
			Assert.Equal(2, dynamicObject.CoAuthors.Length);
		}
Ejemplo n.º 30
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncServerClient"/> class.
		/// </summary>
		public AsyncServerClient(string url, DocumentConvention convention, ICredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid? sessionId)
		{
			profilingInformation = ProfilingInformation.CreateProfilingInformation(sessionId);
			this.url = url;
			if (this.url.EndsWith("/"))
				this.url = this.url.Substring(0, this.url.Length-1);
			this.jsonRequestFactory = jsonRequestFactory;
			this.sessionId = sessionId;
			this.convention = convention;
			this.credentials = credentials;
		}