Beispiel #1
0
        /**
         * Sets the Thumbnail for the document, replacing any existing
         *  one.
         *
         * @param name The filename for the thumbnail image, eg <code>thumbnail.jpg</code>
         * @param imageData The inputstream to read the thumbnail image from
         */
        public void SetThumbnail(String filename, Stream imageData)
        {
            PackagePart tPart = ThumbnailPart;

            if (tPart == null)
            {
                // New thumbnail
                pkg.AddThumbnail(filename, imageData);
            }
            else
            {
                // Change existing
                String newType = ContentTypes.GetContentTypeFromFileExtension(filename);
                if (!newType.Equals(tPart.ContentType))
                {
                    throw new ArgumentException("Can't set a Thumbnail of type " +
                                                newType + " when existing one is of a different type " +
                                                tPart.ContentType);
                }
                StreamHelper.CopyStream(imageData, tPart.GetOutputStream());
            }
        }
        private static void PrepareRequestContentStream(IEnumerable <string> files, IEnumerable <KeyValuePair <string, string> > formFields, string boundary, MemoryStream requestContentStream)
        {
            var boundarybytes    = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            var endBoundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");

            var formdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";

            if (formFields != null)
            {
                var formFieldData = Encoding.UTF8.GetBytes(string.Join(string.Empty, formFields.Select(kvp => string.Format(CultureInfo.InvariantCulture, formdataTemplate, kvp.Key, kvp.Value))));
                requestContentStream.Write(formFieldData, 0, formFieldData.Length);
            }

            foreach (var file in files)
            {
                requestContentStream.Write(boundarybytes, 0, boundarybytes.Length);

                var headerTemplate = "Content-Disposition: form-data; name=\"fname\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";

                var header      = string.Format(CultureInfo.InvariantCulture, headerTemplate, file, ContentTypes.GetContentTypeFromFileExtension(Path.GetExtension(file)));
                var headerbytes = Encoding.UTF8.GetBytes(header);
                requestContentStream.Write(headerbytes, 0, headerbytes.Length);

                var fileBytes = File.ReadAllBytes(file);
                requestContentStream.Write(fileBytes, 0, fileBytes.Length);
            }

            requestContentStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        }
        private static TResponse SendFileUploadRequest <TResponse>(string path, string query, FileInfo[] files)
        {
            var blogApplicationController = CreateController();
            var request = blogApplicationController.ControllerContext.HttpContext.Request;

            request.Path        = new PathString($"/{nameof(BlogApplicationController).Replace("Controller", string.Empty)}{path}");
            request.QueryString = new QueryString($"{query}");

            var boundary = $"{Guid.NewGuid()}";

            request.ContentType = $"multipart/form-data; boundary={boundary}";

            var requestBodyStream = new MemoryStream();

            for (int fileIndex = 0; fileIndex < files.Length; fileIndex++)
            {
                var seperatorBytes = Encoding.ASCII.GetBytes($"{(fileIndex == 0 ? string.Empty : Environment.NewLine)}--{boundary}{Environment.NewLine}Content-Disposition: form-data; name=\"filename\"; filename=\"{Path.GetFileName(files[fileIndex].FullName)}\"{Environment.NewLine}Content-Type: {ContentTypes.GetContentTypeFromFileExtension(files[fileIndex].Extension)}{Environment.NewLine}{Environment.NewLine}");
                requestBodyStream.Write(seperatorBytes);
                requestBodyStream.Write(File.ReadAllBytes(files[fileIndex].FullName));
            }

            requestBodyStream.Write(Encoding.ASCII.GetBytes($"{Environment.NewLine}--{boundary}--"));

            requestBodyStream.Position = 0;
            request.ContentLength      = requestBodyStream.Length;
            request.Body = requestBodyStream;

            return((TResponse)blogApplicationController.ReceiveRequest());
        }
        private void ProcessFile(FileInfo file, Guid projectId, string comboxPath)
        {
            CLLogger.LogVerbose(string.Format("The file '{0}' --> '{2}' will be associated to project '{1}'", file.FullName.Substring(_rootFolder.Length), Cache.GetProjectName(projectId), comboxPath));
            totalSize += (file.Length * 1d) / 1024 / 1024;

            var  cleanPath = comboxPath.TrimEnd('\\').Split('\\');
            Guid?folderId  = null;

            using (var context = FactoryDbContext.Create())
            {
                for (var i = 0; i < cleanPath.Length; i++)
                {
                    var currentFolder    = CleanStringForWeb(cleanPath[i]);
                    var existingFolderId = context.EntityFolders.Where(x => x.ReferenceId == projectId && x.ParentId == folderId && x.Name == currentFolder).Select(x => x.Id).FirstOrDefault();

                    if (existingFolderId == Guid.Empty)
                    {
                        var folder = EntityFolder.New();
                        folder.CurrentUserId = Constants.User.Admin;
                        folder.Id            = Guid.NewGuid();
                        folder.EntityId      = Constants.EntityType.Project;
                        folder.ReferenceId   = projectId;
                        folder.ParentId      = folderId;
                        folder.Name          = currentFolder;
                        folder.Save();

                        folderId = folder.Id;
                    }
                    else
                    {
                        folderId = existingFolderId;
                    }
                }
            }

            var document = Document.New();

            document.ReferenceId     = projectId;
            document.EntityId        = Constants.EntityType.Project;
            document.CurrentUserId   = Constants.User.Admin;
            document.CreatedOn       = DateTime.Now;
            document.LastUpdatedOn   = DateTime.Now;
            document.CreatedById     = Constants.User.Admin;
            document.LastUpdatedById = Constants.User.Admin;
            document.Id              = Guid.NewGuid();
            document.FolderId        = folderId;
            document.DocumentTypeId  = LookupServices.GetLookupItemIdFromTag("LST_DOCUMENT_TYPE_NOT_CLASSIFIED");
            document.Filename        = CleanStringForWeb(file.Name).Replace("..", ".");
            document.FileExtension   = file.Extension;
            document.FileContentType = ContentTypes.GetContentTypeFromFileExtension(document.FileExtension);

            try
            {
                using (var stream = file.OpenRead())
                {
                    document.Insert <JMSL.Framework.DAL.Entities.Document, Document>(DocumentManagerProvider.Get(),
                                                                                     new TransferDocument()
                    {
                        FileName       = document.Filename,
                        FileLength     = file.Length,
                        FileByteStream = stream
                    });
                }
            }
            catch (Exception ex)
            {
                CLLogger.LogError(ex);
            }
        }