/// <summary> /// Allow to append a new content stream after the current one and select it /// </summary> public void NewContentStreamAfter() { var index = Math.Min(contentStreams.IndexOf(CurrentStream) + 1, contentStreams.Count); CurrentStream = new ContentStream(); contentStreams.Insert(index, CurrentStream); }
public unsafe override void Write(ProcessedAudio input, ContentStream writer, WriterContext ctx) { try { writer.Write(input.FrameCount); writer.Write(input.SampleRate); writer.Write(input.Stereo); writer.Write(false); // true = lossy, false = lossless byte * data = (byte *)input.Data.ToPointer(); RLADAudio rlad = input as RLADAudio; uint lmod = input.Stereo ? 2u : 1; uint len = 0; for (uint ci = 0; ci < rlad.ChunkCount; ++ci, data += len) { var stype = rlad.Chunks[ci].Type; var extra = rlad.Chunks[ci].Extra; var head = ((stype & 0x03) << 6) | (extra & 0x3F); writer.Write((byte)(head & 0xFF)); // First calculate the length assuming one chunk of mono data, then correct for stereo and chunk count len = (stype == RLADAudio.SMALL_TYPE) ? 8u : (stype == RLADAudio.MED_TYPE) ? 12u : 16u; len *= (lmod * (extra + 1u)); writer.Write(data, len); } } finally { input.Dispose(); } }
/// <summary> /// Allow to append a new content stream before the current one and select it /// </summary> public void NewContentStreamBefore() { var index = Math.Max(contentStreams.IndexOf(CurrentStream) - 1, 0); CurrentStream = new ContentStream(); contentStreams.Insert(index, CurrentStream); }
/// <summary> /// Creates a document. /// </summary> /// <returns>The document.</returns> /// <param name="folder">Parent folder.</param> /// <param name="name">Name of the document.</param> /// <param name="content">If content is not null, a content stream containing the given content will be added.</param> /// <param name="checkedOut">If true, the new document will be created in checked out state.</param> public static IDocument CreateDocument(this IFolder folder, string name, string content, bool checkedOut = false) { Dictionary <string, object> properties = new Dictionary <string, object>(); properties.Add(PropertyIds.Name, name); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); if (string.IsNullOrEmpty(content)) { return(folder.CreateDocument(properties, null, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null)); } ContentStream contentStream = new ContentStream(); contentStream.FileName = name; contentStream.MimeType = MimeType.GetMIMEType(name); contentStream.Length = content.Length; IDocument doc = null; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = stream; doc = folder.CreateDocument(properties, contentStream, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null); } return(doc); }
public ContentStream Download(string DocumentID) { try { Document doc = session.GetObject(DocumentID) as Document; ContentStream contentStream = (DotCMIS.Data.Impl.ContentStream)doc.GetContentStream(); Stream stream = contentStream.Stream; string path = AppDomain.CurrentDomain.BaseDirectory + @"\downloadtemp\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var fileStream = File.Create(path + contentStream.FileName)) { contentStream.Stream.CopyTo(fileStream); } return(contentStream); } catch (Exception ex) { throw ex as Exception; } }
private static void UploadTest() { AuthInfo authInfo = AuthInfo.ReadAuthInfo(); ISession session = SessionUtils.CreateSession(authInfo.serviceUrl, authInfo.username, authInfo.password); //IFolder rootFolder = session.GetRootFolder(); IFolder userHomeFolder = GetUserFolder(session, authInfo.username); // document name string formattedName = "Home Page.pdf"; // define dictionary IDictionary <string, object> properties = new Dictionary <string, object>(); properties.Add(PropertyIds.Name, formattedName); // define object type as document, as we wanted to create document properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); // read a empty document with empty bytes // fileUpload1: is a .net file upload control byte[] datas = File.ReadAllBytes("C:\\Users\\KVM\\Home Page.pdf"); ContentStream contentStream = new ContentStream { FileName = formattedName, MimeType = "application/pdf", Length = datas.Length, Stream = new MemoryStream(datas) }; // this statment would create document in default repository userHomeFolder.CreateDocument(properties, contentStream, null); Debug.WriteLine("OK"); }
private void UpdateFile(string filePath, IDocument remoteFile) { Logger.Info("CmisDirectory | ## Updating " + filePath); Stream localfile = File.OpenRead(filePath); if ((localfile == null) && (localfile.Length == 0)) { Logger.Info("Sync | Skipping update of file with null or empty content stream: " + filePath); return; } // Prepare content stream ContentStream remoteStream = new ContentStream(); remoteStream.FileName = remoteFile.ContentStreamFileName; remoteStream.Length = localfile.Length; remoteStream.MimeType = MimeType.GetMIMEType(Path.GetFileName(filePath)); remoteStream.Stream = localfile; remoteStream.Stream.Flush(); Logger.Info("CmisDirectory | before SetContentStream"); // CMIS do not have a Method to upload block by block. So upload file must be full. // We must waiting for support of CMIS 1.1 https://issues.apache.org/jira/browse/CMIS-628 // http://docs.oasis-open.org/cmis/CMIS/v1.1/cs01/CMIS-v1.1-cs01.html#x1-29700019 // DotCMIS.Client.IObjectId objID = remoteFile.SetContentStream(remoteStream, true, true); remoteFile.SetContentStream(remoteStream, true, true); Logger.Info("CmisDirectory | after SetContentStream"); localfile.Close(); localfile.Dispose(); remoteStream.Stream.Close(); Logger.Info("CmisDirectory | ## Updated " + filePath); }
private TValue GetTask(long blockposition) { lock (_object) { ContentStream.Position = blockposition; byte[] check = new byte[2]; ContentStream.Read(check, 0, 2); if (check[0] != startbyteone && check[1] != startbytetwo) { return(default(TValue)); } byte[] counter = new byte[4]; ContentStream.Read(counter, 0, 4); int len = BitConverter.ToInt32(counter, 0); byte[] content = new byte[len]; ContentStream.Read(content, 0, len); return(this.ValueConverter.FromByte(content)); } }
protected ContentStream GetContentStream() { ContentStream stream = null; if (_allContent.Length > 0) { var content = UTF8Encoding.UTF8.GetBytes(_allContent.ToString()); stream = new ContentStream(); stream.Stream = new MemoryStream(content); stream.Length = content.LongLength; stream.MimeType = MimeTypeInternal; } else if (!String.IsNullOrEmpty(LocalFileInternal)) { var fileStream = new FileStream(LocalFileInternal, FileMode.Open, FileAccess.Read, FileShare.Read); stream = new ContentStream(); var ext = System.IO.Path.GetExtension(LocalFileInternal); stream.Stream = fileStream; stream.MimeType = MimeTypeMap.MimeTypeMap.GetMimeType(ext); stream.Length = fileStream.Length; stream.FileName = fileStream.Name; } return(stream); }
public void Dispose() { if (ContentStream != null) { ContentStream.Dispose(); } }
private Stream ReplaceContentStreamWithMemoryStream() { if (ContentStream is DurableMemoryStream) { return(ContentStream); } var buffer = new byte[4096]; var stream = new MemoryStream(); var count = 0; do { if (ContentStream == null) { continue; } count = ContentStream.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, count); } while (count != 0); if (ContentStream != null) { ContentStream.Close(); ContentStream.Dispose(); } if (stream.CanSeek) { stream.Position = 0; } return(new DurableMemoryStream(stream)); }
public Path(ContentStream contentStream, GraphicsState graphicsState) { _contentStream = contentStream; GraphicsState = graphicsState; _startPath(); }
public void RemoteDocumentCreation(string ignoredCanonicalName, string ignoredLocalPath, string remoteFolderPath, string url, string user, string password, string repositoryId) { // Prepare remote folder and CmisSync process. IFolder remoteBaseFolder = ClearRemoteCMISFolder(url, user, password, repositoryId, remoteFolderPath); sync = new CmisSyncProcess(remoteFolderPath, url, user, password, repositoryId); // Remote file creations string[] remoteFilenames = { "document.txt", "いろんなカタチが、見えてくる。", "مشاور", "コンサルティングपरामर्शदाता컨설턴트" }; foreach (string remoteFilename in remoteFilenames) { // Create remote file IDictionary <string, object> properties = new Dictionary <string, object>(); properties[PropertyIds.Name] = remoteFilename; properties[PropertyIds.ObjectTypeId] = "cmis:document"; byte[] creationContent = UTF8Encoding.UTF8.GetBytes("Hello World!"); ContentStream creationContentStream = new ContentStream(); creationContentStream.FileName = remoteFilename; creationContentStream.MimeType = "text/plain"; creationContentStream.Length = creationContent.Length; creationContentStream.Stream = new MemoryStream(creationContent); remoteBaseFolder.CreateDocument(properties, creationContentStream, null); // Wait for a few seconds so that sync gets a chance to sync things. Thread.Sleep(20 * 1000); // Check locally Assert.True(File.Exists(Path.Combine(sync.Folder(), (String)properties[PropertyIds.Name]))); } }
private IDocument CreateNewFile(IFolder folder, string file) { try { var fi = new FileInfo(file); IDictionary <string, object> properties = new Dictionary <string, object>(); properties[PropertyIds.Name] = fi.Name; properties[PropertyIds.ObjectTypeId] = "cmis:document"; var content = File.ReadAllBytes(fi.FullName); var contentStream = new ContentStream { FileName = fi.Name, MimeType = "application/pdf", Length = content.Length, Stream = new MemoryStream(content) }; var doc = folder.CreateDocument(properties, contentStream, null); Log.Information("Uploaded new document"); return(doc); } catch (Exception e) { Console.WriteLine(e); } return(null); }
public void ContentStream_ctor_NullAssembler_Throws() { Assert.Throws <ArgumentNullException>(() => { var c = new ContentStream(Guid.Empty, null); }); }
private static void UploadRandomDocumentTo(IFolder folder) { string filename = "file_" + Guid.NewGuid() + ".bin"; //byte[] content = UTF8Encoding.UTF8.GetBytes("Hello World!"); int sizeInMb = 40; byte[] data = new byte[sizeInMb * 1024 * 1024]; Random rng = new Random(); rng.NextBytes(data); IDictionary<string, object> properties = new Dictionary<string, object>(); properties[PropertyIds.Name] = filename; properties[PropertyIds.ObjectTypeId] = "cmis:document"; ContentStream contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = "application/octet-stream"; contentStream.Length = data.Length; contentStream.Stream = new MemoryStream(data); Console.Write("Uploading " + filename + " ... "); folder.CreateDocument(properties, contentStream, null); Console.WriteLine(" Done."); contentStream.Stream.Close(); contentStream.Stream.Dispose(); }
/// <summary> /// Sets the request stream. /// </summary> /// <param name="requestStreamContent">The content stream to copy into the request stream.</param> internal void SetRequestStream(ContentStream requestStreamContent) { if (requestStreamContent.IsKnownMemoryStream) { this.SetContentLengthHeader(); } #if DEBUG this.ValidateHeaders(); #endif using (Stream requestStream = this.requestMessage.GetStream()) { if (requestStreamContent.IsKnownMemoryStream) { MemoryStream bufferableStream = (MemoryStream)requestStreamContent.Stream; Debug.Assert(bufferableStream.Position == 0, "Cached/buffered stream position should be 0"); byte[] buffer = bufferableStream.GetBuffer(); int bufferOffset = checked ((int)bufferableStream.Position); int bufferLength = checked ((int)bufferableStream.Length) - bufferOffset; // the following is useful in the debugging Immediate Window // string x = System.Text.Encoding.UTF8.GetString(buffer, bufferOffset, bufferLength); requestStream.Write(buffer, bufferOffset, bufferLength); } else { byte[] buffer = new byte[WebUtil.DefaultBufferSizeForStreamCopy]; WebUtil.CopyStream(requestStreamContent.Stream, requestStream, ref buffer); } } }
public void Update(IRepository repository, String folderName, Document document) { var parameters = GetParameters(repository.Id); var session = _factory.CreateSession(parameters); var properties = new Dictionary <string, object>(); properties[PropertyIds.Name] = document.ContentStreamFileName; properties[PropertyIds.ObjectTypeId] = "cmis:document"; var content = Encoding.UTF8.GetBytes(String.Format("Hello World at {0}", Guid.NewGuid())); var newDoc = (Document)session.GetObject(document.Id); if (repository.Capabilities.ContentStreamUpdatesCapability == CapabilityContentStreamUpdates.Anyime) { //Need to 'check-out' prior to update" return; } var contentStream = new ContentStream { FileName = String.Format("Hello World at {0}", Guid.NewGuid()), MimeType = "text/plain", Length = content.Length, Stream = new MemoryStream(content) }; newDoc.SetContentStream(contentStream, true); }
public void GetContentStreamHash( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { Regex entryRegex = new Regex(@"^\{.+\}[0-9a-fA-F]+$"); ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); string filename = "hashedfile.txt"; try { IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument; if (doc != null) { doc.Delete(true); } } catch (CmisObjectNotFoundException) { } Dictionary <string, object> properties = new Dictionary <string, object>(); properties.Add(PropertyIds.Name, filename); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); using (var oneByteStream = new MemoryStream(new byte[1])) { ContentStream contentStream = new ContentStream(); contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = 1; contentStream.Stream = oneByteStream; var emptyDoc = folder.CreateDocument(properties, contentStream, null); var context = new OperationContext(); IDocument requestedDoc = session.GetObject(emptyDoc, context) as IDocument; foreach (var prop in requestedDoc.Properties) { if (prop.Id == "cmis:contentStreamHash") { Assert.That(prop.IsMultiValued, Is.True); if (prop.Values != null) { foreach (string entry in prop.Values) { Assert.That(entryRegex.IsMatch(entry)); } } } } byte[] remoteHash = requestedDoc.ContentStreamHash(); if (remoteHash != null) { Assert.That(remoteHash, Is.EqualTo(SHA1.Create().ComputeHash(new byte[1]))); } requestedDoc.Delete(true); } }
public virtual void DumpToStream(ContentStream stream) { // byte[] pageBytes = Encoding.UTF8.GetBytes(this.HTMLContent); // stream.Write(pageBytes, 0, pageBytes.Length); this.Parse(); stream.Write(this.HTMLContent); }
public void WriteThenRead(string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId) { string fileName = "test.txt"; var cmisParameters = new Dictionary <string, string>(); cmisParameters[SessionParameter.BindingType] = BindingType.AtomPub; cmisParameters[SessionParameter.AtomPubUrl] = url; cmisParameters[SessionParameter.User] = user; cmisParameters[SessionParameter.Password] = Crypto.Deobfuscate(password); cmisParameters[SessionParameter.RepositoryId] = repositoryId; SessionFactory factory = SessionFactory.NewInstance(); ISession session = factory.GetRepositories(cmisParameters)[0].CreateSession(); // IFolder root = session.GetRootFolder(); IFolder root = (IFolder)session.GetObjectByPath(remoteFolderPath); Dictionary <string, object> properties = new Dictionary <string, object>(); properties.Add(PropertyIds.Name, fileName); properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); // Should CmisSync try to guess? byte[] bytes = Encoding.UTF8.GetBytes("Hello,world!"); contentStream.Stream = new MemoryStream(bytes); contentStream.Length = bytes.Length; // Create file. DotCMIS.Enums.VersioningState?state = null; if (true != session.RepositoryInfo.Capabilities.IsAllVersionsSearchableSupported) { state = DotCMIS.Enums.VersioningState.None; } session.CreateDocument(properties, root, contentStream, state); // Check whether file is present. IItemEnumerable <ICmisObject> children = root.GetChildren(); bool found = false; foreach (ICmisObject child in children) { string childFileName = (string)child.GetPropertyValue(PropertyIds.Name); Console.WriteLine(childFileName); if (childFileName.Equals(fileName)) { found = true; } } Assert.True(found); // Clean. IDocument doc = (IDocument)session.GetObjectByPath((remoteFolderPath + "/" + fileName).Replace("//", "/")); doc.DeleteAllVersions(); }
public void LoadText(string text) { ContentType = "text/html"; byte[] buf = EncodingText.GetBytes(text); ContentStream = (Stream)(new MemoryStream()); ContentStream.Write(buf, 0, buf.Length); }
public void Empty() { if (ContentStream != null) { ContentStream.Dispose(); ContentStream = null; } }
public void ContentStream_Id() { var id = Guid.NewGuid(); var assembler = new PayloadStreamAssembler(null, id); var c = new ContentStream(id, assembler); Assert.AreEqual(id, c.Id); }
/// <summary> /// Releases the unmanaged resources used by the Attachment and /// optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing && !_isDisposed) { _isDisposed = true; ContentStream.Dispose(); } }
public IDocument CreateTempDocument(CmisPath path, ContentStream stream, IDictionary <string, object> properties) { var doc = _cmisNav.CreateDocument(path, stream, properties); _createdObjects.Add(doc); return(doc); }
internal ShapeContext(ContentStream contentStream, PageResources resources) { _contentStream = contentStream; _contentStream.SaveState(); State = new GraphicsState(resources); }
/// <summary> /// Initializes a new instance of the PDF canvas with the specified page size. /// <para> /// A PDF with a single page of the specified size will be created. The QR bill /// will be drawn in the bottom left corner of the page. /// </para> /// </summary> /// <param name="width">The page width, in mm.</param> /// <param name="height">The page height, in mm.</param> public PDFCanvas(double width, double height) { SetupFontMetrics("Helvetica"); _document = new Document("Swiss QR Bill"); Page page = _document.CreatePage((float)(width * MmToPt), (float)(height * MmToPt)); _contentStream = page.Contents; }
protected ContentStream File(string name) { var stream = new ContentStream(_directory, name, ""); _streams.Add(stream); return(stream); }
/// <summary> /// Sets the content from a stream into the request. /// </summary> /// <param name="stream">The stream of content.</param> /// <param name="progress">The progress callback to report on the amount of data that's been uploaded.</param> public void SetContent(Stream stream, Connection.ProgressCallback progress) { this.ContentStream = stream; this.ContentLength = stream.Length; this.Progress = progress; this.ETag = StringifyMD5(new MD5CryptoServiceProvider().ComputeHash(ContentStream)); ContentStream.Seek(0, 0); }
public virtual void WriteBodyToConnection(Connection connection) { try { Byte[] lBuffer; if (HasOnTransferProgress) { connection.OnBytesSent += new EventHandler(HandleOnBytesSent); connection.ResetStatistics(); } switch (ContentSource) { case ContentSource.ContentBytes: TriggerOnTransferStart(TransferDirection.Send, ContentBytes.Length); connection.Send(ContentBytes); TriggerOnTransferEnd(TransferDirection.Send); break; case ContentSource.ContentStream: TriggerOnTransferStart(TransferDirection.Send, ContentStream.Length); lBuffer = new Byte[BUFFER_SIZE]; Int32 lBytesRead; do { lBytesRead = ContentStream.Read(lBuffer, 0, BUFFER_SIZE); if (lBytesRead != 0) { connection.Send(lBuffer, 0, lBytesRead); } }while (lBytesRead > 0); if (CloseStream) { ContentStream.Close(); } TriggerOnTransferEnd(TransferDirection.Send); break; case ContentSource.ContentNone: /* Nothing to do */ break; } if (HasOnTransferProgress) { connection.OnBytesSent -= new EventHandler(HandleOnBytesSent); } } finally { fContentBytes = null; fContentStream = null; fContentString = null; } }
public IDocument CreateDocument(CmisPath path, ContentStream stream, IDictionary<string, object> properties) { var components = path.GetComponents(); var name = components[1]; if (name.Length == 0) { throw new CmisNameConstraintViolationException("The document name is empty."); } var folder = GetFolder(components[0]); var allProps = new Dictionary<string, object>() { { PropertyIds.ObjectTypeId, "cmis:document" }, { PropertyIds.Name, name } }; Utilities.UpdateDictionary(allProps, properties); return folder.CreateDocument(allProps, stream, VersioningState.Major); }
private static void Update(IDocument doc) { Stream data = File.OpenRead("../../local.txt"); ContentStream contentStream = new ContentStream(); contentStream.FileName = doc.ContentStreamFileName; contentStream.Length = data.Length; contentStream.MimeType = "application/octet-stream"; contentStream.Stream = data; contentStream.Stream.Flush(); Console.WriteLine("before"); doc.SetContentStream(contentStream, true, true); Console.WriteLine("after"); // Not reached the second time the method is called. data.Close(); data.Dispose(); contentStream.Stream.Close(); }
/// <summary> /// Creates a document. /// </summary> /// <returns>The document.</returns> /// <param name="folder">Parent folder.</param> /// <param name="name">Name of the document.</param> /// <param name="content">If content is not null, a content stream containing the given content will be added.</param> /// <param name="checkedOut">If true, the new document will be created in checked out state.</param> public static IDocument CreateDocument(this IFolder folder, string name, string content, bool checkedOut = false) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, name); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); if (string.IsNullOrEmpty(content)) { return folder.CreateDocument(properties, null, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null); } ContentStream contentStream = new ContentStream(); contentStream.FileName = name; contentStream.MimeType = MimeType.GetMIMEType(name); contentStream.Length = content.Length; IDocument doc = null; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = stream; doc = folder.CreateDocument(properties, contentStream, checkedOut ? (VersioningState?)VersioningState.CheckedOut : (VersioningState?)null); } return doc; }
protected ContentStream GetContentStream() { ContentStream stream = null; if (_allContent.Length > 0) { var content = UTF8Encoding.UTF8.GetBytes(_allContent.ToString()); stream = new ContentStream(); stream.Stream = new MemoryStream(content); stream.Length = content.LongLength; stream.MimeType = MimeTypeInternal; } else if (!String.IsNullOrEmpty(LocalFileInternal)) { var fileStream = new FileStream(LocalFileInternal, FileMode.Open, FileAccess.Read, FileShare.Read); stream = new ContentStream(); var ext = System.IO.Path.GetExtension(LocalFileInternal); stream.Stream = fileStream; stream.MimeType = MimeTypeMap.MimeTypeMap.GetMimeType(ext); stream.Length = fileStream.Length; stream.FileName = fileStream.Name; } return stream; }
public void SetContentStream(string repositoryId, string documentId, ContentStream contentStream, bool? overwriteFlag) { throw new NotImplementedException(); }
/// <summary> /// Upload new version of file. /// </summary> private bool UpdateFile(string filePath, IDocument remoteFile) { SleepWhileSuspended(); try { var syncItem = database.GetSyncItemFromLocalPath(filePath); if (null == syncItem) { syncItem = SyncItemFactory.CreateFromLocalPath(filePath, repoinfo); } Logger.Info("Updating: " + syncItem.LocalPath); using (Stream localfile = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // Ignore files with null or empty content stream. if ((localfile == null) && (localfile.Length == 0)) { Logger.Info("Skipping update of file with null or empty content stream: " + filePath); return true; } // Check is write permission is allow // Check if the file is Check out or not //if (!(bool)remoteFile.IsVersionSeriesCheckedOut) if ((remoteFile.IsVersionSeriesCheckedOut == null) || !(bool)remoteFile.IsVersionSeriesCheckedOut) { // Prepare content stream ContentStream remoteStream = new ContentStream(); remoteStream.FileName = remoteFile.ContentStreamFileName; remoteStream.Length = localfile.Length; remoteStream.MimeType = remoteFile.GetContentStream().MimeType; remoteStream.Stream = localfile; remoteStream.Stream.Flush(); Logger.Debug("before SetContentStream"); // CMIS do not have a Method to upload block by block. So upload file must be full. // We must waiting for support of CMIS 1.1 https://issues.apache.org/jira/browse/CMIS-628 // http://docs.oasis-open.org/cmis/CMIS/v1.1/cs01/CMIS-v1.1-cs01.html#x1-29700019 // DotCMIS.Client.IObjectId objID = remoteFile.SetContentStream(remoteStream, true, true); remoteFile.SetContentStream(remoteStream, true, true); Logger.Debug("after SetContentStream"); // Update timestamp in database. database.SetFileServerSideModificationDate(syncItem, ((DateTime)remoteFile.LastModificationDate).ToUniversalTime()); // Update checksum database.RecalculateChecksum(syncItem); // TODO Update metadata? Logger.Info("Updated: " + syncItem.LocalPath); return true; } else { string message = String.Format("File {0} is CheckOut on the server by another user: {1}", syncItem.LocalPath, remoteFile.CheckinComment); // throw new IOException("File is Check Out on the server"); Logger.Info(message); Utils.NotifyUser(message); return false; } } } catch (Exception e) { ProcessRecoverableException("Could not update file: " + filePath, e); return false; } }
/// <summary> /// Upload a single file to the CMIS server. /// </summary> private bool UploadFile(string filePath, IFolder remoteFolder) // TODO make SyncItem { SleepWhileSuspended(); var syncItem = database.GetSyncItemFromLocalPath(filePath); if (null == syncItem) { syncItem = SyncItemFactory.CreateFromLocalPath(filePath, repoinfo); } Logger.Info("Uploading: " + syncItem.LocalPath); try { IDocument remoteDocument = null; byte[] filehash = { }; // Prepare properties string remoteFileName = syncItem.RemoteFileName; Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, remoteFileName); properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); properties.Add(PropertyIds.CreationDate, File.GetCreationTime(syncItem.LocalPath)); properties.Add(PropertyIds.LastModificationDate, File.GetLastWriteTime(syncItem.LocalPath)); // Prepare content stream using (Stream file = File.Open(syncItem.LocalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (SHA1 hashAlg = new SHA1Managed()) using (CryptoStream hashstream = new CryptoStream(file, hashAlg, CryptoStreamMode.Read)) { ContentStream contentStream = new ContentStream(); contentStream.FileName = remoteFileName; contentStream.MimeType = MimeType.GetMIMEType(remoteFileName); contentStream.Length = file.Length; contentStream.Stream = hashstream; Logger.Debug("Uploading: " + syncItem.LocalPath + " as " + remoteFolder.Path + "/" + remoteFileName); remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null); Logger.Debug("Uploaded: " + syncItem.LocalPath); filehash = hashAlg.Hash; } // Get metadata. Some metadata has probably been automatically added by the server. Dictionary<string, string[]> metadata = FetchMetadata(remoteDocument); // Create database entry for this file. database.AddFile(syncItem, remoteDocument.Id, remoteDocument.LastModificationDate, metadata, filehash); Logger.Info("Added file to database: " + syncItem.LocalPath); return true; } catch (Exception e) { ProcessRecoverableException("Could not upload file: " + syncItem.LocalPath, e); return false; } }
public void CreateDocument() { var content = Encoding.UTF8.GetBytes("Test Content!"); var stream = new ContentStream(); stream.FileName = "mycontent.txt"; stream.MimeType = "text/plain"; stream.Stream = new MemoryStream(content); stream.Length = content.Length; var obj = _cmisNav.CreateDocument("__cdDoc", stream); CmisHelper.RegisterTempObject(obj); Assert.That(obj.Paths, Contains.Item("/__cdDoc")); Assert.That(obj.Name, Is.EqualTo("__cdDoc")); Assert.That(obj, CmisHelper.HasContent(content, stream.MimeType)); }
public void SetJPEGContentStream( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); string filename = "testfile.jpg"; Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, filename); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); try { IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument; if (doc != null) { doc.Delete(true); } } catch (CmisObjectNotFoundException) { } IDocument emptyDoc = folder.CreateDocument(properties, null, null); Assert.That(emptyDoc.ContentStreamLength == null || emptyDoc.ContentStreamLength == 0, "returned document shouldn't got any content"); int contentLength = 1024; byte[] content = new byte[contentLength]; using (RandomNumberGenerator random = RandomNumberGenerator.Create()) { random.GetBytes(content); } ContentStream contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = content.Length; using (var memstream = new MemoryStream(content)) { contentStream.Stream = memstream; emptyDoc.SetContentStream(contentStream, true, true); } Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength, "Setting content failed"); IDocument randomDoc = session.GetObjectByPath(emptyDoc.Paths[0]) as IDocument; Assert.That(randomDoc != null); Assert.AreEqual(content.Length, randomDoc.ContentStreamLength, "Getting content on new object failed"); emptyDoc.DeleteAllVersions(); }
public void SetContentStreamTest( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); string filename = "testfile.txt"; Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, filename); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); try { IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument; if (doc != null) { doc.Delete(true); } } catch (CmisObjectNotFoundException) { } IDocument emptyDoc = folder.CreateDocument(properties, null, null); Assert.That(emptyDoc.ContentStreamLength == null || emptyDoc.ContentStreamLength == 0, "returned document shouldn't got any content"); string content = string.Empty; content += "Test "; ContentStream contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = content.Length; using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = memstream; emptyDoc.SetContentStream(contentStream, true, true); } Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength); emptyDoc.DeleteContentStream(true); content += "Test "; contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = content.Length; using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = memstream; emptyDoc.SetContentStream(contentStream, true, true); } Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength); emptyDoc.DeleteContentStream(true); content += "Test "; contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = content.Length; using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = memstream; emptyDoc.SetContentStream(contentStream, true, true); } Assert.AreEqual(content.Length, emptyDoc.ContentStreamLength); emptyDoc.DeleteAllVersions(); }
public IDocument CreateTempDocument(CmisPath path, ContentStream stream, IDictionary<string, object> properties) { var doc = _cmisNav.CreateDocument(path, stream, properties); _createdObjects.Add(doc); return doc; }
public Stream GetStream() { if (this.cachedRequestStream == null) { this.cachedRequestStream = new ContentStream(new MemoryStream(), true /*isKnownMemoryStream*/); } return this.cachedRequestStream.Stream; }
/// <summary> /// Sets the request stream. /// </summary> /// <param name="requestStreamContent">The content stream to copy into the request stream.</param> internal void SetRequestStream(ContentStream requestStreamContent) { if (requestStreamContent.IsKnownMemoryStream) { this.SetContentLengthHeader(); } #if DEBUG this.ValidateHeaders(); #endif using (Stream requestStream = this.requestMessage.GetStream()) { if (requestStreamContent.IsKnownMemoryStream) { MemoryStream bufferableStream = (MemoryStream)requestStreamContent.Stream; Debug.Assert(bufferableStream.Position == 0, "Cached/buffered stream position should be 0"); byte[] buffer = bufferableStream.GetBuffer(); int bufferOffset = checked((int)bufferableStream.Position); int bufferLength = checked((int)bufferableStream.Length) - bufferOffset; // the following is useful in the debugging Immediate Window // string x = System.Text.Encoding.UTF8.GetString(buffer, bufferOffset, bufferLength); requestStream.Write(buffer, bufferOffset, bufferLength); } else { byte[] buffer = new byte[WebUtil.DefaultBufferSizeForStreamCopy]; WebUtil.CopyStream(requestStreamContent.Stream, requestStream, ref buffer); } } }
public static OrganizationAccount GetOrganizationAccountByUserAccountKey(Guid userAccountKey) { OrganizationAccount organizationAccountFound = null; ContentStream contentStreamFound = null; using (var db = new FHNWPrototypeDB()) { organizationAccountFound = db.UserAccounts .Include("OrganizationAccount.Organization") .Include("OrganizationAccount.PartnershipsRequested.Sender.Organization") .Include("OrganizationAccount.PartnershipsRequested.Receiver.Organization") .Include("OrganizationAccount.PartnershipsReceived.Sender.Organization") .Include("OrganizationAccount.PartnershipsReceived.Receiver.Organization") .Include("OrganizationAccount.AllianceMemberships.AllianceRequested") .Include("OrganizationAccount.Employees.OrganizationAccount.Organization") .Include("OrganizationAccount.Employees.User") .Include("OrganizationAccount.Location") .SingleOrDefault(x => x.Key == userAccountKey).OrganizationAccount; contentStreamFound = (from cs in db.ContentStreams .Include("Posts.Author") .Include("Posts.Comments.Author") where cs.Owner.ReferenceKey == organizationAccountFound.Key select cs).FirstOrDefault(); if (organizationAccountFound != null) { if (contentStreamFound != null) { organizationAccountFound.Wall = contentStreamFound; } else { ContentStream emptyWall = new ContentStream(); emptyWall.Posts = new List<Post>(); organizationAccountFound.Wall = emptyWall; } } else { return null; } } return organizationAccountFound; }
public static ContentStream GetContentStreamAsNewsfeed(Guid OwnerKey) { ContentStream newsfeed = new ContentStream(); newsfeed.Posts = new List<Post>(); newsfeed.Tweets = new List<Tweet>(); newsfeed.Retweets = new List<Retweet>(); //used when the viewer is a user account List<Post> postsFromMyEmployer = new List<Post>(); List<Tweet> tweetsFromEmployer = new List<Tweet>(); List<Retweet> retweetsFromEmployer = new List<Retweet>(); List<Post> postsToMe = new List<Post>(); List<Post> postsFromPeersReceived = new List<Post>(); List<Post> postsFromPeersRequested = new List<Post>(); List<Tweet> tweetsToMe = new List<Tweet>(); List<Tweet> tweetsFromPeersReceived = new List<Tweet>(); List<Tweet> tweetsFromPeersRequested = new List<Tweet>(); List<Retweet> retweetsFromMe = new List<Retweet>(); List<Retweet> retweetsFromPeersReceived = new List<Retweet>(); List<Retweet> retweetsFromPeersRequested = new List<Retweet>(); List<Post> allPostsFromNewsfeed = new List<Post>(); List<Tweet> allTweetsFromNewsfeed = new List<Tweet>(); List<Retweet> allRetweetsFromNewsfeed = new List<Retweet>(); using (var db = new FHNWPrototypeDB()) { //db.Configuration.LazyLoadingEnabled = false; newsfeed.Owner = db.BasicProfiles.FirstOrDefault(x => x.ReferenceKey == OwnerKey); if (newsfeed.Owner.ReferenceType == Domain._Base.Accounts.AccountType.UserAccount) { var owner = db.UserAccounts .Include("FriendshipsReceived.Sender") .Include("FriendshipsRequested.Receiver") .FirstOrDefault(x => x.Key == OwnerKey); var employer = db.UserAccounts .Include("OrganizationAccount") .FirstOrDefault(x=> x.Key==owner.Key) .OrganizationAccount.Key; var anyPostsOnMyEmployersWall = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == employer) .Posts .OrderByDescending(y=>y.PublishDateTime) .ToList(); if (anyPostsOnMyEmployersWall != null) postsFromMyEmployer.AddRange(anyPostsOnMyEmployersWall); var anyPostsOnMyWall = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey) .Posts .OrderByDescending(y => y.PublishDateTime) .ToList(); if (anyPostsOnMyWall != null) postsToMe.AddRange(anyPostsOnMyWall); var tweetsOnMyEmployerWall = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == employer) .Tweets.Where(x => x.Author.ReferenceKey == employer) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsOnMyEmployerWall != null) tweetsFromEmployer.AddRange(tweetsOnMyEmployerWall); var tweetsFromMyWall = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey ) .Tweets.Where(x => x.Author.ReferenceKey == OwnerKey ) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsFromMyWall != null) tweetsToMe.AddRange(tweetsFromMyWall); var retweetsFromMyEmployerWall = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == employer) .Retweets.Where(x => x.Author.ReferenceKey == employer) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromMyEmployerWall != null) retweetsFromEmployer.AddRange(retweetsFromMyEmployerWall); var retweetsFromMyWall = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey ) .Retweets.Where(x => x.Author.ReferenceKey == OwnerKey ) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromMyWall != null) retweetsFromMe.AddRange(retweetsFromMyWall); foreach (FriendshipStateInfo friendship in owner.FriendshipsReceived) { // var peerProfile = db.BasicProfiles.SingleOrDefault(x=>x.ReferenceKey==friendship.Sender.Key); var postsFromWallOfReceived= db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Sender.Key) .Posts.Where(x => x.Author.ReferenceKey == friendship.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (postsFromWallOfReceived != null) postsFromPeersReceived.AddRange(postsFromWallOfReceived); var tweetsFromWallOfReceived = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Sender.Key) .Tweets.Where(x => x.Author.ReferenceKey == friendship.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsFromWallOfReceived != null) tweetsFromPeersReceived.AddRange(tweetsFromWallOfReceived); var retweetsFromWallOfReceived = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Sender.Key) .Retweets.Where(x => x.Author.ReferenceKey == friendship.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromWallOfReceived != null) retweetsFromPeersReceived.AddRange(retweetsFromWallOfReceived); } foreach (FriendshipStateInfo friendship in owner.FriendshipsRequested) { // var peerProfile = db.BasicProfiles.SingleOrDefault(x => x.ReferenceKey == friendship.Receiver.Key); var postFromWallRequested = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Receiver.Key) .Posts.Where(x => x.Author.ReferenceKey == friendship.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (postFromWallRequested != null) postsFromPeersRequested.AddRange(postFromWallRequested); var tweetsFromWallRequested = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Receiver.Key) .Tweets.Where(x => x.Author.ReferenceKey == friendship.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsFromWallRequested != null) tweetsFromPeersRequested.AddRange(tweetsFromWallRequested); var retweetsFromWallRequested = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == friendship.Receiver.Key) .Retweets.Where(x => x.Author.ReferenceKey == friendship.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromWallRequested != null) retweetsFromPeersRequested.AddRange(retweetsFromWallRequested); } } if (newsfeed.Owner.ReferenceType == AccountType.OrganizationAccount) { var owner = db.OrganizationAccounts .Include("PartnershipsReceived.Sender") .Include("PartnershipsRequested.Receiver") .FirstOrDefault(x => x.Key == OwnerKey); var postsFromMyWall = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey) .Posts .OrderByDescending(y => y.PublishDateTime) .ToList(); if (postsFromMyWall != null) postsToMe.AddRange(postsFromMyWall); var tweetsFromMyWall = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey) .Tweets .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsFromMyWall != null) tweetsToMe.AddRange(tweetsFromMyWall); var retweetsFromMyWall = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey) .Retweets.Where(x => x.Author.ReferenceKey == OwnerKey) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromMyWall != null) retweetsFromMe.AddRange(retweetsFromMyWall); foreach (PartnershipStateInfo partnership in owner.PartnershipsReceived) { // var peerProfile = db.BasicProfiles.SingleOrDefault(x => x.ReferenceKey == partnership.Sender.Key); var postsfromWallOfReceived = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Sender.Key) .Posts.Where(x => x.Author.ReferenceKey == partnership.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (postsfromWallOfReceived != null) postsFromPeersReceived.AddRange(postsfromWallOfReceived); var tweetsfromWallOfReceived = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Sender.Key) .Tweets.Where(x => x.Author.ReferenceKey == partnership.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsfromWallOfReceived != null) tweetsFromPeersReceived.AddRange(tweetsfromWallOfReceived); var retweetsfromWallOfReceived = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Sender.Key) .Retweets.Where(x => x.Author.ReferenceKey == partnership.Sender.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsfromWallOfReceived != null) retweetsFromPeersReceived.AddRange(retweetsfromWallOfReceived); } foreach (PartnershipStateInfo partnership in owner.PartnershipsRequested) { // var peerProfile = db.BasicProfiles.SingleOrDefault(x => x.ReferenceKey == partnership.Receiver.Key); //var temp = db.ContentStreams // .Include("Owner") // .Include("Posts.Author") // .Include("Posts.PostLikes.Author") // .Include("Posts.Comments.Author") // .Include("Posts.Comments.CommentLikes.Author") // .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Receiver.Key) // .Posts.Where(x => x.Author.ReferenceKey == partnership.Receiver.Key) // .OrderByDescending(y => y.PublishDateTime) // .Take(3).ToList(); //if (temp != null) postsFromPeersRequested.AddRange(temp); var postFromWallRequested = db.ContentStreams .Include("Owner") .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Receiver.Key) .Posts.Where(x => x.Author.ReferenceKey == partnership.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (postFromWallRequested != null) postsFromPeersRequested.AddRange(postFromWallRequested); var tweetsFromWallRequested = db.ContentStreams .Include("Owner") .Include("Tweets.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Receiver.Key) .Tweets.Where(x => x.Author.ReferenceKey == partnership.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (tweetsFromWallRequested != null) tweetsFromPeersRequested.AddRange(tweetsFromWallRequested); var retweetsFromWallRequested = db.ContentStreams .Include("Owner") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == partnership.Receiver.Key) .Retweets.Where(x => x.Author.ReferenceKey == partnership.Receiver.Key) .OrderByDescending(y => y.PublishDateTime) .ToList(); if (retweetsFromWallRequested != null) retweetsFromPeersRequested.AddRange(retweetsFromWallRequested); } } if (postsToMe != null) newsfeed.Posts = newsfeed.Posts.Union(postsToMe).ToList(); if (postsFromMyEmployer != null) newsfeed.Posts = newsfeed.Posts.Union(postsFromMyEmployer).ToList(); if (postsFromPeersReceived != null) newsfeed.Posts= newsfeed.Posts.Union(postsFromPeersReceived).ToList(); if (postsFromPeersRequested != null) newsfeed.Posts = newsfeed.Posts.Union(postsFromPeersRequested).ToList(); newsfeed.Posts = newsfeed.Posts.OrderByDescending(x => x.PublishDateTime).ToList(); if (tweetsToMe != null) newsfeed.Tweets= newsfeed.Tweets.Union(tweetsToMe).ToList(); if (tweetsFromEmployer != null) newsfeed.Tweets = newsfeed.Tweets.Union(tweetsFromEmployer).ToList(); if (tweetsFromPeersReceived != null) newsfeed.Tweets = newsfeed.Tweets.Union(tweetsFromPeersReceived).ToList(); if (tweetsFromPeersRequested != null) newsfeed.Tweets = newsfeed.Tweets.Union(tweetsFromPeersRequested).ToList(); newsfeed.Tweets = newsfeed.Tweets.OrderByDescending(x => x.PublishDateTime).ToList(); if (retweetsFromMe != null) newsfeed.Retweets= newsfeed.Retweets.Union(retweetsFromMe).ToList(); if (retweetsFromEmployer != null) newsfeed.Retweets = newsfeed.Retweets.Union(retweetsFromEmployer).ToList(); if (retweetsFromPeersReceived != null) newsfeed.Retweets = newsfeed.Retweets.Union(retweetsFromPeersReceived).ToList(); if (retweetsFromPeersRequested != null) newsfeed.Retweets = newsfeed.Retweets.Union(retweetsFromPeersRequested).ToList(); newsfeed.Retweets = newsfeed.Retweets.OrderByDescending(x => x.PublishDateTime).ToList(); return newsfeed; } }
private bool UploadStreamInTrunk(string filePath, Stream fileStream, IDocument remoteDocument) { if (repoinfo.ChunkSize <= 0) { return false; } string fileName = remoteDocument.Name; for (long offset = fileStream.Position; offset < fileStream.Length; offset += repoinfo.ChunkSize) { bool isLastTrunk = false; if (offset + repoinfo.ChunkSize >= fileStream.Length) { isLastTrunk = true; } Logger.Debug(String.Format("Uploading next chunk (size={1}) of {0}: {2} of {3} finished({4}%)", fileName, repoinfo.ChunkSize, offset, fileStream.Length, 100 * offset / fileStream.Length)); using (ChunkedStream chunkstream = new ChunkedStream(fileStream, repoinfo.ChunkSize)) { chunkstream.ChunkPosition = offset; ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); contentStream.Length = repoinfo.ChunkSize; if (isLastTrunk) { contentStream.Length = fileStream.Length - offset; } contentStream.Stream = chunkstream; lock (disposeLock) { if (disposed) { throw new ObjectDisposedException("Uploading"); } try { remoteDocument.AppendContentStream(contentStream, isLastTrunk); Logger.Debug("Response of the server: " + offset.ToString()); database.SetFileServerSideModificationDate(filePath, remoteDocument.LastModificationDate); } catch (Exception ex) { Logger.Fatal("Upload failed: " + ex); return false; } } } } return true; }
public IDocument CreateTempDocument(CmisPath path, ContentStream stream) { return CreateTempDocument(path, stream, null); }
public IDocument CreateTempDocument(CmisPath path, string content, string mimeType) { var bytes = Encoding.UTF8.GetBytes(content); var contentStream = new ContentStream(); contentStream.MimeType = mimeType; contentStream.Length = bytes.Length; using (var memoryStream = new MemoryStream(bytes)) { contentStream.Stream = memoryStream; return CreateTempDocument(path, contentStream, null); } }
/** * Upload a single file to the CMIS server. */ private void UploadFile(string filePath, IFolder remoteFolder) { activityListener.ActivityStarted(); IDocument remoteDocument = null; try { // Prepare properties string fileName = Path.GetFileName(filePath); Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, fileName); properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); // Prepare content stream ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); // Should CmisSync try to guess? contentStream.Stream = File.OpenRead(filePath); // Upload remoteDocument = remoteFolder.CreateDocument(properties, contentStream, null); // Create database entry for this file. database.AddFile(filePath, remoteDocument.LastModificationDate, null); } catch (FileNotFoundException e) { SparkleLogger.LogInfo("Sync", "File deleted while trying to upload it, reverting."); // File has been deleted while we were trying to upload/checksum/add. // This can typically happen in Windows when creating a new text file and giving it a name. // Revert the upload. if (remoteDocument != null) { remoteDocument.DeleteAllVersions(); } } activityListener.ActivityStopped(); }
protected ContentStream File(string name) { var stream = new ContentStream(_directory, name, ""); _streams.Add(stream); return stream; }
public void GetContentStreamHash( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { Regex entryRegex = new Regex(@"^\{.+\}[0-9a-fA-F]+$"); ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); string filename = "hashedfile.txt"; try { IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument; if (doc != null) { doc.Delete(true); } } catch (CmisObjectNotFoundException) { } Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, filename); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); using (var oneByteStream = new MemoryStream(new byte[1])) { ContentStream contentStream = new ContentStream(); contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = 1; contentStream.Stream = oneByteStream; var emptyDoc = folder.CreateDocument(properties, contentStream, null); var context = new OperationContext(); IDocument requestedDoc = session.GetObject(emptyDoc, context) as IDocument; foreach (var prop in requestedDoc.Properties) { if (prop.Id == "cmis:contentStreamHash") { Assert.That(prop.IsMultiValued, Is.True); if (prop.Values != null) { foreach (string entry in prop.Values) { Assert.That(entryRegex.IsMatch(entry)); } } } } byte[] remoteHash = requestedDoc.ContentStreamHash(); if (remoteHash != null) { Assert.That(remoteHash, Is.EqualTo(SHA1.Create().ComputeHash(new byte[1]))); } requestedDoc.Delete(true); } }
public IDocument CreateDocument(IFolder folder, string name, string content) { Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, name); properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); ContentStream contentStream = new ContentStream(); contentStream.FileName = name; contentStream.MimeType = MimeType.GetMIMEType(name); contentStream.Length = content.Length; contentStream.Stream = new MemoryStream(Encoding.UTF8.GetBytes(content)); return folder.CreateDocument(properties, contentStream, null); }
public static ContentStream GetContentStreamAsProfileWall(Guid OwnerKey) { // var result = null; using (var db = new FHNWPrototypeDB()) { ContentStream result = db.ContentStreams .Include("Posts.Author") .Include("Posts.PostLikes.Author") .Include("Posts.Comments.Author") .Include("Posts.Comments.CommentLikes.Author") .Include("Tweets.Author") .Include("Retweets.Author") .Include("Retweets.Tweet.Author") .FirstOrDefault(x => x.Owner.ReferenceKey == OwnerKey); if (result == null) { result = new ContentStream(); result.Posts = new List<Post>(); result.Tweets = new List<Tweet>(); result.Retweets = new List<Retweet>(); } else { if (result.Posts == null) result.Posts = new List<Post>(); if (result.Tweets == null) result.Tweets = new List<Tweet>(); if (result.Retweets == null) result.Retweets = new List<Retweet>(); var newPostList = result.Posts.OrderByDescending(x => x.PublishDateTime).Take(3).ToList(); foreach (var post in newPostList) { var newCommentList = post.Comments.OrderBy(x => x.PublishDateTime).ToList(); post.Comments = newCommentList; } result.Posts = newPostList; var newTweetList = result.Tweets.OrderByDescending(x => x.PublishDateTime).Take(3).ToList(); result.Tweets = newTweetList; var newRetweetList = result.Retweets.OrderByDescending(x => x.PublishDateTime).Take(3).ToList(); result.Retweets = newRetweetList; } return result; } }
/** * Upload new version of file content. */ private void UpdateFile(string filePath, IFolder remoteFolder) { activityListener.ActivityStarted(); string fileName = Path.GetFileName(filePath); // Prepare content stream ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); // Should CmisSync try to guess? contentStream.Stream = File.OpenRead(filePath); IDocument document = null; bool found = false; foreach(ICmisObject obj in remoteFolder.GetChildren()) { if (obj is IDocument) { document = (IDocument)obj; if (document.Name == fileName) { found = true; break; } } } // If not found, it means the document has been deleted, will be processed at the next sync cycle. if (!found) { return; } // Send content stream. IObjectId id = document.SetContentStream(contentStream, true, true); // Read new last modification date. // TODO document = (IDocument)id; // null. See DotCMIS 0.4 bug: CMIS-594 // // Update timestamp in database. //database.SetFileServerSideModificationDate(filePath, document.LastModificationDate); activityListener.ActivityStopped(); }
public void WriteThenRead(string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId) { string fileName = "test.txt"; var cmisParameters = new Dictionary<string, string>(); cmisParameters[SessionParameter.BindingType] = BindingType.AtomPub; cmisParameters[SessionParameter.AtomPubUrl] = url; cmisParameters[SessionParameter.User] = user; cmisParameters[SessionParameter.Password] = Crypto.Deobfuscate(password); cmisParameters[SessionParameter.RepositoryId] = repositoryId; SessionFactory factory = SessionFactory.NewInstance(); ISession session = factory.GetRepositories(cmisParameters)[0].CreateSession(); // IFolder root = session.GetRootFolder(); IFolder root = (IFolder)session.GetObjectByPath(remoteFolderPath); Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, fileName); properties.Add(PropertyIds.ObjectTypeId, "cmis:document"); ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); // Should CmisSync try to guess? byte[] bytes = Encoding.UTF8.GetBytes("Hello,world!"); contentStream.Stream = new MemoryStream(bytes); contentStream.Length = bytes.Length; // Create file. DotCMIS.Enums.VersioningState? state = null; if (true != session.RepositoryInfo.Capabilities.IsAllVersionsSearchableSupported) { state = DotCMIS.Enums.VersioningState.None; } session.CreateDocument(properties, root, contentStream, state); // Check whether file is present. IItemEnumerable<ICmisObject> children = root.GetChildren(); bool found = false; foreach (ICmisObject child in children) { string childFileName = (string)child.GetPropertyValue(PropertyIds.Name); Console.WriteLine(childFileName); if (childFileName.Equals(fileName)) { found = true; } } Assert.True(found); // Clean. IDocument doc = (IDocument)session.GetObjectByPath((remoteFolderPath + "/" + fileName).Replace("//","/")); doc.DeleteAllVersions(); }
public IContentStream GetContentStream(string streamId, long? offset, long? length) { IContentStream contentStream = Session.GetContentStream(this, streamId, offset, length); if (contentStream == null) { // no content stream return null; } // the AtomPub binding doesn't return a file name // -> get the file name from properties, if present if (contentStream.FileName == null && ContentStreamFileName != null) { ContentStream newContentStream = new ContentStream(); newContentStream.FileName = ContentStreamFileName; newContentStream.Length = contentStream.Length; newContentStream.MimeType = contentStream.MimeType; newContentStream.Stream = contentStream.Stream; newContentStream.Extensions = contentStream.Extensions; contentStream = newContentStream; } return contentStream; }
/// <summary> /// Uploads the file. /// Resumes an upload if the given localFileStream.Position is larger than zero. /// </summary> /// <returns> /// The new CMIS document. /// </returns> /// <param name='remoteDocument'> /// Remote document where the local content should be uploaded to. /// </param> /// <param name='localFileStream'> /// Local file stream. /// </param> /// <param name='transmission'> /// Transmission status where the uploader should report its uploading status. /// </param> /// <param name='hashAlg'> /// Hash alg which should be used to calculate a checksum over the uploaded content. /// </param> /// <param name='overwrite'> /// If true, the local content will overwrite the existing content. /// </param> /// <param name="update">Is called on every new chunk, if not <c>null</c>.</param> /// <exception cref="CmisSync.Lib.Tasks.UploadFailedException"> /// Contains the last successful remote document state. This is needed for continue a failed upload. /// </exception> public override IDocument UploadFile( IDocument remoteDocument, Stream localFileStream, Transmission transmission, HashAlgorithm hashAlg, bool overwrite = true, UpdateChecksum update = null) { IDocument result = remoteDocument; for (long offset = localFileStream.Position; offset < localFileStream.Length; offset += this.ChunkSize) { bool isFirstChunk = offset == 0; bool isLastChunk = (offset + this.ChunkSize) >= localFileStream.Length; using (var hashstream = new NonClosingHashStream(localFileStream, hashAlg, CryptoStreamMode.Read)) using (var chunkstream = new ChunkedStream(hashstream, this.ChunkSize)) using (var offsetstream = new OffsetStream(chunkstream, offset)) using (var transmissionStream = transmission.CreateStream(offsetstream)) { transmission.Length = localFileStream.Length; transmission.Position = offset; chunkstream.ChunkPosition = offset; ContentStream contentStream = new ContentStream(); contentStream.FileName = remoteDocument.Name; contentStream.MimeType = Cmis.MimeType.GetMIMEType(remoteDocument.Name); if (isLastChunk) { contentStream.Length = localFileStream.Length - offset; } else { contentStream.Length = this.ChunkSize; } contentStream.Stream = transmissionStream; try { if (isFirstChunk && result.ContentStreamId != null && overwrite) { result.DeleteContentStream(true); } result.AppendContentStream(contentStream, isLastChunk, true); HashAlgorithmReuse reuse = hashAlg as HashAlgorithmReuse; if (reuse != null && update != null) { using (HashAlgorithm hash = (HashAlgorithm)reuse.Clone()) { hash.TransformFinalBlock(new byte[0], 0, 0); update(hash.Hash, result.ContentStreamLength.GetValueOrDefault()); } } } catch (Exception e) { if (e is FileTransmission.AbortException) { throw; } if (e.InnerException is FileTransmission.AbortException) { throw e.InnerException; } throw new UploadFailedException(e, result); } } } hashAlg.TransformFinalBlock(new byte[0], 0, 0); return result; }
public void EnsureFileNameStaysEqualWhileUploading( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); string filename = "testfile.txt"; Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add(PropertyIds.Name, filename); properties.Add(PropertyIds.ObjectTypeId, BaseTypeId.CmisDocument.GetCmisValue()); try { IDocument doc = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + filename) as IDocument; if (doc != null) { doc.Delete(true); } } catch (CmisObjectNotFoundException) { } IDocument emptyDoc = folder.CreateDocument(properties, null, null); int length = 1024 * 1024; byte[] content = new byte[length]; ContentStream contentStream = new ContentStream(); contentStream.FileName = filename; contentStream.MimeType = MimeType.GetMIMEType(filename); contentStream.Length = content.Length; Action assert = delegate { Assert.That((session.GetObject(emptyDoc.Id, OperationContextFactory.CreateNonCachingPathIncludingContext(session)) as IDocument).Name, Is.EqualTo(filename)); }; using (var memstream = new AssertingStream(new MemoryStream(content), assert)) { contentStream.Stream = memstream; emptyDoc.SetContentStream(contentStream, true, true); } }
public void CheckinTest( string canonical_name, string localPath, string remoteFolderPath, string url, string user, string password, string repositoryId, string binding) { string subFolderName = "subFolder"; string fileName = "testFile.bin"; string subFolderPath = remoteFolderPath.TrimEnd('/') + "/" + subFolderName; string filePath = subFolderPath + "/" + fileName; ISession session = DotCMISSessionTests.CreateSession(user, password, url, repositoryId, binding); if (!session.ArePrivateWorkingCopySupported()) { Assert.Ignore("PWCs are not supported"); } try { IFolder dir = session.GetObjectByPath(remoteFolderPath.TrimEnd('/') + "/" + subFolderName) as IFolder; if (dir != null) { dir.DeleteTree(true, null, true); } } catch (CmisObjectNotFoundException) { } IFolder folder = (IFolder)session.GetObjectByPath(remoteFolderPath); IFolder subFolder = folder.CreateFolder(subFolderName); string content = "testContent"; IDocument doc = subFolder.CreateDocument(fileName, "testContent", checkedOut: true); IObjectId checkoutId = doc.CheckOut(); IDocument docCheckout = session.GetObject(checkoutId) as IDocument; Assert.AreEqual(doc.ContentStreamLength, docCheckout.ContentStreamLength); ContentStream contentStream = new ContentStream(); contentStream.FileName = fileName; contentStream.MimeType = MimeType.GetMIMEType(fileName); contentStream.Length = content.Length; for (int i = 0; i < 10; ++i) { using (var memstream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { contentStream.Stream = memstream; docCheckout.AppendContentStream(contentStream, i == 9); } Assert.That(docCheckout.ContentStreamLength, Is.EqualTo(content.Length * (i + 2))); } IObjectId checkinId = docCheckout.CheckIn(true, null, null, "checkin"); IDocument docCheckin = session.GetObject(checkinId) as IDocument; docCheckin.Refresh(); // refresh is required, or DotCMIS will re-use the cached properties if checinId is the same as doc.Id Assert.That(docCheckin.ContentStreamLength, Is.EqualTo(content.Length * (9 + 2))); }