Ejemplo n.º 1
0
        public static void Upload(FileUpload newFile, DropDownList folderName, Label lblMessage)
        {
            try
            {
                // Get the files about to be uploaded
                IList <HttpPostedFile> filePaths = newFile.PostedFiles;
                string message = "";

                // Get the user id thats currently logged in
                string userId = HttpContext.Current.Session["UserId"].ToString();
                var    user   = db.HPSUsers.Select(u => u)
                                .Where(uid => uid.UserId == userId)
                                .SingleOrDefault();

                // Get the role the current folder is in to assign the file to that role as well
                int folderId = Convert.ToInt32(folderName.SelectedValue);
                var folder   = db.Folders.Select(a => a)
                               .Where(b => b.Id == folderId)
                               .SingleOrDefault();

                // Hold the folder name in a variable before it gets deleted
                string   nameOfFolder   = folder.FolderName;
                string   roles          = folder.RoleName;
                string[] roleNamesArray = new string[1];

                // Check for multiple roles there will always be at least 1 role
                if (roles.Contains(','))
                {
                    roleNamesArray = roles.Split(',');
                }
                else
                {
                    roleNamesArray[0] = roles;
                }

                foreach (var file in filePaths)
                {
                    string filePath    = file.FileName;
                    string filename    = Path.GetFileName(filePath);
                    string ext         = Path.GetExtension(filename).ToLower();
                    string contenttype = String.Empty;

                    switch (ext)
                    {
                    case ".doc":
                        contenttype = "application/vnd.ms-word";
                        break;

                    case ".docx":
                        contenttype = "application/vnd.ms-word";
                        break;

                    case ".xls":
                        contenttype = "application/vnd.ms-excel";
                        break;

                    case ".xlsx":
                        contenttype = "application/vnd.ms-excel";
                        break;

                    case ".jpg":
                        contenttype = "image/jpg";
                        break;

                    case ".png":
                        contenttype = "image/png";
                        break;

                    case ".gif":
                        contenttype = "image/gif";
                        break;

                    case ".jpeg":
                        contenttype = "image/jpeg";
                        break;

                    case ".pdf":
                        contenttype = "application/pdf";
                        break;

                    case ".txt":
                        contenttype = "text/plain";
                        break;

                    case ".avi":
                        contenttype = "video/avi";
                        break;

                    case ".mov":
                        contenttype = "video/quicktime";
                        break;

                    case ".mp3":
                        contenttype = "audio/mpeg3";
                        break;

                    case ".mpeg":
                        contenttype = "video/mpeg";
                        break;

                    case ".mpg":
                        contenttype = "video/mpeg";
                        break;

                    case ".mp4":
                        contenttype = "video/mp4";
                        break;
                    }

                    // Decalre instance of new file object
                    HPSFile f = new HPSFile();

                    using (var binaryReader = new BinaryReader(file.InputStream))
                    {
                        // Get bytes
                        var memoryBytes = binaryReader.ReadBytes(file.ContentLength);

                        // Assign bytes to fileData
                        f.FileData = memoryBytes;
                        f.FileSize = memoryBytes.Length;
                        // Check if type is image, if so, compress and resize the image
                        using (var memoryStream = new MemoryStream(memoryBytes))
                        {
                            if (contenttype.Contains("image"))
                            {
                                System.Drawing.Image imageStream = System.Drawing.Image.FromStream(memoryStream);
                                f.Thumbnail = ImageToByte(ResizeImage(imageStream, 100, 100));
                            }
                            else
                            {
                                f.Thumbnail = null;
                            }
                        }
                    }

                    // Assign the rest of the details to the file object
                    f.FileName        = filename;
                    f.FolderId        = folderId;
                    f.FileContentType = contenttype;
                    f.FileExtension   = ext;
                    f.FileDate        = DateTime.Now;
                    f.UserId          = userId;
                    f.RoleName        = folder.RoleName;

                    // Declare insatnace of null thumbnail
                    //Byte[] thumbnail = null;



                    //// Create blank bitmap
                    //Bitmap bmp;
                    //if (contenttype.Contains("image"))
                    //{
                    //    using (var ms = new MemoryStream(bytes))
                    //    {
                    //        bmp = new Bitmap(ms);
                    //        thumbnail = ImageToByte(ResizeImage(bmp, 100, 100));

                    //        // Clear these out of memory to allow more images to be uploaded
                    //        bmp.Dispose();
                    //    }
                    //}

                    //// Set the column names for the new file
                    //HPSFile f = new HPSFile();
                    //f.FileName = filename;
                    //f.FolderId = folderId;
                    //f.FileSize = file.ContentLength;
                    //f.FileContentType = contenttype;
                    //f.FileExtension = ext;
                    //f.Thumbnail = thumbnail;
                    //f.FileDate = DateTime.Now;
                    //f.UserId = userId;
                    //f.RoleName = folder.RoleName;

                    // Add the file to the database
                    db.HPSFiles.Add(f);

                    // Add the file names to the message
                    message += "'" + filename + "', ";
                }

                // Trim the trailing and leading comma's and extra spaces
                char[] charsToTrim = { ',', ' ' };
                message = message.Trim(charsToTrim);

                try
                {
                    // Save to the database
                    db.SaveChanges();

                    // Create a notification for the database
                    NotificationCreator.CreateNotification(roleNamesArray, "File Uploaded", filePaths.Count + " file(s) were uploaded to the " + folder.FolderName + " folder by " + user.AspNetUser.UserName, DateTime.Now, "Info", null, null);

                    // Set the message
                    lblMessage.CssClass = "text-success";
                    lblMessage.Text     = filePaths.Count + " file(s) were successfully uploaded to the " + folder.FolderName + " folder.";
                }
                catch (DataException dx)
                {
                    HttpContext.Current.Response.Write(dx.ToString());
                    // Set the message
                    lblMessage.CssClass = "text-danger";
                    lblMessage.Text     = filePaths.Count + " file(s) " + message + " could not be uploaded at this time. Please try again later or inform an administrator";
                }
            }
            catch (OutOfMemoryException ox)
            {
                HttpContext.Current.Response.Write(ox.ToString());
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.ToString());
            }
        }
Ejemplo n.º 2
0
        public static void DeleteFile(int id)
        {
            ActivityTracker.Track("Deleted a File", (int)UserActionEnum.Deleted);
            // Get all files attached to folder
            HPSFile file = db.HPSFiles.Find(id);

            // Hold the folder name in a variable before it gets deleted
            string folderName = file.Folder.FolderName;
            string roles      = file.Folder.RoleName;

            string[] roleNamesArray = new string[1];


            // Check for multiple roles there will always be at least 1 role
            if (roles.Contains(','))
            {
                roleNamesArray = roles.Split(',');
            }
            else
            {
                roleNamesArray[0] = roles;
            }

            // Get the user id thats currently logged in
            string userId = HttpContext.Current.Session["UserId"].ToString();
            var    user   = db.HPSUsers.Select(u => u)
                            .Where(uid => uid.UserId == userId)
                            .SingleOrDefault();

            try
            {
                // Remove the file
                db.HPSFiles.Remove(file);

                // Save Changes to the database
                db.SaveChanges();

                // Create a notification for the database
                NotificationCreator.CreateNotification(roleNamesArray, "File Deleted", user.AspNetUser.UserName + " deleted '" + file.FileName + "' from the " + folderName + " folder.", DateTime.Now, "Info", id, null);

                // Set the delete flag and refresh the page so we can rebuild the folders/files
                deleteClicked = true;

                // Set the notification
                notificationMessage = "'" + file.FileName + "'  was successfully deleted.";
                notificationStyle   = "text-success";
                notification        = true;
            }
            catch (DataException dx)
            {
                // Set the notification
                notificationMessage = "'" + file.FileName + " could not be deleted at this time. Please try again later or inform an Administrator.";
                notificationStyle   = "text-danger";
                notification        = true;

                // Write error to log file Log File Writer
                LogFile.WriteToFile("FileManager.aspx.cs", "DeleteFile", dx, user.AspNetUser.UserName + "tried to delete a File named " + file.FileName, "HPSErrorLog.txt");
            }
            catch (Exception ex)
            {
                // Set the notification
                notificationMessage = "'" + file.FileName + " could not be deleted at this time. Please try again later or inform an Administrator.";
                notificationStyle   = "text-danger";
                notification        = true;

                // Write error to log file Log File Writer
                LogFile.WriteToFile("FileManager.aspx.cs", "DeleteFile", ex, user.AspNetUser.UserName + "tried to delete a File named " + file.FileName, "HPSErrorLog.txt");
            }
        }
Ejemplo n.º 3
0
        protected void btnCalendarEvent_Click(object sender, EventArgs e)
        {
            HelperMethods.ActivityTracker.Track("Viewed a Calendar Event", (int)UserActionEnum.Clicked);
            // Get the id from the clicked link button
            int id = Convert.ToInt32(Request.Form["__EVENTARGUMENT"]);

            // Query the db for that specific record
            CalendarEvent calEvent = db.CalendarEvents.Select(c => c)
                                     .Where(c => c.Id == id)
                                     .SingleOrDefault();

            // Get the file associated with this calendar event
            HPSFile file = db.HPSFiles.Where(f => f.Id == calEvent.FileId).SingleOrDefault();

            // Add data to controls
            txtEventName.Text            = calEvent.CalendarEventName;
            ddlVisibilty.SelectedValue   = calEvent.RoleName;
            txtEventDescription.Text     = calEvent.CalendarEventDescription;
            txtEventDate.Text            = Convert.ToDateTime(calEvent.CalendarEventDate).ToString("yyyy-MM-dd");
            txtEventTime.Text            = Convert.ToDateTime(calEvent.CalendarEventDate).ToString("HH:mm");
            hdrEventModalTitle.InnerHtml = "<b>" + calEvent.CalendarEventName + "</b>" + " - " + Convert.ToDateTime(calEvent.CalendarEventDate).ToLongDateString();

            // if user is not administrator, disable controls
            if (!Page.User.IsInRole("Administrator"))
            {
                txtEventName.Enabled        = false;
                ddlVisibilty.Enabled        = false;
                txtEventDescription.Enabled = false;
                txtEventDate.Enabled        = false;
                txtEventTime.Enabled        = false;
                ddlEventFile.Enabled        = false;
            }

            // Check if there is a file assocaited with this event
            if (file != null)
            {
                btnEventFileDownload.Attributes.Add("data-id", file.Id.ToString());
                btnEventFileDownload.OnClientClick       = "";
                btnEventFileDownload.Attributes["title"] = "Download: " + file.FileName;
                ddlEventFile.SelectedValue = file.Id.ToString();
            }
            else
            {
                btnEventFileDownload.OnClientClick       = "return false";
                btnEventFileDownload.Attributes["title"] = "No File to Download.";
                ddlEventFile.SelectedValue = "null";
            }

            //pnlSetFile.Visible = false;
            //pnlDownloadFile.Visible = true;

            // Add id's to button clicks
            btnDeleteEvent.Attributes.Add("data-id", calEvent.Id.ToString());
            btnSaveEvent.Attributes.Add("data-id", calEvent.Id.ToString());

            // If these 3 roles are the user thats log in, allow update and delete priviledges
            if (User.IsInRole("Administrator"))
            {
                btnDeleteEvent.Visible = true;
                btnSaveEvent.Visible   = true;
                btnCreateEvent.Visible = false;
            }
            else
            {
                btnDeleteEvent.Visible = false;
                btnSaveEvent.Visible   = false;
                btnCreateEvent.Visible = false;
            }

            // Open the modal to display information
            ScriptManager.RegisterStartupScript(this, this.GetType(), "eventModal", "$('#mdlEventsCalendar').modal('show');", true);
        }