public ActionResult Create(DX_FILES dx_files)
        {
            long newFileId = -1;
            try
            {
                if (Request.Files[0].InputStream.Length != 0)
                {
                    if (Request.Files[0].InputStream.Length < MAX_FILE_SIZE)
                    {
                        HttpPostedFileBase file = Request.Files[0];
                        System.IO.Stream stream = file.InputStream;
                        byte[] fileData = new byte[stream.Length];
                        stream.Read(fileData, 0, fileData.Length);

                        string userid = SessionKeyMgmt.UserId;

                        //Setting properties of the file object

                        string description = Request.Params.Get("description");
                        if (description.Length != 0 || description.Length > 75)
                        {
                            dx_files.ownerid = userid;
                            dx_files.isarchived = false;
                            dx_files.islocked = false;

                            // Get the filename and its extension
                            string filetype = System.IO.Path.GetExtension(file.FileName);
                            string filename = System.IO.Path.GetFileName(file.FileName);

                            dx_files.type = filetype;
                            dx_files.filename = filename;

                            if (supportedFileTypes.Contains(filetype))
                            {
                                // Find if there are any files with the same filename
                                var existingFiles = from filesTable in db.DX_FILES
                                                    where filesTable.ownerid == userid && filesTable.filename == filename
                                                    select filesTable;

                                // If there already existed a document by this name
                                // increment the verison number
                                if (existingFiles.Count() != 0)
                                {
                                    DX_FILES existingFile = existingFiles.First();
                                    if (existingFile.isarchived == true)
                                    {
                                        ModelState.AddModelError("", "A file with the same name exists in your archived docs. Cannot upload");
                                        return View();
                                    }
                                    else
                                    {
                                        ModelState.AddModelError("", "A file with same name exists in My Docs. Please update the corresponding file");
                                        return View();
                                    }
                                }
                                else
                                {
                                    // Creating a new file
                                    dx_files.latestversion = 1;
                                    dx_files.creationdate = System.DateTime.Now;

                                    DX_USER user = db.DX_USER.Single(d => d.userid == userid);
                                    string accesslevel = user.accesslevel;

                                    if(accesslevel !="employee" && accesslevel!="manager" && accesslevel!="vp" && accesslevel!="ceo")
                                    {
                                        ModelState.AddModelError("", "You are not authorized to upload a file");
                                        return View();
                                    }

                                    //Based on the role, the file should be shared with managers
                                    // Create a new file version object
                                    DX_FILEVERSION fileversion = new DX_FILEVERSION();
                                    fileversion.isencrypted = false;

                                    // Encrypt the file data if requested
                                    string encrypted = Request.Params.Get("encrypted");
                                    if (encrypted == "true")
                                    {
                                        // Read the encrytion key
                                        if (Request.Files[1].InputStream.Length != 0)
                                        {
                                            HttpPostedFileBase keyFile = Request.Files[1];
                                            System.IO.Stream keyStream = keyFile.InputStream;
                                            byte[] keyData = new byte[keyStream.Length];
                                            keyStream.Read(keyData, 0, (int)keyStream.Length);
                                            fileversion.isencrypted = true;

                                            RijndaelManaged Crypto = new RijndaelManaged();
                                            Crypto.BlockSize = 128;
                                            Crypto.KeySize = 256;
                                            Crypto.Mode = CipherMode.CBC;
                                            Crypto.Padding = PaddingMode.PKCS7;
                                            Crypto.Key = keyData;

                                            // Convert the ivString to a byte array
                                            byte[] ivArray = new byte[16];
                                            System.Buffer.BlockCopy(ivStringConstant.ToCharArray(), 0,
                                                ivArray, 0, ivArray.Length);
                                            Crypto.IV = ivArray;

                                            ICryptoTransform Encryptor = Crypto.CreateEncryptor(Crypto.Key, Crypto.IV);
                                            byte[] cipherText = Encryptor.TransformFinalBlock(fileData, 0, fileData.Length);

                                            // Copy the encrypted data to the file data buffer
                                            Array.Clear(fileData, 0, fileData.Length);
                                            Array.Resize(ref fileData, cipherText.Length);
                                            Array.Copy(cipherText, fileData, cipherText.Length);
                                        }
                                        else
                                        {
                                            ModelState.AddModelError("", "Please enter a valid keyfile");
                                            return View();
                                        }
                                    }

                                    var allFiles = from fileversions in db.DX_FILEVERSION
                                                   select fileversions;
                                    double totalSize;
                                    if (allFiles.Count() != 0)
                                    {
                                        totalSize = allFiles.Sum(w => w.size);
                                    }
                                    else
                                        totalSize=0;
                                    totalSize /= (1024 * 1024);

                                    long maxSize = long.Parse(System.Configuration.ConfigurationManager.AppSettings["filestreamMaxSize"]);

                                    if ((totalSize + (fileData.Length / (1024 * 1024)) > maxSize))
                                    {
                                        ModelState.AddModelError("", "Disk space exceeded. Please contact admin");
                                        return View();
                                    }

                                    // Save changes for the DX_FILES object so the new fileid is
                                    // auto generated.
                                    db.DX_FILES.AddObject(dx_files);
                                    db.SaveChanges();

                                    newFileId = dx_files.fileid;

                                    fileversion.versionnumber = (int)dx_files.latestversion;
                                    fileversion.updatedate = System.DateTime.Now;
                                    fileversion.description = description;
                                    fileversion.updatedby = userid;

                                    // Add information about the file version to database
                                    fileversion.filedata = fileData;
                                    fileversion.size = fileData.Length;

                                    fileversion.fileid = dx_files.fileid;
                                    fileversion.versionid = Guid.NewGuid();

                                    db.DX_FILEVERSION.AddObject(fileversion);

                                    //Share with the owner
                                    DX_PRIVILEGE empPriv = new DX_PRIVILEGE();

                                    empPriv.userid = userid;
                                    empPriv.read = true;
                                    empPriv.update = true;
                                    empPriv.reason = "owner";
                                    empPriv.check = true;
                                    empPriv.delete = true;

                                    empPriv.fileid = dx_files.fileid;
                                    db.DX_PRIVILEGE.AddObject(empPriv);

                                    if (accesslevel == "employee")
                                    {
                                        //Getting the dept id of employee
                                        DX_USERDEPT userdept = db.DX_USERDEPT.Single(d => d.userid == userid);
                                        int deptid = userdept.deptid;

                                        //Getting the user id of manager
                                        var managers = from usersTable in db.DX_USER
                                                       join userdepts in db.DX_USERDEPT on usersTable.userid equals userdepts.userid
                                                       where usersTable.accesslevel == "manager" && userdepts.deptid == deptid
                                                       select usersTable;
                                        if (managers.Count() != 0)
                                        {
                                            DX_PRIVILEGE mgrPriv = new DX_PRIVILEGE();
                                            foreach (DX_USER managerUser in managers)
                                            {
                                                //Providing manager the respective rights
                                                string managerId = managerUser.userid;

                                                mgrPriv.userid = managerId;
                                                mgrPriv.read = true;
                                                mgrPriv.check = true;
                                                mgrPriv.update = true;
                                                mgrPriv.reason = "inherit";
                                                mgrPriv.delete = true;
                                                mgrPriv.fileid = dx_files.fileid;
                                                db.DX_PRIVILEGE.AddObject(mgrPriv);
                                            }
                                        }

                                    }
                                    if (accesslevel == "manager" || accesslevel == "employee")
                                    {
                                        //Getting the dept id of employee
                                        DX_USERDEPT userdept = db.DX_USERDEPT.Single(d => d.userid == userid);
                                        int deptid = userdept.deptid;

                                        var vp = from usersTable in db.DX_USER
                                                 join userdepts in db.DX_USERDEPT on usersTable.userid equals userdepts.userid
                                                 where usersTable.accesslevel == "vp" && userdepts.deptid == deptid
                                                 select usersTable;
                                        if (vp.Count() != 0)
                                        {
                                            foreach (DX_USER vpUser in vp)
                                            {
                                                DX_PRIVILEGE vpPriv = new DX_PRIVILEGE();
                                                string vpId = vpUser.userid;

                                                vpPriv.userid = vpId;
                                                vpPriv.read = true;
                                                vpPriv.check = true;
                                                vpPriv.update = true;
                                                vpPriv.reason = "inherit";
                                                vpPriv.delete = true;
                                                vpPriv.fileid = dx_files.fileid;
                                                db.DX_PRIVILEGE.AddObject(vpPriv);
                                            }
                                        }

                                    }
                                    if (accesslevel == "vp" || accesslevel == "manager" || accesslevel == "employee")
                                    {
                                        var ceo = from usersTable in db.DX_USER
                                                  where usersTable.accesslevel == "ceo"
                                                  select usersTable;
                                        if (ceo.Count() != 0)
                                        {
                                            foreach (DX_USER ceoUser in ceo)
                                            {
                                                DX_PRIVILEGE ceoPriv = new DX_PRIVILEGE();
                                                string ceoId = ceoUser.userid;

                                                ceoPriv.userid = ceoId;
                                                ceoPriv.read = true;
                                                ceoPriv.check = true;
                                                ceoPriv.update = true;
                                                ceoPriv.reason = "inherit";
                                                ceoPriv.delete = true;
                                                ceoPriv.fileid = dx_files.fileid;
                                                db.DX_PRIVILEGE.AddObject(ceoPriv);
                                            }
                                        }

                                    }

                                    db.SaveChanges();

                                    // Show the document list
                                    return RedirectToAction("ListDocuments");
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("","Invalid file type. Accepted file types are PDF, Word, Excel, PowerPoint, Text and Image Files");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("","Please enter a valid description");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "File size exceeded 5 MB Limit");
                        return View();
                    }
                }
                else
                {
                    ModelState.AddModelError("","Please select the file to be uploaded");
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("","Error uploading the document ");
                // Check if a document information has been uploaded to DX_FILES
                // and delete it
                if (newFileId != -1)
                {
                    db.DX_FILES.DeleteObject(dx_files);
                    db.SaveChanges();
                }
            }
            return View();
        }
 /// <summary>
 /// Create a new DX_FILEVERSION object.
 /// </summary>
 /// <param name="version">Initial value of the version property.</param>
 /// <param name="fileid">Initial value of the fileid property.</param>
 /// <param name="versionid">Initial value of the versionid property.</param>
 /// <param name="versionnumber">Initial value of the versionnumber property.</param>
 /// <param name="updatedate">Initial value of the updatedate property.</param>
 /// <param name="description">Initial value of the description property.</param>
 /// <param name="size">Initial value of the size property.</param>
 /// <param name="updatedby">Initial value of the updatedby property.</param>
 public static DX_FILEVERSION CreateDX_FILEVERSION(global::System.Int64 version, global::System.Int64 fileid, global::System.Guid versionid, global::System.Int32 versionnumber, global::System.DateTime updatedate, global::System.String description, global::System.Int32 size, global::System.String updatedby)
 {
     DX_FILEVERSION dX_FILEVERSION = new DX_FILEVERSION();
     dX_FILEVERSION.version = version;
     dX_FILEVERSION.fileid = fileid;
     dX_FILEVERSION.versionid = versionid;
     dX_FILEVERSION.versionnumber = versionnumber;
     dX_FILEVERSION.updatedate = updatedate;
     dX_FILEVERSION.description = description;
     dX_FILEVERSION.size = size;
     dX_FILEVERSION.updatedby = updatedby;
     return dX_FILEVERSION;
 }
        public ActionResult Update()
        {
            string originalCaller = "ListDocuments";
            try
            {
                // Get the parameters from request
                long fileId = long.Parse(Request.Params.Get("fileId"));
                string encryptionStatus = Request.Params.Get("encryptionStatus");
                bool isEncrypted = encryptionStatus == "true" ? true : false;
                originalCaller = Request.Params.Get("originalCaller");

                // Basics validations and permission checking
                // Check if the fileId to be updated is still valid
                DX_FILES dx_files = db.DX_FILES.SingleOrDefault(d => d.fileid == fileId);
                if (dx_files == null)
                    throw new FileNotFoundException("File not found!");

                // Get the current userId
                string userId = SessionKeyMgmt.UserId;

                // Check if user has update privileges for this document
                DX_PRIVILEGE documentPrivilege = db.DX_PRIVILEGE.SingleOrDefault(d => d.fileid == fileId && d.userid == userId);
                bool hasUpdatePrivileges = documentPrivilege == null ? false : documentPrivilege.check;

                if (hasUpdatePrivileges == false)
                    throw new AccessViolationException("Document cannot be updated. Access Denied. Please try later.");
                else if (dx_files.isarchived)
                    throw new AccessViolationException("Document is archived and cannot be updated");

                // Check if document is checked out by current user
                bool isFileLocked = false;
                if (dx_files.islocked.HasValue)
                    isFileLocked = (bool)dx_files.islocked;

                if (isFileLocked == false)
                    throw new AccessViolationException("Document cannot be updated. Please check out the file before updating.");

                bool isDocumentCheckedOutByUser = isFileLocked && (dx_files.lockedby == userId);

                // Check if document is not archived
                if (isDocumentCheckedOutByUser == false)
                    throw new AccessViolationException("Document cannot be updated now. Some one else has currently checked out the document. Please try later.");

                // Validate the input file length
                Int64 inputFileLength = Request.Files[0].InputStream.Length;
                if (inputFileLength <= 0)
                {
                    throw new ArgumentException("File uploaded cannot be empty. Please try again.");
                }
                else if (inputFileLength > MAX_FILE_SIZE)
                {
                    throw new ArgumentException("File uploaded cannot be exceed 5 MB. Please try again.");
                }
                else
                {
                    // Check if the new file uploaded will exceed the overall file size
                    var allFiles = from fileversions in db.DX_FILEVERSION
                                   select fileversions;
                    double totalSize = 0;
                    if (allFiles.Count() > 0)
                    {
                        totalSize = allFiles.Sum(w => w.size);
                        totalSize /= (1024 * 1024);
                    }

                    if ((totalSize + (inputFileLength / (1024 * 1024)) > 1024))
                    {
                        ModelState.AddModelError("", "Disk space exceeded. Please contact admin");
                        throw new Exception();
                    }
                }

                // Get the input file and validate the file name
                HttpPostedFileBase inputFile = Request.Files[0];
                if (inputFile.FileName != dx_files.filename)
                    throw new ArgumentException("Name of file uploaded should match the existing file getting updated");

                // Validate the description given
                string fileDescription = Request.Params.Get("description");
                if (fileDescription.Length <= 0 || fileDescription.Length > 75)
                    throw new ArgumentException("Description text should be atleast 1 character and can be a maximum of 75 characters");

                // Read the given file data
                System.IO.Stream inFileStream = inputFile.InputStream;
                byte[] inputFileData = new byte[inFileStream.Length];
                inFileStream.Read(inputFileData, 0, inputFileData.Length);

                DX_FILEVERSION fileVersion = new DX_FILEVERSION();
                fileVersion.isencrypted = false;

                // Check if file needs to be encrpted before storing it
                if (isEncrypted)
                {
                    Int64 keyFileLength = Request.Files[1].InputStream.Length;
                    if (keyFileLength <= 0)
                        throw new ArgumentException("Invalid key file size. Please try again.");

                    try
                    {
                        HttpPostedFileBase keyFile = Request.Files[1];
                        System.IO.Stream keyStream = keyFile.InputStream;
                        byte[] keyData = new byte[keyStream.Length];
                        keyStream.Read(keyData, 0, (int)keyStream.Length);

                        RijndaelManaged Crypto = new RijndaelManaged();
                        Crypto.BlockSize = 128;
                        Crypto.KeySize = 256;
                        Crypto.Mode = CipherMode.CBC;
                        Crypto.Padding = PaddingMode.PKCS7;
                        Crypto.Key = keyData;

                        // Convert the ivString to a byte array
                        byte[] ivArray = new byte[16];
                        System.Buffer.BlockCopy(ivStringConstant.ToCharArray(), 0,
                            ivArray, 0, ivArray.Length);
                        Crypto.IV = ivArray;

                        ICryptoTransform Encryptor = Crypto.CreateEncryptor(Crypto.Key, Crypto.IV);
                        byte[] cipherText = Encryptor.TransformFinalBlock(inputFileData, 0, inputFileData.Length);

                        // Copy the encrypted data to the file data buffer
                        Array.Clear(inputFileData, 0, inputFileData.Length);
                        Array.Resize(ref inputFileData, cipherText.Length);
                        Array.Copy(cipherText, inputFileData, cipherText.Length);

                        fileVersion.isencrypted = true;
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Error encrypting the document");
                    }
                }

                int newVersionNumber = Convert.ToInt32(dx_files.latestversion) + 1;

                // Construct the fileversion object and update database
                fileVersion.fileid = fileId;
                fileVersion.versionid = Guid.NewGuid();
                fileVersion.versionnumber = newVersionNumber;
                fileVersion.updatedate = System.DateTime.Now;
                fileVersion.description = fileDescription;
                fileVersion.size = inputFileData.Length;
                fileVersion.filedata = inputFileData;
                fileVersion.updatedby = userId;

                db.DX_FILEVERSION.AddObject(fileVersion);

                // Update the version number in DX_FILES
                dx_files.latestversion++;

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                if (ex is FileNotFoundException || ex is AccessViolationException ||
                    ex is ArgumentException)
                {
                    ModelState.AddModelError("", ex.Message);
                }
                else
                {
                    ModelState.AddModelError("", "Error updating the document");
                }
            }

            // Irrespective of whether document was updated or error
            // return to the original view
            switch (originalCaller)
            {
                case "ListDocuments": return RedirectToAction("ListDocuments");
                case "SharedFiles": return RedirectToAction("SharedFiles");
                case "DepartmentFiles": return RedirectToAction("DepartmentFiles", new { dept = TempData["dept"] as string });
                default: return RedirectToAction("ListDocuments");
            }
        }
 /// <summary>
 /// Deprecated Method for adding a new object to the DX_FILEVERSION EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToDX_FILEVERSION(DX_FILEVERSION dX_FILEVERSION)
 {
     base.AddObject("DX_FILEVERSION", dX_FILEVERSION);
 }