• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Lite.BlobKey类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Couchbase.Lite.BlobKey的典型用法代码示例。如果您正苦于以下问题:C# BlobKey类的具体用法?C# BlobKey怎么用?C# BlobKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



BlobKey类属于Couchbase.Lite命名空间,在下文中一共展示了BlobKey类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: TestBasicOperation

		/// <exception cref="System.Exception"></exception>
		public virtual void TestBasicOperation()
		{
			BlobStore attachments = database.GetAttachments();
			InputStream attachmentStream = GetAsset("attachment.png");
			byte[] bytes = IOUtils.ToByteArray(attachmentStream);
			BlobStoreWriter blobStoreWriter = new BlobStoreWriter(attachments);
			blobStoreWriter.AppendData(bytes);
			blobStoreWriter.Finish();
			blobStoreWriter.Install();
			string sha1DigestKey = blobStoreWriter.SHA1DigestString();
			BlobKey keyFromSha1 = new BlobKey(sha1DigestKey);
			NUnit.Framework.Assert.IsTrue(attachments.GetSizeOfBlob(keyFromSha1) == bytes.Length
				);
		}
开发者ID:Redth,项目名称:couchbase-lite-net,代码行数:15,代码来源:BlobStoreWriterTest.cs


示例2: KeyForBlob

		public static BlobKey KeyForBlob(byte[] data)
		{
			MessageDigest md;
			try
			{
				md = MessageDigest.GetInstance("SHA-1");
			}
			catch (NoSuchAlgorithmException)
			{
				Log.E(Database.Tag, "Error, SHA-1 digest is unavailable.");
				return null;
			}
			byte[] sha1hash = new byte[40];
			md.Update(data, 0, data.Length);
			sha1hash = md.Digest();
			BlobKey result = new BlobKey(sha1hash);
			return result;
		}
开发者ID:Redth,项目名称:couchbase-lite-net,代码行数:18,代码来源:BlobStore.cs


示例3: TestBasicOperation

        public void TestBasicOperation()
        {
            var attachmentStream = (InputStream)GetAsset("attachment.png");
            var memoryStream = new MemoryStream();
            attachmentStream.Wrapped.CopyTo(memoryStream);
            var bytes = memoryStream.ToArray();

            var attachments = database.Attachments;
            var blobStoreWriter = new BlobStoreWriter(attachments);
            blobStoreWriter.AppendData(bytes);
            blobStoreWriter.Finish();
            blobStoreWriter.Install();

            var sha1DigestKey = blobStoreWriter.SHA1DigestString();
            Assert.IsTrue(sha1DigestKey.Contains("LmsoqJJ6LOn4YS60pYnvrKbBd64="));

            var keyFromSha1 = new BlobKey(sha1DigestKey);
            Assert.IsTrue(attachments.GetSizeOfBlob(keyFromSha1) == bytes.Length);
        }
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:19,代码来源:BlobStoreWriterTest.cs


示例4: GetAttachmentsFromRevision

        /// <summary>
        /// Given a revision, read its _attachments dictionary (if any), convert each attachment to a
        /// AttachmentInternal object, and return a dictionary mapping names-&gt;CBL_Attachments.
        /// </summary>
        /// <remarks>
        /// Given a revision, read its _attachments dictionary (if any), convert each attachment to a
        /// AttachmentInternal object, and return a dictionary mapping names-&gt;CBL_Attachments.
        /// </remarks>
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal IDictionary<String, AttachmentInternal> GetAttachmentsFromRevision(RevisionInternal rev)
        {
            var revAttachments = rev.GetPropertyForKey("_attachments").AsDictionary<string, object>();
            if (revAttachments == null || revAttachments.Count == 0 || rev.IsDeleted())
            {
                return new Dictionary<string, AttachmentInternal>();
            }

            var attachments = new Dictionary<string, AttachmentInternal>();
            foreach (var name in revAttachments.Keys)
            {
                var attachInfo = revAttachments.Get(name).AsDictionary<string, object>();
                var contentType = (string)attachInfo.Get("content_type");
                var attachment = new AttachmentInternal(name, contentType);
                var newContentBase64 = (string)attachInfo.Get("data");
                if (newContentBase64 != null)
                {
                    // If there's inline attachment data, decode and store it:
                    byte[] newContents;
                    try
                    {
                        newContents = StringUtils.ConvertFromUnpaddedBase64String (newContentBase64);
                    }
                    catch (IOException e)
                    {
                        throw new CouchbaseLiteException(e, StatusCode.BadEncoding);
                    }
                    attachment.Length = newContents.Length;
                    var outBlobKey = new BlobKey();
                    var storedBlob = Attachments.StoreBlob(newContents, outBlobKey);
                    attachment.BlobKey = outBlobKey;
                    if (!storedBlob)
                    {
                        throw new CouchbaseLiteException(StatusCode.AttachmentError);
                    }
                }
                else
                {
                    if (attachInfo.ContainsKey("follows") && ((bool)attachInfo.Get("follows")))
                    {
                        // "follows" means the uploader provided the attachment in a separate MIME part.
                        // This means it's already been registered in _pendingAttachmentsByDigest;
                        // I just need to look it up by its "digest" property and install it into the store:
                        InstallAttachment(attachment, attachInfo);
                    }
                    else
                    {
                        // This item is just a stub; validate and skip it
                        if (((bool)attachInfo.Get("stub")) == false)
                        {
                            throw new CouchbaseLiteException("Expected this attachment to be a stub", StatusCode.
                                                             BadAttachment);
                        }

                        var revPos = Convert.ToInt64(attachInfo.Get("revpos"));
                        if (revPos <= 0)
                        {
                            throw new CouchbaseLiteException("Invalid revpos: " + revPos, StatusCode.BadAttachment);
                        }

                        continue;
                    }
                }
                // Handle encoded attachment:
                string encodingStr = (string)attachInfo.Get("encoding");
                if (encodingStr != null && encodingStr.Length > 0)
                {
                    if (Runtime.EqualsIgnoreCase(encodingStr, "gzip"))
                    {
                        attachment.Encoding = AttachmentEncoding.GZIP;
                    }
                    else
                    {
                        throw new CouchbaseLiteException("Unnkown encoding: " + encodingStr, StatusCode.BadEncoding
                                                        );
                    }
                    attachment.EncodedLength = attachment.Length;
                    if (attachInfo.ContainsKey("length"))
                    {
                        attachment.Length = attachInfo.GetCast<long>("length");
                    }
                }
                if (attachInfo.ContainsKey("revpos"))
                {
                    var revpos = Convert.ToInt32(attachInfo.Get("revpos"));
                    attachment.RevPos = revpos;
                }
                attachments[name] = attachment;
            }
            return attachments;
        }
开发者ID:DotNetEra,项目名称:couchbase-lite-net,代码行数:100,代码来源:Database.cs


示例5: FileForAttachmentDict

 internal Uri FileForAttachmentDict(IDictionary<String, Object> attachmentDict)
 {
     var digest = (string)attachmentDict.Get("digest");
     if (digest == null)
     {
         return null;
     }
     string path = null;
     var pending = PendingAttachmentsByDigest.Get(digest);
     if (pending != null)
     {
         path = pending.FilePath;
     }
     else
     {
         // If it's an installed attachment, ask the blob-store for it:
         var key = new BlobKey(digest);
         path = Attachments.PathForKey(key);
     }
     Uri retval = null;
     try
     {
         retval = new FilePath(path).ToURI().ToURL();
     }
     catch (UriFormatException)
     {
     }
     //NOOP: retval will be null
     return retval;
 }
开发者ID:DotNetEra,项目名称:couchbase-lite-net,代码行数:30,代码来源:Database.cs


示例6: GetAttachmentsDictForSequenceWithContent

        /// <summary>Constructs an "_attachments" dictionary for a revision, to be inserted in its JSON body.</summary>
        internal IDictionary<String, Object> GetAttachmentsDictForSequenceWithContent(long sequence, DocumentContentOptions contentOptions)
        {
            Debug.Assert((sequence > 0));

            Cursor cursor = null;
            var args = new Object[] { sequence };

            try
            {
                cursor = StorageEngine.RawQuery("SELECT filename, key, type, length, revpos FROM attachments WHERE sequence=?", CommandBehavior.SequentialAccess, args);
                if (!cursor.MoveToNext())
                {
                    return null;
                }

                var result = new Dictionary<String, Object>();

                while (!cursor.IsAfterLast())
                {
                    var dataSuppressed = false;
                    var filename = cursor.GetString(0);
                    var keyData = cursor.GetBlob(1);
                    var contentType = cursor.GetString(2);
                    var length = cursor.GetInt(3);
                    var revpos = cursor.GetInt(4);

                    var key = new BlobKey(keyData);
                    var digestString = "sha1-" + Convert.ToBase64String(keyData);

                    var dataBase64 = (string) null;
                    if (contentOptions.HasFlag(DocumentContentOptions.IncludeAttachments))
                    {
                        if (contentOptions.HasFlag(DocumentContentOptions.BigAttachmentsFollow) && 
                            length >= Database.BigAttachmentLength)
                        {
                            dataSuppressed = true;
                        }
                        else
                        {
                            byte[] data = Attachments.BlobForKey(key);
                            if (data != null)
                            {
                                dataBase64 = Convert.ToBase64String(data);
                            }
                            else
                            {
                                // <-- very expensive
                                Log.W(Tag, "Error loading attachment");
                            }
                        }
                    }
                    var attachment = new Dictionary<string, object>();
                    if (!(dataBase64 != null || dataSuppressed))
                    {
                        attachment["stub"] = true;
                    }
                    if (dataBase64 != null)
                    {
                        attachment["data"] = dataBase64;
                    }
                    if (dataSuppressed) {
                        attachment.Put ("follows", true);
                    }
                    attachment["digest"] = digestString;

                    attachment["content_type"] = contentType;
                    attachment["length"] = length;
                    attachment["revpos"] = revpos;

                    result[filename] = attachment;

                    cursor.MoveToNext();
                }
                return result;
            }
            catch (SQLException e)
            {
                Log.E(Tag, "Error getting attachments for sequence", e);
                return null;
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }
        }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:89,代码来源:Database.cs


示例7: GarbageCollectAttachments

        /// <summary>Deletes obsolete attachments from the sqliteDb and blob store.</summary>
        private Status GarbageCollectAttachments()
        {
            // First delete attachment rows for already-cleared revisions:
            // OPT: Could start after last sequence# we GC'd up to
            try
            {
                StorageEngine.ExecSQL("DELETE FROM attachments WHERE sequence IN (SELECT sequence from revs WHERE json IS null)");
            }
            catch (SQLException e)
            {
                Log.E(Tag, "Error deleting attachments", e);
            }

            // Now collect all remaining attachment IDs and tell the store to delete all but these:
            Cursor cursor = null;
            try
            {
                cursor = StorageEngine.RawQuery("SELECT DISTINCT key FROM attachments", CommandBehavior.SequentialAccess);
                cursor.MoveToNext();

                var allKeys = new AList<BlobKey>();
                while (!cursor.IsAfterLast())
                {
                    var key = new BlobKey(cursor.GetBlob(0));
                    allKeys.AddItem(key);
                    cursor.MoveToNext();
                }

                var numDeleted = Attachments.DeleteBlobsExceptWithKeys(allKeys);
                if (numDeleted < 0)
                {
                    return new Status(StatusCode.InternalServerError);
                }

                Log.V(Tag, "Deleted " + numDeleted + " attachments");

                return new Status(StatusCode.Ok);
            }
            catch (SQLException e)
            {
                Log.E(Tag, "Error finding attachment keys in use", e);
                return new Status(StatusCode.InternalServerError);
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }
        }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:52,代码来源:Database.cs


示例8: AttachmentInternal

        public AttachmentInternal(string name, IDictionary<string, object> info) 
            : this(name, info.GetCast<string>("content_type"))
        {
            Length = info.GetCast<long>("length");
            EncodedLength = info.GetCast<long>("encoded_length");
            _digest = info.GetCast<string>("digest");
            if (_digest != null) {
                BlobKey = new BlobKey(_digest);
            }

            string encodingString = info.GetCast<string>("encoding");
            if (encodingString != null) {
                if (encodingString.Equals("gzip")) {
                    Encoding = AttachmentEncoding.GZIP;
                } else {
                    throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadEncoding, TAG,
                        "Invalid encoding type ({0}) in ctor", encodingString);
                }
            }

            var data = info.Get("data");
            if (data != null) {
                // If there's inline attachment data, decode and store it:
                if (data is string) {
                    _data = Convert.FromBase64String((string)data);
                } else {
                    _data = data as IEnumerable<byte>;
                }

                if (_data == null) {
                    throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadEncoding, TAG,
                        "Invalid data type ({0}) in ctor", data.GetType().Name);
                }

                SetPossiblyEncodedLength(_data.LongCount());
            } else if (info.GetCast<bool>("stub", false)) {
                // This item is just a stub; validate and skip it
                if(info.ContainsKey("revpos")) {
                    var revPos = info.GetCast("revpos", -1);  // PouchDB has a bug that generates "revpos":0; allow this (#627)
                    if (revPos < 0) {
                        throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadAttachment, TAG,
                            "Invalid revpos ({0}) in ctor", revPos);
                    }

                    RevPos = revPos;
                }
            } else if (info.GetCast<bool>("follows", false)) {
                // I can't handle this myself; my caller will look it up from the digest
                if (Digest == null) {
                    throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadAttachment, TAG,
                        "follows is true, but the attachment digest is null in ctor");
                }

                if(info.ContainsKey("revpos")) {
                    var revPos = info.GetCast("revpos", -1);  // PouchDB has a bug that generates "revpos":0; allow this (#627)
                    if (revPos < 0) {
                        throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadAttachment, TAG,
                            "Invalid revpos ({0}) in ctor", revPos);
                    }

                    RevPos = revPos;
                }
            } else {
                throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadAttachment, TAG,
                    "Neither data nor stub nor follows was specified on the attachment data");
            }
        }
开发者ID:jonfunkhouser,项目名称:couchbase-lite-net,代码行数:67,代码来源:AttachmentInternal.cs


示例9: FileForAttachmentDict

        internal Uri FileForAttachmentDict(IDictionary<String, Object> attachmentDict)
        {
            if (!IsOpen) {
                Log.W(TAG, "FileForAttachmentDict called on closed database");
                return null;
            }

            var digest = (string)attachmentDict.Get("digest");
            if (digest == null) {
                return null;
            }

            string path = null;
            var pending = PendingAttachmentsByDigest.Get(digest);
            if (pending != null) {
                path = pending.FilePath;
            } else {
                // If it's an installed attachment, ask the blob-store for it:
                var key = new BlobKey(digest);
                path = Attachments.PathForKey(key);
            }

            Uri retVal = null;
            if (!Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out retVal)) {
                return null;
            }

            return retVal;
        }
开发者ID:pkdevboxy,项目名称:couchbase-lite-net,代码行数:29,代码来源:Database.cs


示例10: GetKeyForFilename

 public bool GetKeyForFilename(BlobKey outKey, string filename)
 {
     if (!filename.EndsWith(FileExtension))
     {
         return false;
     }
     //trim off extension
     string rest = Sharpen.Runtime.Substring(filename, path.Length + 1, filename.Length
          - FileExtension.Length);
     outKey.SetBytes(BlobKey.ConvertFromHex(rest));
     return true;
 }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:12,代码来源:BlobStore.cs


示例11: GetSizeOfBlob

 public long GetSizeOfBlob(BlobKey key)
 {
     string path = PathForKey(key);
     FilePath file = new FilePath(path);
     return file.Length();
 }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:6,代码来源:BlobStore.cs


示例12: PathForKey

 public string PathForKey(BlobKey key)
 {
     return path + FilePath.separator + BlobKey.ConvertToHex(key.GetBytes()) + FileExtension;
 }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:4,代码来源:BlobStore.cs


示例13: Finish

		/// <summary>Call this after all the data has been added.</summary>
		/// <remarks>Call this after all the data has been added.</remarks>
		public virtual void Finish()
		{
			try
			{
				outStream.Close();
			}
			catch (IOException e)
			{
				Log.W(Database.Tag, "Exception closing output stream", e);
			}
			blobKey = new BlobKey(sha1Digest.Digest());
			md5DigestResult = md5Digest.Digest();
		}
开发者ID:Redth,项目名称:couchbase-lite-net,代码行数:15,代码来源:BlobStoreWriter.cs


示例14: GetAttachmentsFromRevision

		internal IDictionary<string, AttachmentInternal> GetAttachmentsFromRevision(RevisionInternal
			 rev)
		{
			IDictionary<string, object> revAttachments = (IDictionary<string, object>)rev.GetPropertyForKey
				("_attachments");
			if (revAttachments == null || revAttachments.Count == 0 || rev.IsDeleted())
			{
				return new Dictionary<string, AttachmentInternal>();
			}
			IDictionary<string, AttachmentInternal> attachments = new Dictionary<string, AttachmentInternal
				>();
			foreach (string name in revAttachments.Keys)
			{
				IDictionary<string, object> attachInfo = (IDictionary<string, object>)revAttachments
					.Get(name);
				string contentType = (string)attachInfo.Get("content_type");
				AttachmentInternal attachment = new AttachmentInternal(name, contentType);
				string newContentBase64 = (string)attachInfo.Get("data");
				if (newContentBase64 != null)
				{
					// If there's inline attachment data, decode and store it:
					byte[] newContents;
					try
					{
						newContents = Base64.Decode(newContentBase64);
					}
					catch (IOException e)
					{
						throw new CouchbaseLiteException(e, Status.BadEncoding);
					}
					attachment.SetLength(newContents.Length);
					BlobKey outBlobKey = new BlobKey();
					bool storedBlob = GetAttachments().StoreBlob(newContents, outBlobKey);
					attachment.SetBlobKey(outBlobKey);
					if (!storedBlob)
					{
						throw new CouchbaseLiteException(Status.StatusAttachmentError);
					}
				}
				else
				{
					if (attachInfo.ContainsKey("follows") && ((bool)attachInfo.Get("follows")) == true)
					{
						// "follows" means the uploader provided the attachment in a separate MIME part.
						// This means it's already been registered in _pendingAttachmentsByDigest;
						// I just need to look it up by its "digest" property and install it into the store:
						InstallAttachment(attachment, attachInfo);
					}
					else
					{
						// This item is just a stub; validate and skip it
						if (((bool)attachInfo.Get("stub")) == false)
						{
							throw new CouchbaseLiteException("Expected this attachment to be a stub", Status.
								BadAttachment);
						}
						int revPos = ((int)attachInfo.Get("revpos"));
						if (revPos <= 0)
						{
							throw new CouchbaseLiteException("Invalid revpos: " + revPos, Status.BadAttachment
								);
						}
						continue;
					}
				}
				// Handle encoded attachment:
				string encodingStr = (string)attachInfo.Get("encoding");
				if (encodingStr != null && encodingStr.Length > 0)
				{
					if (Sharpen.Runtime.EqualsIgnoreCase(encodingStr, "gzip"))
					{
						attachment.SetEncoding(AttachmentInternal.AttachmentEncoding.AttachmentEncodingGZIP
							);
					}
					else
					{
						throw new CouchbaseLiteException("Unnkown encoding: " + encodingStr, Status.BadEncoding
							);
					}
					attachment.SetEncodedLength(attachment.GetLength());
					if (attachInfo.ContainsKey("length"))
					{
						Number attachmentLength = (Number)attachInfo.Get("length");
						attachment.SetLength(attachmentLength);
					}
				}
				if (attachInfo.ContainsKey("revpos"))
				{
					attachment.SetRevpos((int)attachInfo.Get("revpos"));
				}
				else
				{
					attachment.SetRevpos(1);
				}
				attachments.Put(name, attachment);
			}
			return attachments;
		}
开发者ID:Redth,项目名称:couchbase-lite-net,代码行数:98,代码来源:Database.cs


示例15: GetAttachmentsDictForSequenceWithContent

		public IDictionary<string, object> GetAttachmentsDictForSequenceWithContent(long 
			sequence, EnumSet<Database.TDContentOptions> contentOptions)
		{
			System.Diagnostics.Debug.Assert((sequence > 0));
			Cursor cursor = null;
			string[] args = new string[] { System.Convert.ToString(sequence) };
			try
			{
				cursor = database.RawQuery("SELECT filename, key, type, length, revpos FROM attachments WHERE sequence=?"
					, args);
				if (!cursor.MoveToNext())
				{
					return null;
				}
				IDictionary<string, object> result = new Dictionary<string, object>();
				while (!cursor.IsAfterLast())
				{
					bool dataSuppressed = false;
					int length = cursor.GetInt(3);
					byte[] keyData = cursor.GetBlob(1);
					BlobKey key = new BlobKey(keyData);
					string digestString = "sha1-" + Base64.EncodeBytes(keyData);
					string dataBase64 = null;
					if (contentOptions.Contains(Database.TDContentOptions.TDIncludeAttachments))
					{
						if (contentOptions.Contains(Database.TDContentOptions.TDBigAttachmentsFollow) && 
							length >= Database.kBigAttachmentLength)
						{
							dataSuppressed = true;
						}
						else
						{
							byte[] data = attachments.BlobForKey(key);
							if (data != null)
							{
								dataBase64 = Base64.EncodeBytes(data);
							}
							else
							{
								// <-- very expensive
								Log.W(Database.Tag, "Error loading attachment");
							}
						}
					}
					IDictionary<string, object> attachment = new Dictionary<string, object>();
					if (dataBase64 == null || dataSuppressed == true)
					{
						attachment.Put("stub", true);
					}
					if (dataBase64 != null)
					{
						attachment.Put("data", dataBase64);
					}
					if (dataSuppressed == true)
					{
						attachment.Put("follows", true);
					}
					attachment.Put("digest", digestString);
					string contentType = cursor.GetString(2);
					attachment.Put("content_type", contentType);
					attachment.Put("length", length);
					attachment.Put("revpos", cursor.GetInt(4));
					string filename = cursor.GetString(0);
					result.Put(filename, attachment);
					cursor.MoveToNext();
				}
				return result;
			}
			catch (SQLException e)
			{
				Log.E(Database.Tag, "Error getting attachments for sequence", e);
				return null;
			}
			finally
			{
				if (cursor != null)
				{
					cursor.Close();
				}
			}
		}
开发者ID:Redth,项目名称:couchbase-lite-net,代码行数:81,代码来源:Database.cs


示例16: KeyForBlobFromFile

 public static BlobKey KeyForBlobFromFile(FileInfo file)
 {
     MessageDigest md;
     try
     {
         md = MessageDigest.GetInstance("SHA-1");
     }
     catch (NoSuchAlgorithmException)
     {
         Log.E(Database.Tag, "Error, SHA-1 digest is unavailable.");
         return null;
     }
     byte[] sha1hash = new byte[40];
     try
     {
         var fis = new FileInputStream(file);
         byte[] buffer = new byte[65536];
         int lenRead = fis.Read(buffer);
         while (lenRead > 0)
         {
             md.Update(buffer, 0, lenRead);
             lenRead = fis.Read(buffer);
         }
         fis.Close();
     }
     catch (IOException)
     {
         Log.E(Database.Tag, "Error readin tmp file to compute key");
     }
     sha1hash = md.Digest();
     BlobKey result = new BlobKey(sha1hash);
     return result;
 }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:33,代码来源:BlobStore.cs


示例17: UploadMultipartRevision

        private bool UploadMultipartRevision(RevisionInternal revision)
        {
            MultipartContent multiPart = null;
            var revProps = revision.GetProperties();

            var attachments = revProps.Get("_attachments").AsDictionary<string,object>();
            foreach (var attachmentKey in attachments.Keys) {
                var attachment = attachments.Get(attachmentKey).AsDictionary<string,object>();
                if (attachment.ContainsKey("follows")) {
                    if (multiPart == null) {
                        multiPart = new MultipartContent("related");
                        try {
                            var json = Manager.GetObjectMapper().WriteValueAsString(revProps);
                            var utf8charset = Encoding.UTF8;
                            //multiPart.Add(new StringContent(json, utf8charset, "application/json"), "param1");

                            var jsonContent = new StringContent(json, utf8charset, "application/json");
                            //jsonContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                            multiPart.Add(jsonContent);
                        } catch (IOException e) {
                            throw new ArgumentException("Not able to serialize revision properties into a multipart request content.", e);
                        }
                    }

                    var blobStore = LocalDatabase.Attachments;
                    var base64Digest = (string)attachment.Get("digest");

                    var blobKey = new BlobKey(base64Digest);
                    var inputStream = blobStore.BlobStreamForKey(blobKey);

                    if (inputStream == null) {
                        Log.W(TAG, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision.");
                        multiPart = null;
                    } else {
                        string contentType = null;
                        if (attachment.ContainsKey("content_type")) {
                            contentType = (string)attachment.Get("content_type");
                        } else {
                            if (attachment.ContainsKey("content-type")) {
                                var message = string.Format("Found attachment that uses content-type"
                                              + " field name instead of content_type (see couchbase-lite-android"
                                              + " issue #80): " + attachment);
                                Log.W(TAG, message);
                            }
                        }

                        var content = new StreamContent(inputStream);
                        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                            FileName = attachmentKey
                        };
                        content.Headers.ContentType = new MediaTypeHeaderValue(contentType ?? "application/octet-stream");

                        multiPart.Add(content);
                    }
                }
            }

            if (multiPart == null) {
                return false;
            }

            var path = string.Format("/{0}?new_edits=false", revision.GetDocId());

            // TODO: need to throttle these requests
            Log.D(TAG, "Uploading multipart request.  Revision: " + revision);
            SafeAddToChangesCount(1);
            SendAsyncMultipartRequest(HttpMethod.Put, path, multiPart, (result, e) => 
            {
                if (e != null) {
                    var httpError = e as HttpResponseException;
                    if (httpError != null) {
                        if (httpError.StatusCode == System.Net.HttpStatusCode.UnsupportedMediaType) {
                            _dontSendMultipart = true;
                            UploadJsonRevision(revision);
                        }
                    } else {
                        Log.E (TAG, "Exception uploading multipart request", e);
                        LastError = e;
                        RevisionFailed();
                    }
                } else {
                    Log.D (TAG, "Uploaded multipart request.  Result: " + result);
                    SafeIncrementCompletedChangesCount();
                    RemovePending(revision);
                }
            });

            return true;
        }
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:89,代码来源:Pusher.cs


示例18: BlobForKey

 public byte[] BlobForKey(BlobKey key)
 {
     string path = PathForKey(key);
     FilePath file = new FilePath(path);
     byte[] result = null;
     try
     {
         result = GetBytesFromFile(file);
     }
     catch (IOException e)
     {
         Log.E(Database.Tag, "Error reading file", e);
     }
     return result;
 }
开发者ID:FireflyLogic,项目名称:couchbase-lite-net,代码行数:15,代码来源:BlobStore.cs


示例19: ProcessAttachmentsForRevision

        internal bool ProcessAttachmentsForRevision(RevisionInternal rev, IList<string> ancestry)
        {
            var revAttachments = rev.GetAttachments();
            if (revAttachments == null) {
                return true; // no-op: no attachments
            }

            // Deletions can't have attachments:
            if (rev.IsDeleted() || revAttachments.Count == 0) {
                var body = rev.GetProperties();
                body.Remove("_attachments");
                rev.SetProperties(body);
                return true;
            }

            var prevRevId = ancestry != null && ancestry.Count > 0 ? ancestry[0] : null;
            int generation = RevisionInternal.GenerationFromRevID(prevRevId) + 1;
            IDictionary<string, object> parentAttachments = null;
            return rev.MutateAttachments((name, attachInfo) =>
            {
                AttachmentInternal attachment = null;
                try {
                    attachment = new AttachmentInternal(name, attachInfo);
                } catch(CouchbaseLiteException) {
                    return null;
                }

                if(attachment.EncodedContent != null) {
                    // If there's inline attachment data, decode and store it:
                    BlobKey blobKey = new BlobKey();
                    if(!Attachments.StoreBlob(attachment.EncodedContent.ToArray(), blobKey)) {
                        throw new CouchbaseLiteException(
                            String.Format("Failed to write attachment ' {0}'to disk", name), StatusCode.AttachmentError);
                    }

                    attachment.BlobKey = blobKey;
                } else if(attachInfo.GetCast<bool>("follows")) {
                    // "follows" means the uploader provided the attachment in a separate MIME part.
                    // This means it's already been registered in _pendingAttachmentsByDigest;
                    // I just need to look it up by its "digest" property and install it into the store:
                    InstallAttachment(attachment);
                } else if(attachInfo.GetCast<bool>("stub")) {
                    // "stub" on an incoming revision means the attachment is the same as in the parent.
                    if(parentAttachments == null && prevRevId != null) {
                        parentAttachments = GetAttachmentsFromDoc(rev.GetDocId(), prevRevId);
                        if(parentAttachments == null) {
                            if(Attachments.HasBlobForKey(attachment.BlobKey)) {
                                // Parent revision's body isn't known (we are probably pulling a rev along
                                // with its entire history) but it's OK, we have the attachment already
                                return attachInfo;
                            }

                            var ancestorAttachment = FindAttachment(name, attachment.RevPos, rev.GetDocId(), ancestry);
                            if(ancestorAttachment != null) {
                                return ancestorAttachment;
                            }

                            throw new CouchbaseLiteException(
                                String.Format("Unable to find 'stub' attachment {0} in history", name), StatusCode.BadAttachment);
                        }
                    }

                    var parentAttachment = parentAttachments == null ? null : parentAttachments.Get(name).AsDictionary<string, object>();
                    if(parentAttachment == null) {
                        throw new CouchbaseLiteException(
                            String.Format("Unable to find 'stub' attachment {0} in history", name), StatusCode.BadAttachment);
                    }

                    return parentAttachment;
                }


                // Set or validate the revpos:
                if(attachment.RevPos == 0) {
                    attachment.RevPos = generation;
                } else if(attachment.RevPos > generation) {
                    throw new CouchbaseLiteException(
                        String.Format("Attachment specifies revision generation {0} but document is only at revision generation {1}",
                        attachment.RevPos, generation), StatusCode.BadAttachment);
                }

                Debug.Assert(attachment.IsValid);
                return attachment.AsStubDictionary();
            });
        }
开发者ID:pkdevboxy,项目名称:couchbase-lite-net,代码行数:85,代码来源:Database.cs


示例20: BlobStreamForKey

 public Stream BlobStreamForKey(BlobKey key)
 {
     var path = PathForKey(key);
     Log.D(Database.Tag, "Blob Path : " + path);
     var file = new FilePath(path);
     if (file.CanRead())
     {
         try
         {
             return new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
         }
         catch (FileNotFoundException e)
         {
             Log.E(Database.Tag, "Unexpected file not found in blob store", e);
             return null;
         }
         catch (Exception e)
         {
             Log.E(Database.Tag, "Cannot  

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Lite.Database类代码示例发布时间:2022-05-24
下一篇:
C# Client.ClientConfiguration类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap