当前位置: 首页>>代码示例>>C#>>正文


C# RavenJObject.ToString方法代码示例

本文整理汇总了C#中RavenJObject.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# RavenJObject.ToString方法的具体用法?C# RavenJObject.ToString怎么用?C# RavenJObject.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在RavenJObject的用法示例。


在下文中一共展示了RavenJObject.ToString方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddAttachment

		public Etag AddAttachment(string key, Etag etag, Stream data, RavenJObject headers)
		{
			Api.JetSetCurrentIndex(session, Files, "by_name");
			Api.MakeKey(session, Files, key, Encoding.Unicode, MakeKeyGrbit.NewKey);
			var isUpdate = Api.TrySeek(session, Files, SeekGrbit.SeekEQ);
			if (isUpdate)
			{
				var existingEtag = Etag.Parse(Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]));
				if (existingEtag != etag && etag != null)
				{
					throw new ConcurrencyException("PUT attempted on attachment '" + key +
						"' using a non current etag")
					{
						ActualETag = existingEtag,
						ExpectedETag = etag
					};
				}
			}
			else
			{
				if (data == null)
					throw new InvalidOperationException("When adding new attachment, the attachment data must be specified");

				if (Api.TryMoveFirst(session, Details))
					Api.EscrowUpdate(session, Details, tableColumnsCache.DetailsColumns["attachment_count"], 1);
			}

			Etag newETag = uuidGenerator.CreateSequentialUuid(UuidType.Attachments);
			using (var update = new Update(session, Files, isUpdate ? JET_prep.Replace : JET_prep.Insert))
			{
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["name"], key, Encoding.Unicode);
				if (data != null)
				{
					long written;
					using (var columnStream = new ColumnStream(session, Files, tableColumnsCache.FilesColumns["data"]))
					{
						if (isUpdate)
							columnStream.SetLength(0);
						using (var stream = new BufferedStream(columnStream))
						{
							data.CopyTo(stream);
							written = stream.Position;
							stream.Flush();
						}
					}
					if (written == 0) // empty attachment
					{
						Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["data"], new byte[0]);
					}
				}

				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["etag"], newETag.TransformToValueForEsentSorting());
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["metadata"], headers.ToString(Formatting.None), Encoding.Unicode);

				update.Save();
			}
			logger.Debug("Adding attachment {0}", key);

			return newETag;
		}
开发者ID:925coder,项目名称:ravendb,代码行数:60,代码来源:DocumentStorageActions.cs

示例2: TryResolveConflict

		public bool TryResolveConflict(string id, RavenJObject metadata, byte[] data, Attachment existingAttachment,
										Func<string, Attachment> getAttachment, out RavenJObject metadataToSave,
										out byte[] dataToSave)
		{
			var success = TryResolve(id, metadata, data, existingAttachment, getAttachment, out metadataToSave, out dataToSave);
			if (success == false)
				return false;

			var metaToSave = metadataToSave;
			log.Debug(() =>
			{
				var builder = new StringBuilder();
				builder.AppendLine(string.Format("Conflict on attachment with key '{0}' resolved by '{1}'.", id, GetType().Name));
				builder.AppendLine(string.Format("Existing metadata:"));
				if (existingAttachment != null && existingAttachment.Metadata != null)
					builder.AppendLine(existingAttachment.Metadata.ToString());
				builder.AppendLine(string.Format("Incoming metadata:"));
				if (metadata != null)
					builder.AppendLine(metadata.ToString());
				builder.AppendLine(string.Format("Output metadata:"));
				if (metaToSave != null)
					builder.AppendLine(metaToSave.ToString());

				return builder.ToString();
			});

			return true;
		}
开发者ID:GorelH,项目名称:ravendb,代码行数:28,代码来源:AbstractAttachmentReplicationConflictResolver.cs

示例3: Basic

		public void Basic()
		{
			var ravenJObject = new RavenJObject
			{
				{"Val", 3.3f}
			};
			var s = ravenJObject.ToString(Formatting.None);
			Assert.Equal("{\"Val\":3.3}", s);
		}
开发者ID:WimVergouwe,项目名称:ravendb,代码行数:9,代码来源:Floats.cs

示例4: WhenCloningWillRetainAllValues

		public void WhenCloningWillRetainAllValues()
		{
			var newBlog = new Blog()
			{
				Tags = new[]{
			          new BlogTag() { Name = "SuperCallaFragalisticExpealadocious" }
			     }
			};

			var expected = RavenJObject.FromObject(newBlog);
			var actual = new RavenJObject(expected);

			Assert.Equal(expected.ToString(Formatting.None), actual.ToString(Formatting.None));
		}
开发者ID:925coder,项目名称:ravendb,代码行数:14,代码来源:CloningTests.cs

示例5: AddAttachment

		public Guid AddAttachment(string key, Guid? etag, Stream data, RavenJObject headers)
		{
			Api.JetSetCurrentIndex(session, Files, "by_name");
			Api.MakeKey(session, Files, key, Encoding.Unicode, MakeKeyGrbit.NewKey);
			var isUpdate = Api.TrySeek(session, Files, SeekGrbit.SeekEQ);
			if (isUpdate)
			{
				var existingEtag = Api.RetrieveColumn(session, Files, tableColumnsCache.FilesColumns["etag"]).TransfromToGuidWithProperSorting();
				if (existingEtag != etag && etag != null)
				{
					throw new ConcurrencyException("PUT attempted on attachment '" + key +
						"' using a non current etag")
					{
						ActualETag = existingEtag,
						ExpectedETag = etag.Value
					};
				}
			}
			else
			{
				if (Api.TryMoveFirst(session, Details))
					Api.EscrowUpdate(session, Details, tableColumnsCache.DetailsColumns["attachment_count"], 1);
			}

			Guid newETag = uuidGenerator.CreateSequentialUuid();
			using (var update = new Update(session, Files, isUpdate ? JET_prep.Replace : JET_prep.Insert))
			{
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["name"], key, Encoding.Unicode);
				using (var stream = new BufferedStream(new ColumnStream(session, Files, tableColumnsCache.FilesColumns["data"])))
				{
					data.CopyTo(stream);
					stream.Flush();
				}
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["etag"], newETag.TransformToValueForEsentSorting());
				Api.SetColumn(session, Files, tableColumnsCache.FilesColumns["metadata"], headers.ToString(Formatting.None), Encoding.Unicode);

				update.Save();
			}
			logger.Debug("Adding attachment {0}", key);

		    return newETag;
		}
开发者ID:Korn1699,项目名称:ravendb,代码行数:42,代码来源:DocumentStorageActions.cs

示例6: TryResolveConflict

        public bool TryResolveConflict(string id, RavenJObject metadata, RavenJObject document, JsonDocument existingDoc,
                                        Func<string, JsonDocument> getDocument, out RavenJObject metadataToSave,
                                        out RavenJObject documentToSave)
        {
            var success = TryResolve(id, metadata, document, existingDoc, getDocument, out metadataToSave, out documentToSave);
            if (success == false)
                return false;

            var docToSave = documentToSave;
            var metaToSave = metadataToSave;
            log.Debug(() =>
            {
                var builder = new StringBuilder();
                builder.AppendLine(string.Format("Conflict on document with key '{0}' resolved by '{1}'.", id, GetType().Name));
                builder.AppendLine(string.Format("Existing document:"));
                if (existingDoc != null && existingDoc.DataAsJson != null)
                    builder.AppendLine(existingDoc.DataAsJson.ToString());
                builder.AppendLine(string.Format("Existing metadata:"));
                if (existingDoc != null && existingDoc.Metadata != null)
                    builder.AppendLine(existingDoc.Metadata.ToString());
                builder.AppendLine(string.Format("Incoming document:"));
                if (document != null)
                    builder.AppendLine(document.ToString());
                builder.AppendLine(string.Format("Incoming metadata:"));
                if (metadata != null)
                    builder.AppendLine(metadata.ToString());
                builder.AppendLine(string.Format("Output document:"));
                if (docToSave != null)
                    builder.AppendLine(docToSave.ToString());
                builder.AppendLine(string.Format("Output metadata:"));
                if (metaToSave != null)
                    builder.AppendLine(metaToSave.ToString());

                return builder.ToString();
            });

            return true;
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:38,代码来源:AbstractDocumentReplicationConflictResolver.cs

示例7: PutAsync

		/// <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();
		}
开发者ID:ryanheath,项目名称:ravendb,代码行数:46,代码来源:AsyncServerClient.cs

示例8: UpdateMetadata

		private void UpdateMetadata(RavenJObject metadataAsJson)
		{
			metadata = metadataAsJson.ToDictionary(x => x.Key, x =>
			{
				if (x.Value.Type == JTokenType.String)
					return x.Value.Value<string>();
				return x.Value.ToString(Formatting.None);
			});
			OnPropertyChanged(() => Metadata);
			JsonMetadata = metadataAsJson.ToString(Formatting.Indented);
		}
开发者ID:samueldjack,项目名称:ravendb,代码行数:11,代码来源:EditableDocumentModel.cs

示例9: PrepareRawJsonString

		private static string PrepareRawJsonString(RavenJObject json)
		{
			return json.ToString(Formatting.Indented);
		}
开发者ID:kblooie,项目名称:ravendb,代码行数:4,代码来源:EditDocumentViewModel.cs

示例10: PutAsync

		/// <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();
		}
开发者ID:nzdunic,项目名称:ravendb,代码行数:43,代码来源:AsyncServerClient.cs

示例11: InsertItems

		protected void InsertItems(string tableName, string pkName, IEnumerable<ItemToReplicate> dataForTable)
		{
		    tableName = tableName.ToLowerInvariant(); // type names have to be lowercase
            foreach (var itemToReplicate in dataForTable)
            {
                var o = new RavenJObject();

                if (database != null)
                    database.WorkContext.CancellationToken.ThrowIfCancellationRequested();

                foreach (var column in itemToReplicate.Columns.Where(column => column.Key != pkName))
                {
                    o[column.Key] = column.Value;
                }

                if ("_id".Equals(pkName))
                {
                    bulkCommands.Add("{\"index\":{\"_index\":\"" + targetIndexName + "\",\"_type\":\"" + tableName + "\",\"_id\":\"" + itemToReplicate.DocumentId + "\"}}");
                }
                else
                {
                    o[pkName] = itemToReplicate.DocumentId;
                    bulkCommands.Add("{\"index\":{\"_index\":\"" + targetIndexName + "\",\"_type\":\"" + tableName + "\"}}");
                }

                // Setup timestamps, converting from a Javascript notation to an ES/Kibana notation
                if (o.ContainsKey("$timestamp"))
                {
                    o["@timestamp"] = o["$timestamp"];
                    o.Remove("$timestamp");
                }
                else
                {
                    o["@timestamp"] = DateTime.UtcNow;
                }

                bulkCommands.Add(o.ToString(Formatting.None));
            }
		}
开发者ID:synhershko,项目名称:RavenDB.ElasticsearchReplication,代码行数:39,代码来源:ElasticsearchDestinationWriter.cs

示例12: BlogAdminModule


//.........这里部分代码省略.........

                var input = this.Bind<BlogPost>();

                bool validated = true;
                if (!validated)
                {
                    //ModelState.AddModelError("Id", "");
                    return View["Edit", input];
                }

                blogPost.Title = input.Title;
                blogPost.Content = input.Content;

                string tags = Request.Form.TagsAsString;
                blogPost.Tags = new HashSet<string>();
                if (!String.IsNullOrWhiteSpace(tags))
                {
                    foreach (var tag in tags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        blogPost.Tags.Add(tag.Trim());
                    }
                }
                blogPost.LastEditedAt = DateTimeOffset.UtcNow;

                if ("Publish".Equals(Request.Form["SubmitAction"]))
                {
                    blogPost.CurrentState = BlogPost.State.Public;
                    if (blogPost.PublishedAt == DateTimeOffset.MinValue)
                    {
                        blogPost.PublishedAt = DateTimeOffset.UtcNow;
                    }
                }

                // Update the cached rendered page
                blogPost.CachedRenderedContent = blogPost.CompiledContent(true).ToHtmlString();

                session.SaveChanges();

                return Response.AsRedirect(input.ToUrl(AreaRoutePrefix.TrimEnd('/')));
            };

            Get[@"/stats/{days?7}/{type?all}"] = o =>
                                                     {
                                                         var ret = new RavenJObject();

                                                         if (blogConfig != null)
                                                         {
                                                             var url = string.Format(@"http://stats.wordpress.com/csv.php?api_key={0}&blog_id={1}&format=json",
                                                                 blogConfig.WordPressAPIKey, blogConfig.WordPressBlogId);
                                                             using (var webClient = new System.Net.WebClient())
                                                             {
                                                                 // TODO async, not UTF8 compatible
                                                                 switch ((string)o.type)
                                                                 {
                                                                     case "searchterms":
                                                                         ret.Add("searchterms", RavenJToken.Parse(webClient.DownloadString(url + "&table=searchterms")));
                                                                         break;
                                                                     case "clicks":
                                                                         ret.Add("clicks", RavenJToken.Parse(webClient.DownloadString(url + "&table=clicks")));
                                                                         break;
                                                                     case "referrers":
                                                                         ret.Add("referrers", RavenJToken.Parse(webClient.DownloadString(url + "&table=referrers_grouped")));
                                                                         break;
                                                                     case "views":
                                                                     default:
                                                                         ret.Add("histogram", RavenJToken.Parse(webClient.DownloadString(url)));
                                                                         break;
                                                                 }

                                                                 if ("all".Equals((string) o.type))
                                                                 {
                                                                     ret.Add("searchterms", RavenJToken.Parse(webClient.DownloadString(url + "&table=searchterms&days=2")));
                                                                     ret.Add("clicks", RavenJToken.Parse(webClient.DownloadString(url + "&table=clicks&days=2")));
                                                                     ret.Add("referrers", RavenJToken.Parse(webClient.DownloadString(url + "&table=referrers_grouped&days=2")));
                                                                 }
                                                             }
                                                         }

                                                         return Response.AsText(ret.ToString(), "text/json");
                                                     };

            Get[@"/config"] = o =>
                                  {
                                      using (session.Advanced.DocumentStore.DisableAggressiveCaching())
                                      {
                                          var config = session.Load<BlogConfig>("NSemble/Configs/" + AreaConfigs.AreaName);
                                          return View["Config", config];
                                      }
                                  };

            Get[@"/config/widgets"] = o =>
                                          {
                                              using (session.Advanced.DocumentStore.DisableAggressiveCaching())
                                              {
                                                  var config =
                                                      session.Load<BlogConfig>("NSemble/Configs/" + AreaConfigs.AreaName);
                                                  return View["ConfigWidgets", config.Widgets.ToArray()];
                                              }
                                          };
        }
开发者ID:synhershko,项目名称:NSemble,代码行数:101,代码来源:BlogAdminModule.cs

示例13: Put

        private BatchResult Put(PutCommandData command)
        {
            if (command.Etag.HasValue && database.ContainsKey(new Guid(command.Key))) {
                var existing = database[new Guid(command.Key)];
                if (existing.Item2 != command.Etag.Value) {
                    throw new InvalidOperationException("Optimistic Concurrency Exception");
                }
            }

            var ret = new RavenJObject
                {
                    {"Key", command.Key},
                    {"Document", command.Document},
                    {"Metadata", command.Metadata},
                };

            var newEtag = GuidComb.NewGuid();
            var tuple = new Tuple<string, Guid, DateTime>(ret.ToString(Formatting.None), newEtag, DateTime.UtcNow);
            database[new Guid(command.Key)] = tuple;

            return new BatchResult() {
                Key = command.Key,
                Etag = newEtag,
                Method = command.Method,
                Metadata = command.Metadata,
            };
        }
开发者ID:clearwavebuild,项目名称:SqlDocDB,代码行数:27,代码来源:MemoryDatabase.cs


注:本文中的RavenJObject.ToString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。