本文整理汇总了C#中Couchbase.Lite.BlobKey类的典型用法代码示例。如果您正苦于以下问题:C# BlobKey类的具体用法?C# BlobKey怎么用?C# BlobKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BlobKey类属于Couchbase.Lite命名空间,在下文中一共展示了BlobKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
);
}
示例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;
}
示例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->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->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;
}
示例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;
}
示例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();
}
}
}
示例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();
}
}
}
示例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");
}
}
示例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;
}
示例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;
}
示例11: GetSizeOfBlob
public long GetSizeOfBlob(BlobKey key)
{
string path = PathForKey(key);
FilePath file = new FilePath(path);
return file.Length();
}
示例12: PathForKey
public string PathForKey(BlobKey key)
{
return path + FilePath.separator + BlobKey.ConvertToHex(key.GetBytes()) + FileExtension;
}
示例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();
}
示例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;
}
示例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();
}
}
}