Пример #1
0
		/// <summary>
		/// 
		/// </summary>
		public void Emit()
		{
			var data = new byte[_end - _idx];
			var delt = _idx;
			for (var i = _idx; i < _end; i++)
			{
				data[i - delt] = _buffer[i];
			}
			if (_currentType == "")
			{
				_result.Form[_currentName] = _encoding.GetString(data, 0, (int)data.Length);
			}
			else
			{
				var postFile = new PostFile
					{
						Content = data,
						ContentType = _currentType,
						FileName = _currentFileName,
						Name = _currentName
					};
				_result.Files[_currentName] = postFile;
			}
			_currentName = "";
			_currentType = "";
			_currentFileName = "";
		}
Пример #2
0
        public async Task <PostFile> MakeAsync(CreatePostFileDto model)
        {
            model.CheckArgumentIsNull();
            if (model.FileId.HasValue)
            {
                var referencedFile = await _fileRepository.FindAsync(model.FileId.Value);

                referencedFile.CheckReferenceIsNull();
                var postFile = new PostFile {
                    CreateDate     = _dateService.UtcNow(),
                    CreatorUserId  = _userContext.UserId,
                    FileId         = referencedFile.Id,
                    File           = referencedFile,
                    ModifierUserId = _userContext.UserId,
                    ModifyDate     = _dateService.UtcNow(),
                    OrderNum       = model.OrderNum,
                    PostId         = model.PostId
                };
                return(await Task.FromResult(postFile));
            }

            return(new PostFile());
            //var file = new File {
            //    CreateDate = _dateService.UtcNow(),
            //    CreatorUserId = _userContext.UserId,

            //};
        }
Пример #3
0
 private PostFile ParseFile(JsonObject data, string board)
 {
     if (data["filename"] != null)
     {
         PostFile pf = new PostFile();
         pf.filename      = HttpUtility.HtmlDecode(data["filename"].ToString());
         pf.ext           = data["ext"].ToString().Substring(1);
         pf.height        = Convert.ToInt32(data["h"]);
         pf.width         = Convert.ToInt32(data["w"]);
         pf.thumbW        = Convert.ToInt32(data["tn_w"]);
         pf.thumbH        = Convert.ToInt32(data["tn_h"]);
         pf.thumbnail_tim = data["tim"].ToString();
         pf.board         = board;
         pf.hash          = data["md5"].ToString();
         pf.size          = Convert.ToInt32(data["fsize"]);
         if (data["spoiler"] != null)
         {
             pf.IsSpoiler = Convert.ToInt32(data["spoiler"]) == 1;
         }
         return(pf);
     }
     else
     {
         return(null);
     }
 }
        public JsonResult DeleteFile(string fileId)
        {
            if (String.IsNullOrEmpty(fileId))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new { Result = "Error" }));
            }
            try
            {
                Guid     guid       = new Guid(fileId);
                PostFile fileDetail = db.PostFiles.Find(guid);
                if (fileDetail == null)
                {
                    Response.StatusCode = (int)HttpStatusCode.NotFound;
                    return(Json(new { Result = "Error" }));
                }

                //Remove from database
                db.PostFiles.Remove(fileDetail);
                db.SaveChanges();

                //Delete file from the file system
                var path = Path.Combine(Server.MapPath("~/upload/bulltin/dnemeeting"), fileDetail.FileId + fileDetail.Extension);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                return(Json(new { Result = "OK" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Result = "ERROR", Message = ex.Message }));
            }
        }
Пример #5
0
        public async Task <ActionResult> SendPost(int topic, string message, HttpPostedFileBase file)
        {
            if (Request.Cookies["user"] != null)
            {
                var    db    = new ForumEntity();
                string email = Request.Cookies["user"].Value;

                var user = await db.Users.Where(u => u.user_email == email)
                           .FirstOrDefaultAsync();

                if (user != null)
                {
                    var post = new Post
                    {
                        post_content = message,
                        post_date    = DateTime.Now,
                        post_topic   = topic,
                        post_by      = user.Id
                    };

                    db.Posts.Add(post);
                    var th = await db.Topics.Where(t => t.topic_id == topic)
                             .FirstOrDefaultAsync();

                    var len = await db.Posts.Where(m => m.post_topic == topic).CountAsync();

                    if (th.status != 3 && len == 1)
                    {
                        th.status = 2;
                    }
                    await db.SaveChangesAsync();

                    var self = await db.Posts.Where(m => m.post_content == message)
                               .FirstOrDefaultAsync();

                    if (file != null)
                    {
                        var ms = new MemoryStream();
                        await file.InputStream.CopyToAsync(ms);

                        var data = new PostFile
                        {
                            file_name    = file.FileName,
                            file_content = ms.ToArray(),
                            file_type    = file.ContentType,
                            ref_id       = self.post_id
                        };

                        db.PostFiles.Add(data);
                        await db.SaveChangesAsync();

                        return(new HttpStatusCodeResult(HttpStatusCode.Created));
                    }
                }

                return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "You must to login!"));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Something is wrong!"));
        }
Пример #6
0
        public async Task <UserPostReadDto> CreatePostAsync(Guid userId, UserPostCreateDto post)
        {
            var contentType      = post.File.FileName.GetContentType();
            var type             = contentType.Substring(0, 5);
            var extension        = contentType.Substring(6);
            var fileNewNameGuid  = Guid.NewGuid().ToString();
            var fileNewName      = fileNewNameGuid + '.' + extension;
            var thumbnailNewName = Guid.NewGuid().ToString() + ".jpeg";

            if (type == "image")
            {
                var thumbnail = _fileOptimizationService.CreateImageThumbnail(post.File);
                await _imageBlobService.UploadFileBlobAsync(post.File, fileNewName);

                await _imageBlobService.UploadFileBlobAsync(thumbnail, thumbnailNewName);
            }
            else if (type == "video")
            {
                var thumbnail = await _fileOptimizationService.CreateVideoThumbnailAsync(post.File, thumbnailNewName);

                await _videoBlobService.UploadFileBlobAsync(post.File, fileNewName);

                await _imageBlobService.UploadFileBlobAsync(thumbnail, thumbnailNewName);
            }

            var postFileModel = new PostFile(fileNewName, type, thumbnailNewName);
            var userPostModel = new UserPost(userId, post.Caption, postFileModel.Id);
            await _userPostRepository.CreatePostAsync(userPostModel, postFileModel);

            return(await _userPostRepository.GetPostByIdAsync(userPostModel.Id));
        }
Пример #7
0
        /// <summary>
        /// Create the store file to upload
        /// </summary>
        /// <param name="fileData">PostFile CSV File to parse</param>
        /// <param name="storeName">Store name</param>
        /// <returns>PostFile of the Store File to upload to Twofish</returns>
        private PostFile CreateStoreUpload(PostFile fileData, string storeName)
        {
            int[] fieldColumn = FindColunmsNumberForFields(fileData, "StoreName,OfferTitle,OfferDescription,Description,ApplicationName,EndDate");

            Dictionary <int, int> skipList = new Dictionary <int, int>();

            Dictionary <int, string> includeList = new Dictionary <int, string>();

            includeList.Add(GetIntFromIntArray(fieldColumn, 0), storeName);

            Dictionary <int, int> subList = new Dictionary <int, int>();
            // subList.Add(GetIntFromIntArray(fieldColumn, 1), GetIntFromIntArray(fieldColumn, 3));  // OfferTitle   Description
            //subList.Add(GetIntFromIntArray(fieldColumn, 2), GetIntFromIntArray(fieldColumn, 3));  //OfferDescription  Description

            Dictionary <int, string> formatList = new Dictionary <int, string>();

            formatList.Add(GetIntFromIntArray(fieldColumn, 5), "DATE");

            string headerToFind = "StoreName,AppName,StoreDescription,CurrencyName,ItemName,ItemPrice,OfferTitle,OfferDescription,TradeInItemNames,EndDate";
            string headerToUse  = "StoreName,ApplicationName,StoreDescription,CurrencyName,ItemName,ItemPrice,OfferTitle,OfferDescription,TradeInItemNames,EndDate";

            //If ApplicationName name found in the header than use headerToUse as the find header.
            if (GetIntFromIntArray(fieldColumn, 4) > 0)
            {
                headerToFind = headerToUse;
            }

            return(CreateUploadFile(fileData, "!TF createStore,,", headerToFind, headerToUse, includeList, subList, skipList, formatList));
        }
Пример #8
0
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {
                post.UserID       = Convert.ToInt32(Session["LoginID"].ToString());
                post.PriorityID   = 1;
                post.RegisterDate = DateTime.Now;

                List <PostFile> postFiles = new List <PostFile>();
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var file = Request.Files[i];
                    if (file != null && file.ContentLength > 0)
                    {
                        var      fileName   = Path.GetFileName(file.FileName);
                        PostFile uploadFile = new PostFile()
                        {
                            FileName  = fileName,
                            Extension = Path.GetExtension(fileName)
                        };
                        postFiles.Add(uploadFile);

                        var path = Path.Combine(Server.MapPath("~/UploadFiles/") + uploadFile.FileName);
                        file.SaveAs(path);
                    }
                }

                post.PostFile = postFiles;
                db.Posts.Add(post);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(post));
        }
Пример #9
0
        public ActionResult PostFileDownload(Guid?id)
        {
            try
            {
                PostFile doc = db_Forum.GetPostFile_ByID(id.ConvertOrDefault <Guid>());
                var      cd  = new System.Net.Mime.ContentDisposition
                {
                    FileName = doc.Filename,
                    Inline   = false
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
                if (doc.FileContent != null)
                {
                    return(File(doc.FileContent, doc.FileContentType ?? "application/octet-stream"));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            TempData["Error"] = "Unable to download document.";
            return(RedirectToAction("Index", "Forum"));
        }
Пример #10
0
        public async Task <PostFile> MakeAsync(File file,
                                               string title,
                                               int?postId        = null,
                                               int?relatedFileId = null,
                                               int orderNum      = 1)
        {
            file.CheckArgumentIsNull(nameof(file));

            var result = new PostFile {
                CreateDate     = _dateService.UtcNow(),
                CreatorUserId  = _userContext.UserId,
                File           = file,
                FileId         = file.Id,
                ModifierUserId = _userContext.UserId,
                ModifyDate     = _dateService.UtcNow(),
                OrderNum       = orderNum,
                Title          = title.ApplyCorrectYeKe()
            };

            if (postId.HasValue)
            {
                result.PostId = postId.Value;
            }

            if (relatedFileId.HasValue)
            {
                result.RelatedFileId = relatedFileId;
            }

            return(await Task.FromResult(result));
        }
Пример #11
0
        public ActionResult PostFileDelete(Guid?id)
        {
            PostFile doc = db_Forum.GetPostFile_ByID(id.ConvertOrDefault <Guid>());

            if (doc != null)
            {
                int UserIDX = db_Accounts.GetUserIDX();

                //permission check
                if (UserIDX == doc.MembershipUser_Id || User.IsInRole("Admins"))
                {
                    int SuccID = db_Forum.DeletePostFile(id.ConvertOrDefault <Guid>());
                    if (SuccID > 0)
                    {
                        //get the topic from post
                        Post _post = db_Forum.GetPost_ByID(doc.Post_Id.ConvertOrDefault <Guid>());

                        TempData["Success"] = "File removed.";
                        return(RedirectToAction("ShowTopic", "Forum", new { id = _post.Topic_Id }));
                    }
                }
            }


            TempData["Error"] = "Unable to delete document.";
            return(RedirectToAction("Index", "Forum"));
        }
Пример #12
0
        public async Task CreatePostAsync(UserPost post, PostFile postFileModel)
        {
            await _context.Posts.AddAsync(post);

            await _context.PostFiles.AddAsync(postFileModel);

            await _context.SaveChangesAsync();
        }
Пример #13
0
 public ActionResult FileUpload(int id, HttpPostedFileBase uploadedFile)
 {
     if (Request.Files.Count > 0)
     {
         PostFile action = new PostFile(_db, id, Requester(), uploadedFile, Server.MapPath("~/Files/"));
         action.Execute();
     }
     return(RedirectToAction("Files", new { id }));
 }
Пример #14
0
        private void CreatePosts(Blog blog, IReadOnlyList <Channel> userChannels, IReadOnlyList <Queue> userQueues)
        {
            for (var postIndex = 0; postIndex < NotesPerChannel; postIndex++)
            {
                var post = PostTests.UniqueNote(Random);
                post.Channel   = userChannels[postIndex % userChannels.Count];
                post.ChannelId = userChannels[postIndex % userChannels.Count].Id;
                post.Queue     = userQueues[postIndex % userQueues.Count];
                post.QueueId   = userQueues[postIndex % userQueues.Count].Id;
                this.posts.Add(post);
            }

            for (var postIndex = 0; postIndex < ImagesPerCollection; postIndex++)
            {
                var post = PostTests.UniqueFileOrImage(Random);
                post.Channel   = userChannels[postIndex % userChannels.Count];
                post.ChannelId = userChannels[postIndex % userChannels.Count].Id;
                post.Queue     = userQueues[postIndex % userQueues.Count];
                post.QueueId   = userQueues[postIndex % userQueues.Count].Id;

                var file = FileTests.UniqueEntity(Random);
                file.UserId         = blog.Creator.Id;
                post.PreviewImage   = file;
                post.PreviewImageId = file.Id;

                var postFile = new PostFile(post.Id, post, file.Id, file);

                this.posts.Add(post);
                this.files.Add(file);
                this.postFiles.Add(postFile);
            }

            for (var postIndex = 0; postIndex < FilesPerCollection; postIndex++)
            {
                var post = PostTests.UniqueFileOrImage(Random);
                post.Channel   = userChannels[postIndex % userChannels.Count];
                post.ChannelId = userChannels[postIndex % userChannels.Count].Id;
                post.Queue     = userQueues[postIndex % userQueues.Count];
                post.QueueId   = userQueues[postIndex % userQueues.Count].Id;

                var file = FileTests.UniqueEntity(Random);
                file.UserId = blog.Creator.Id;

                var postFile = new PostFile(post.Id, post, file.Id, file);

                this.posts.Add(post);
                this.files.Add(file);
                this.postFiles.Add(postFile);
            }

            this.comments.Add(new Comment(Guid.NewGuid(), this.posts.Last().Id, null, this.users.First().Id, null, "Test comment", DateTime.UtcNow));
            this.likes.Add(new Like(this.posts.Last().Id, null, this.users.First().Id, null, DateTime.UtcNow));
            this.freePosts.Add(new FreePost(this.users.First().Id, this.posts.Last().Id, null, DateTime.UtcNow));
        }
Пример #15
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one post file based on id
    /// </summary>
    /// <param name="id">The id for the post file</param>
    /// <returns>A reference to a post file</returns>
    public static PostFile GetOneById(Int32 id)
    {
        // Create the post to return
        PostFile post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.posts_files WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new PostFile(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Пример #16
0
        public static FileViewModel From(PostFile from)
        {
            if (from == null)
            {
                return(null);
            }

            return(new FileViewModel
            {
                Filename = from.Filename
            });
        }
Пример #17
0
        /// <summary>
        /// Implements call to Twofish method CreateCatalog
        /// </summary>
        /// <param name="itemsInfo">IPAddress</param>
        /// <param name="fileData">Twofish catalog csv file</param>
        /// <param name="commmonKeyValue">Twofish REST service common values</param>
        /// <param name="baseAddress">Twofish REST service base address</param>
        /// <returns>Twofish CreateCatalog XML response document</returns>
        public XmlDocument CreateCatalog(ItemsInfo itemsInfo, PostFile fileData, CommmonKeyValues commmonKeyValue, BaseAddress baseAddress)
        {
            ServiceHandler rest = new ServiceHandler(baseAddress.BaseAddressValue);

            Dictionary <string, string> keyValues = commmonKeyValue.GetCommmonInfo(true);

            keyValues.Add("ipAddress", itemsInfo.IPAddress);

            DebugLog("CreateCatalog", keyValues);

            return(rest.MultiPartFormXMLPost("catalog", keyValues, fileData.FileData));
        }
Пример #18
0
        public static void HttpMultipart(HttpWebRequest request, Hashtable data, Hashtable files)
        {
            // We have files, so use the more complex multipart encoding.
            string boundary = string.Format("--{0}",
                                            DateTime.Now.Ticks.ToString("x"));

            request.ContentType = string.Format("multipart/form-data; boundary={0}",
                                                boundary);
            ArrayList items = new ArrayList();
            // Determine the amount of data we will be sending
            long length = 0;

            foreach (string key in data.Keys)
            {
                PostItem item = new PostItem(key, data[key].ToString(), boundary);
                items.Add(item);
                length += item.Length;
            }
            foreach (string key in files.Keys)
            {
                PostFile file = new PostFile(key, (FileInfo)files[key], boundary);
                items.Add(file);
                length += file.Length;
            }
            length += boundary.Length + 8;
            request.ContentLength = length;
            // Now stream the data.
            //using (Stream requestStream = File.Create("c:\\Users\\bneely\\documents\\debug.txt"))
            using (Stream requestStream = request.GetRequestStream())
            {
                foreach (PostItem item in items)
                {
                    requestStream.Write(item.Header, 0, item.Header.Length);
                    if (item.GetType() == typeof(PostFile))
                    {
                        FileStream fileData = ((PostFile)item).OpenRead();
                        byte[]     buffer   = new byte[32768];
                        int        read     = 0;
                        while ((read = fileData.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            requestStream.Write(buffer, 0, read);
                        }
                    }
                    else
                    {
                        byte[] itemData = UTF8Encoding.UTF8.GetBytes(item.Data);
                        requestStream.Write(itemData, 0, itemData.Length);
                    }
                    byte[] end = UTF8Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));
                    requestStream.Write(end, 0, end.Length);
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Implements call to Twofish method StoreBulkLoad
        /// Loads a store catalog
        /// </summary>
        /// <param name="storeInfo">IpAddress</param>
        /// <param name="fileData">Twofish store csv file</param>
        /// <param name="commmonKeyValue">Twofish REST service common values</param>
        /// <param name="baseAddress">Twofish REST service base address</param>
        /// <returns>Twofish store bulk load XML response document</returns>
        public XmlDocument StoreBulkLoad(StoreInfo storeInfo, PostFile fileData, CommmonKeyValues commmonKeyValue, BaseAddress baseAddress)
        {
            ServiceHandler rest = new ServiceHandler(baseAddress.BaseAddressValue);

            Dictionary <string, string> keyValues = commmonKeyValue.GetCommmonInfo(false);

            keyValues.Add("ipAddress", storeInfo.IpAddress);
            keyValues.Add("submit", "User Bulk Load (pretty format)");
            DebugLog("StoreBulkLoad", keyValues);

            return(rest.MultiPartFormXMLPost("store/bulk", keyValues, fileData.FileData));
        }
Пример #20
0
        public FileScan FileScan(string sourceFilePath)
        {
            using (FileStream fs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
            {
                PostFile postFile = new PostFile();
                postFile.FileBytes = new byte[fs.Length];
                fs.Read(postFile.FileBytes, 0, postFile.FileBytes.Length);

                postFile.FileName = Path.GetFileName(sourceFilePath);

                return(FileAPI.FileScan(postFile));
            }
        }
Пример #21
0
        /// <summary>
        /// Creates the UploadFile returning a PostFile
        /// </summary>
        /// <param name="fileData">PostFile CSV input file</param>
        /// <param name="createLine">A string containg the first line in the TwoFish upload file</param>
        /// <param name="headerToFind">The header to find, name of source file fields in the order of fields to use</param>
        /// <param name="headerToUse">The header to use for the output file matched up field for field with the headerToFind</param>
        /// <param name="includeList">Required list data value index array. If the data value does not match, then skip this line.</param>
        /// <param name="subList">Substitution field index array. If the filed is blank, then use the substitution field for the data.</param>
        /// <param name="skipList">Required field index array. If the field is blank, then skip this line.</param>
        /// <param name="formatList">Format List index array.  If the field is found then format using the provided format type</param>
        /// <returns>PostFile containing the upload CSV file</returns>
        private PostFile CreateUploadFile(PostFile fileData, string createLine, string headerToFind, string headerToUse, Dictionary <int, string> includeList, Dictionary <int, int> subList, Dictionary <int, int> skipList, Dictionary <int, string> formatList)
        {
            PostFile     postFile = new PostFile();
            UTF8Encoding encoding = new UTF8Encoding();

            string outputString = CreateUpload(fileData, createLine, headerToFind, headerToUse, includeList, subList, skipList, formatList);

            Byte[] byteArray = encoding.GetBytes(outputString);

            postFile.FileData.Write(byteArray, 0, byteArray.Length);

            return(postFile);
        }
Пример #22
0
 public static PostFileDto ToDto(this PostFile source)
 {
     return(new PostFileDto
     {
         CountDownload = source.CountDownload,
         FileName = source.FileName,
         Id = source.Id,
         Length = source.Length,
         Title = source.Title,
         Type = source.Type,
         PostId = source.PostId
     });
 }
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {
                #region 檔案上傳資料庫更新及實體檔案存檔
                List <PostFile> fileDetails = new List <PostFile>();
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var file = Request.Files[i];
                    if (file != null && file.ContentLength > 0)
                    {
                        var      fileName   = Path.GetFileName(file.FileName);
                        PostFile fileDetail = new PostFile()
                        {
                            FileName  = fileName,
                            Extension = Path.GetExtension(fileName),
                            FileId    = Guid.NewGuid()
                        };

                        fileDetails.Add(fileDetail);

                        var path = Path.Combine(Server.MapPath("~/upload/bulltin/post"),
                                                fileDetail.FileId + fileDetail.Extension);

                        file.SaveAs(path);
                    }



                    post.PostFiles = fileDetails;

                    //post.CreatedBy=
                }
                #endregion

                var user = UserManager.FindByName(User.Identity.Name);
                post.PostDate         = DateTime.Now.ToString("yyyy/MM/dd");
                post.PostId           = Guid.NewGuid();
                post.CreatedBy        = user.FullName;
                post.LastModifiedDate = DateTime.Now.ToString("yyyy/MM/dd");
                post.ModifiedBy       = user.FullName;
                post.IsDeleted        = false;
                db.Posts.Add(post);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(post));
        }
Пример #24
0
        public static PostFile ConvertToPostFile(FileInfoDTO fileDTO)
        {
            var postFile = new PostFile
            {
                File = new FileInfo
                {
                    Id          = fileDTO.Id,
                    Name        = fileDTO.Name,
                    ContentType = fileDTO.ContentType,
                    SizeKB      = fileDTO.SizeKB
                }
            };

            return(postFile);
        }
        } // End of the DeleteAllFiles method

        /// <summary>
        /// Delete all the files for the language and the post
        /// </summary>
        /// <param name="postId">The post id</param>
        /// <param name="languageId">The language id</param>
        private void DeleteLanguageFiles(Int32 postId, Int32 languageId)
        {
            // Define the directory url for product images
            string postDirectory = Server.MapPath("/Content/posts/" + (postId / 100).ToString() + "/" + postId.ToString() + "/" + languageId.ToString());

            // Delete post files
            PostFile.DeleteOnPostId(postId, languageId);

            // Delete the directory if it exists
            if (System.IO.Directory.Exists(postDirectory))
            {
                System.IO.Directory.Delete(postDirectory, true);
            }

        } // End of the DeleteLanguageFiles method
Пример #26
0
        public ActionResult Edit(Post post, HttpPostedFileBase[] Uploads)
        {
            if (ModelState.IsValid)
            {
                var model = postService.Find(post.Id);
                if (Uploads != null && Uploads.Length >= 1)
                {
                    model.PostFiles.Clear();
                    foreach (var item in Uploads)
                    {
                        if (item != null && item.ContentLength > 0)
                        {
                            var fileName  = Path.GetFileName(item.FileName);
                            var extension = Path.GetExtension(fileName).ToLower();
                            if (extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".pdf" || extension == ".doc" || extension == ".docx")
                            {
                                var path = Path.Combine(ConfigurationManager.AppSettings["uploadPath"], fileName);
                                item.SaveAs(path);
                                var file = new PostFile();
                                file.Id        = Guid.NewGuid();
                                file.FileName  = fileName;
                                file.CreatedAt = DateTime.Now;
                                file.CreatedBy = User.Identity.Name;
                                file.UpdatedAt = DateTime.Now;
                                file.UpdatedBy = User.Identity.Name;
                                file.PostId    = post.Id;
                                postFileService.Insert(file);
                            }
                        }
                    }
                }



                model.Title = post.Title;

                model.Description = post.Description;


                model.Photo      = post.Photo;
                model.CategoryId = post.CategoryId;
                postService.Update(model);

                return(RedirectToAction("Index"));
            }
            ViewBag.CategoryId = new SelectList(categoryService.GetAll(), "Id", "Name", post.CategoryId);
            return(View(post));
        }
        public ActionResult Edit([Bind(Include = "PostId, Title, Content, Section, Category")] Post post)
        {
            var entry = db.Posts.Find(post.PostId);

            if (entry == null)
            {
                return(HttpNotFound());
            }

            if (ModelState.IsValid)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var file = Request.Files[i];
                    if (file != null && file.ContentLength > 0)
                    {
                        var      fileName   = Path.GetFileName(file.FileName);
                        PostFile fileDetail = new PostFile()
                        {
                            FileName  = fileName,
                            Extension = Path.GetExtension(fileName),
                            FileId    = Guid.NewGuid(),
                            PostId    = entry.PostId
                        };

                        var path = Path.Combine(Server.MapPath("~/upload/bulltin/post"),
                                                fileDetail.FileId + fileDetail.Extension);
                        file.SaveAs(path);
                        db.Entry(fileDetail).State = EntityState.Added;
                    }
                }
                var user = UserManager.FindByName(User.Identity.Name);


                //設定佈告紀錄相關屬性
                entry.PostId           = post.PostId;
                entry.Section          = post.Section;
                entry.Title            = post.Title;
                entry.Category         = post.Category;
                entry.Content          = post.Content;
                entry.LastModifiedDate = DateTime.Now.ToString("yyyy/MM/dd");
                entry.ModifiedBy       = user.FullName;

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(post));
        }
Пример #28
0
        /// <summary>
        /// Return column index array for the column header fields.
        /// Given a CSV file, returns an integer array with the column number references by the columnNames
        /// The columns names is a comma seperate list of columns.
        /// If the column is not found then the returned array is -1 for that position.
        /// </summary>
        /// <param name="fileData">PostFile CSV File</param>
        /// <param name="colunmNames">Comma seperate string of columns to find.</param>
        /// <returns>An interger array of the index of the matching colunmNames fields, if no match is found then a -1 is in the array for that position</returns>
        private int[] FindColunmsNumberForFields(PostFile fileData, string colunmNames)
        {
            int[] headerIndexArray = null;
            int   lineCount        = 0;

            string[] lineArray  = FileDataToLineStringArray(fileData);
            string   lineString = GetLineFromArray(lineArray, lineCount++);

            while (lineString != null)
            {
                string[] inputItemArray = ConvertLineToItemArray(lineString);
                headerIndexArray = CheckForValidHeader(inputItemArray, colunmNames);
                break;
            }
            return(headerIndexArray);
        }
Пример #29
0
        public static FileInfoDTO ConvertToFileInfoDTO(PostFile postFile)
        {
            if (postFile == null)
            {
                throw new ArgumentNullException();
            }
            var file = postFile.File;

            return(new FileInfoDTO
            {
                Name = file.Name,
                Id = file.Id,
                SizeKB = file.SizeKB,
                ContentType = file.ContentType
            });
        }
Пример #30
0
        public FileScan FileScan(PostFile file)
        {
            this.ApiParams = new string[] { "scan" };

            string URL = GetFullAPIURL();

            Dictionary <string, object> ApiParams = new Dictionary <string, object>()
            {
                ["file"]   = file,
                ["apikey"] = ApiKey
            };

            ResponseAPI responseAPI = RequestAPI.SendRequest(URL, Method.POST, ApiParams).Result;

            return(CreateFileScan(responseAPI));
        }
Пример #31
0
 public JsonPostFile(PostFile file, Post post)
 {
     // Set...
     if (file != null)
     {
         Id              = file.Id;
         Type            = file.Type;
         Title           = file.Title;
         Url             = post.GetFileUrl(file);
         CreatorId       = file.CreatorId;
         CreatorName     = file.Creator?.UserName ?? "???";
         CreationDate    = file.CreationDate;
         CreationDateAge = Convert.ToInt32(DateTime.Now.Subtract(CreationDate).TotalDays);
         ModifiedDate    = file.ModifiedDate;
         PostId          = file.Post?.Id ?? 0;
     }
 }
Пример #32
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one post file
    /// </summary>
    /// <param name="post">A reference to a post file</param>
    public static long Add(PostFile post)
    {
        // Create the long to return
        long idOfInsert = 0;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.posts_files (post_id, language_id, title, src) "
            + "VALUES (@post_id, @language_id, @title, @src);SELECT SCOPE_IDENTITY();";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@post_id", post.post_id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@title", post.title);
                cmd.Parameters.AddWithValue("@src", post.src);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    idOfInsert = Convert.ToInt64(cmd.ExecuteScalar());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        // Return the id of the inserted item
        return idOfInsert;

    } // End of the Add method
Пример #33
0
        public ActionResult add_file(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get form values
            Int32 language_id = Convert.ToInt32(collection["selectLanguage"]);
            Int32 post_id = Convert.ToInt32(collection["txtId"]);
            string title = collection["txtFileTitle"];
            string returnUrl = collection["returnUrl"];
            HttpPostedFileBase uploadedFile = Request.Files["uploadFile"];

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Get the administrator
            Administrator administrator = Administrator.GetSignedInAdministrator();

            // Get the post
            Post post = Post.GetOneById(post_id, currentDomain.back_end_language);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (administrator != null && administrator.admin_role == "Author" &&
                (post == null || post.administrator_id == administrator.id))
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Create the directory string
            string filesDirectory = "/Content/posts/" + (post_id / 100).ToString() + "/" + post_id.ToString() + "/" + language_id.ToString() + "/files/";

            // Check if the directory exists
            if (System.IO.Directory.Exists(Server.MapPath(filesDirectory)) == false)
            {
                // Create the directory
                System.IO.Directory.CreateDirectory(Server.MapPath(filesDirectory));
            }

            // Set the file path
            string filePath = filesDirectory + System.IO.Path.GetFileName(uploadedFile.FileName);

            // Create a new post file
            PostFile postFile = new PostFile();
            postFile.post_id = post_id;
            postFile.language_id = language_id;
            postFile.title = title;
            postFile.src = filePath;

            // Add the post file
            if(uploadedFile.ContentLength > 0)
            {
                PostFile.Add(postFile);
                uploadedFile.SaveAs(Server.MapPath(filePath));
            }

            // Return the files view
            return RedirectToAction("files", new { id = post_id, returnUrl = returnUrl, lang = language_id });

        } // End of the add_file method
Пример #34
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a post file
    /// </summary>
    /// <param name="post">A reference to a post file</param>
    public static void Update(PostFile post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.posts_files SET post_id = @post_id, language_id = @language_id, " 
            + "title = @title, src = @src WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@post_id", post.post_id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@title", post.title);
                cmd.Parameters.AddWithValue("@src", post.src);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
Пример #35
0
 public static void HttpMultipart(HttpWebRequest request, Hashtable data, Hashtable files)
 {
     // We have files, so use the more complex multipart encoding.
     string boundary = string.Format("--{0}",
                                     DateTime.Now.Ticks.ToString("x"));
     request.ContentType = string.Format("multipart/form-data; boundary={0}",
                                          boundary);
     ArrayList items = new ArrayList();
     // Determine the amount of data we will be sending
     long length = 0;
     foreach (string key in data.Keys)
     {
         PostItem item = new PostItem(key, data[key].ToString(), boundary);
         items.Add(item);
         length += item.Length;
     }
     foreach (string key in files.Keys)
     {
         PostFile file = new PostFile(key, (FileInfo)files[key], boundary);
         items.Add(file);
         length += file.Length;
     }
     length += boundary.Length + 8;
     request.ContentLength = length;
     // Now stream the data.
     //using (Stream requestStream = File.Create("c:\\Users\\bneely\\documents\\debug.txt"))
     using (Stream requestStream = request.GetRequestStream())
     {
         foreach (PostItem item in items)
         {
             requestStream.Write(item.Header, 0, item.Header.Length);
             if (item.GetType() == typeof(PostFile))
             {
                 FileStream fileData = ((PostFile)item).OpenRead();
                 byte[] buffer = new byte[32768];
                 int read = 0;
                 while ((read = fileData.Read(buffer, 0, buffer.Length)) != 0)
                 {
                     requestStream.Write(buffer, 0, read);
                 }
             }
             else
             {
                 byte[] itemData = UTF8Encoding.UTF8.GetBytes(item.Data);
                 requestStream.Write(itemData, 0, itemData.Length);
             }
             byte[] end = UTF8Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));
             requestStream.Write(end, 0, end.Length);
         }
     }
 }