public static void WriteError(Exception ex)
        {
            //Gets errorLog path from configUtility
            string errorPath  = IGroupUtility.Decrypt(ConfigurationManager.AppSettings["ErrorLogPath"]);
            string requsetUrl = string.Empty;

            if (HttpContext.Current != null && HttpContext.Current.Request != null &&
                HttpContext.Current.Request.UrlReferrer != null)
            {
                requsetUrl = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            else
            {
                requsetUrl = "no url";
            }

            //Formats error message
            string completeInfo = requsetUrl + "__Source :" + ex.Source + Environment.NewLine +
                                  "Stack Trace :" + ex.StackTrace + Environment.NewLine + "Error Message :"
                                  + ex.Message + Environment.NewLine + "Date Time :" + DateTime.Now.ToString();

            completeInfo = completeInfo + Environment.NewLine +
                           "--------------------------------------------------------------" + Environment.NewLine;

            //FileName for ErrorLog.
            string fileName = DateTime.Now.ToShortDateString().Replace("/", "_") + ".txt";

            //Writes Error in LocalPath.
            WriteErrorInFile(completeInfo, fileName, errorPath, FileMode.Append);
        }
        /// <summary>
        /// For zipping the multiple files into a single file
        /// </summary>
        /// <param name="files"></param>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        public string ZipFiles(HttpFileCollection files, out double fileSize, out string originalFileName,
                               out string extension)
        {
            fileSize         = 0.0;
            originalFileName = string.Empty;
            extension        = string.Empty;
            string savedFileName = string.Empty;

            try
            {
                List <string> fileNames = new List <string>();
                extension = ConstantUtility.Extensions.Zip;

                //Saving the files to the server
                foreach (string key in files)
                {
                    HttpPostedFile file = files[key];

                    originalFileName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + ConstantUtility.Extensions.Zip;
                    savedFileName    = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + Guid.NewGuid().ToString() + ConstantUtility.Extensions.Zip;

                    fileNames.Add(file.FileName);

                    fileSize += (double)file.ContentLength / 1024;
                    string fileName = Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.TempFolder]), file.FileName);

                    file.SaveAs(fileName);
                }

                //Zipping the multiple files
                using (ZipFile zip = new ZipFile())
                {
                    for (int i = 0; i < fileNames.Count; i++)
                    {
                        zip.AddFile(Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.TempFolder]), fileNames[i]), string.Empty);
                    }
                    zip.Save(Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.FolderPath]), savedFileName));
                }

                //Deleting the individual file from the server
                foreach (string name in fileNames)
                {
                    string filePath = Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.TempFolder]), name);

                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                //Log error
                ErrorUtility.WriteError(ex);
            }
            return(savedFileName);
        }
Example #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string fileId;
                fileId = HttpContext.Current.Request.QueryString["FileId"];
                fileId = fileId.Replace(" ", "+");
                //Page.ClientScript.RegisterClientScriptBlock(GetType(), "PushNotification", "PushNotification();", true);

                frmDownloadhandler.Attributes.Add("src", "DownLoadFile.aspx?FileId=" + fileId);
                fileId = IGroupUtility.Decrypt(fileId);
                hdnDownloadFileId.Value = fileId;
            }
            catch (Exception ex)
            {
                ErrorUtility.WriteError(ex);
            }
        }
        /// <summary>
        /// This is used for resizing the images.
        /// </summary>
        /// <param name="originalFilepath"></param>
        /// <param name="thumbFileName"></param>
        public void ResizeImage(string originalFilepath, string thumbFileName)
        {
            Image FullsizeImage = null;

            try
            {
                int NewHeight = 1100;
                int NewWidth  = 800;
                using (FullsizeImage = Image.FromFile(originalFilepath))
                {
                    // Prevent using images internal thumbnail
                    FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

                    if (FullsizeImage.Height > 500)
                    {
                        NewHeight = 1100;
                        // Resize with height instead
                        NewWidth = FullsizeImage.Width * NewHeight / FullsizeImage.Height;
                    }
                }

                FullsizeImage.Dispose();
                Dictionary <string, string> Versions = new Dictionary <string, string>
                {
                    { "_Thumb", "width=96&height=72&format=png&dpi=150" }
                };

                string thumbPath = System.IO.Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.ThumbImagePath]), thumbFileName);

                ImageJob ObjImageJobThumbnail = new ImageJob(originalFilepath, thumbPath, new Instructions(Versions["_Thumb"]));
                ObjImageJobThumbnail.Build();
            }
            catch (Exception ex)
            {
                ErrorUtility.WriteError(ex);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            UploadedFile fileDetails = null;
            string       fileId      = string.Empty;

            try
            {
                if (!IsPostBack)
                {
                    if (HttpContext.Current.Request.QueryString["id"] != null)
                    {
                        if (CurrentUser.IsAdmin == 1)
                        {
                            fileId = HttpContext.Current.Request.QueryString["id"];
                            Page.ClientScript.RegisterStartupScript(typeof(Page), "CloseConsent", "window.close();", true);
                        }
                    }
                    else
                    {
                        fileId = HttpContext.Current.Request.QueryString["FileId"];
                        //Decrypt the file id
                        fileId = fileId.Replace(" ", "+");
                        fileId = IGroupUtility.Decrypt(fileId);
                    }
                    hdnFileId.Value = fileId;

                    DataAccessLayer objData = new DataAccessLayer();

                    //Get the name of the file.
                    fileDetails = objData.DownloadFile(Convert.ToInt32(fileId));

                    if (fileDetails != null && fileDetails.IsLocked &&
                        !fileDetails.IsDeleted)
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "ShowModalBox();", true);
                    }
                    else
                    {
                        string filePath = System.IO.Path.Combine(
                            IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.FolderPath]), fileDetails.SavedFileName);

                        //Check if the file is deleted or not by the user
                        if ((fileDetails != null && !fileDetails.IsDeleted && System.IO.File.Exists(filePath)) ||
                            (CurrentUser != null && CurrentUser.IsAdmin == 1 && fileDetails != null && !fileDetails.IsAdminDeleted &&
                             System.IO.File.Exists(filePath)))
                        {
                            //download the file if the file exists.
                            BusinessLogic objBusiness = new BusinessLogic();

                            objBusiness.DownloadFile(Convert.ToInt32(fileId), fileDetails);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", ConstantUtility.DownloadError, true);
                        }
                    }
                }
                else
                {
                    hdnFilePassword.Value = txtFilePassword.Value;
                }
            }
            catch (Exception ex)
            {
                //Log the error
                ErrorUtility.WriteError(ex);
            }
        }
Example #6
0
        /// <summary>
        /// List view's item bound command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lvFile_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            string backGroundImage = string.Empty;
            string extension       = string.Empty;

            try
            {
                ListViewDataItem dataItem = (ListViewDataItem)e.Item;

                if (e.Item.ItemType == ListViewItemType.DataItem)
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl divFileBox   = e.Item.FindControl(ConstantUtility.FileBox) as System.Web.UI.HtmlControls.HtmlGenericControl;
                    System.Web.UI.HtmlControls.HtmlGenericControl dvExtension  = e.Item.FindControl(ConstantUtility.ExtensionBox) as System.Web.UI.HtmlControls.HtmlGenericControl;
                    System.Web.UI.HtmlControls.HtmlImage          imgThumbnail = e.Item.FindControl(ConstantUtility.ThumbImage) as System.Web.UI.HtmlControls.HtmlImage;

                    if (System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.ThumbName) != DBNull.Value &&
                        !string.IsNullOrEmpty((string)System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.ThumbName)))
                    {
                        imgThumbnail.Attributes.CssStyle.Add("display", "block");
                        dvExtension.Attributes.CssStyle.Add("display", "none");

                        backGroundImage = (string)System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.ThumbName);

                        //For setting thumbnail.
                        if (!string.IsNullOrEmpty(backGroundImage))
                        {
                            backGroundImage = IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.ThumbFolder]) + @"\\" + backGroundImage;
                            string thumbnailPath = Server.MapPath(backGroundImage);

                            //if the image exists, set it as a source
                            if (System.IO.File.Exists(thumbnailPath))
                            {
                                imgThumbnail.Src = backGroundImage;
                            }
                        }
                    }
                    else if (System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.Exe) != DBNull.Value)
                    {
                        dvExtension.Attributes.CssStyle.Add("display", "block");
                        imgThumbnail.Attributes.CssStyle.Add("display", "none");

                        extension = (string)System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.Exe);
                        string color = ConstantUtility.ExeBackColor;
                        divFileBox.Attributes.CssStyle.Add("background-color", color);
                        dvExtension.InnerText = extension;
                    }

                    bool fileStatus = false;
                    if (System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.FileStatus) != DBNull.Value)
                    {
                        bool.TryParse(Convert.ToString(System.Web.UI.DataBinder.Eval(e.Item.DataItem, ConstantUtility.FileStatus))
                                      , out fileStatus);
                    }

                    System.Web.UI.HtmlControls.HtmlGenericControl dvLock   = e.Item.FindControl(ConstantUtility.Lock) as System.Web.UI.HtmlControls.HtmlGenericControl;
                    System.Web.UI.HtmlControls.HtmlGenericControl dvUnlock = e.Item.FindControl(ConstantUtility.Unlock) as System.Web.UI.HtmlControls.HtmlGenericControl;

                    //If the file is locked
                    if (fileStatus)
                    {
                        dvLock.Attributes.CssStyle.Add("display", "none");
                        dvUnlock.Attributes.CssStyle.Add("display", "block");
                    }
                    else //if the file is not locked
                    {
                        dvLock.Attributes.CssStyle.Add("display", "block");
                        dvUnlock.Attributes.CssStyle.Add("display", "none");
                    }

                    if (System.Web.UI.DataBinder.Eval(e.Item.DataItem, "TinyUrl") != DBNull.Value)
                    {
                        HiddenField hdnFileUrl = e.Item.FindControl("hdnFileUrl") as HiddenField;

                        if (hdnFileUrl != null)
                        {
                            if (!string.IsNullOrEmpty(Convert.ToString(System.Web.UI.DataBinder.Eval(e.Item.DataItem, "TinyUrl"))))
                            {
                                hdnFileUrl.Value = Convert.ToString(System.Web.UI.DataBinder.Eval(e.Item.DataItem, "TinyUrl"));
                            }
                            else
                            {
                                if (System.Web.UI.DataBinder.Eval(e.Item.DataItem, "FileId") != DBNull.Value)
                                {
                                    int fileId = 0;

                                    if (int.TryParse(Convert.ToString(System.Web.UI.DataBinder.Eval(e.Item.DataItem, "FileId")), out fileId))
                                    {
                                        hdnFileUrl.Value = GetFileUrl(fileId);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #7
0
        /// <summary>
        /// Returns the name of the file to be downloaded
        /// </summary>
        /// <param name="isDeleted">Whether the file is deleted or not</param>
        /// <param name="isLocked">whether the file is locked or not</param>
        /// <param name="filePassword">Filepassword of the locked file</param>
        /// <param name="fileId">fileid of the file to be downloaded</param>
        public UploadedFile DownloadFile(int fileId)
        {
            UploadedFile  file   = null;
            SqlDataReader reader = null;

            try
            {
                if (!string.IsNullOrEmpty(ConnectionString))
                {
                    using (SqlConnection dbConnection = new SqlConnection(ConnectionString))
                    {
                        using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.FileDownload, dbConnection))
                        {
                            command.CommandType = CommandType.StoredProcedure;

                            //Adding parameter
                            command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId));
                            dbConnection.Open();
                            reader = command.ExecuteReader();

                            //Read data using datareader
                            if (reader.HasRows && reader.Read())
                            {
                                file = new UploadedFile();

                                if (reader[ConstantUtility.IsDeleted] != DBNull.Value)
                                {
                                    file.IsDeleted = Convert.ToBoolean(reader[ConstantUtility.IsDeleted]);
                                }

                                if (reader[ConstantUtility.FileStatus] != DBNull.Value)
                                {
                                    file.IsLocked = Convert.ToBoolean(reader[ConstantUtility.FileStatus]);
                                }

                                if (reader[ConstantUtility.IsAdminDelete] != DBNull.Value)
                                {
                                    file.IsAdminDeleted = Convert.ToBoolean(reader[ConstantUtility.IsAdminDelete]);
                                }

                                if (reader[ConstantUtility.OriginalFileName] != DBNull.Value)
                                {
                                    file.OriginalFileName = Convert.ToString(reader[ConstantUtility.OriginalFileName]);
                                }

                                if (reader[ConstantUtility.SavedFileName] != DBNull.Value)
                                {
                                    file.SavedFileName = Convert.ToString(reader[ConstantUtility.SavedFileName]);
                                }

                                //Check if the file password exists or not.
                                if (reader[ConstantUtility.FilePassword] != DBNull.Value)
                                {
                                    file.FilePassword = IGroupUtility.Decrypt(Convert.ToString(reader[ConstantUtility.FilePassword]));
                                }
                            }
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                //Log the error
                ErrorUtility.WriteError(ex);
            }

            finally
            {
                if (reader != null)
                {
                    ((IDisposable)reader).Dispose();
                }
            }
            return(file);
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string machineName = System.Environment.MachineName;
                string ipAddress   = HttpContext.Current.Request.UserHostAddress;

                int    fileId           = 0;
                string fileName         = string.Empty;
                string originalFileName = string.Empty;
                string savedFileName    = string.Empty;
                string thumbFileName    = null;
                string extension        = string.Empty;
                double fileSize         = 0.0;

                BusinessLogic objBusiness = new BusinessLogic();

                //if there is more than one file, zip it before uploading it
                if (context.Request.Files.Count > 1)
                {
                    HttpFileCollection files = context.Request.Files;
                    savedFileName = ZipFiles(files, out fileSize, out originalFileName, out extension);
                    thumbFileName = objBusiness.ExtIconName(extension);
                }
                else if (context.Request.Files.Count == 1)
                {
                    HttpFileCollection files = context.Request.Files;

                    foreach (string key in files)
                    {
                        HttpPostedFile file = files[key];
                        string         guid = Guid.NewGuid().ToString();
                        fileName = file.FileName;

                        //Get the index of the last dot(.)
                        int indexOfExtension = fileName.LastIndexOf(".");

                        //Get the file extension
                        string fileExtension = fileName.Substring(indexOfExtension);

                        //Get the file name with out extension
                        string fileNameWithoutExtension = fileName.Substring(0, (fileName.Length - fileExtension.Length));

                        //Concat the file name with new guid
                        fileName = string.Concat(fileNameWithoutExtension, "_", guid, fileExtension);

                        //Get the new thumb file name
                        thumbFileName = string.Concat(fileNameWithoutExtension, "_", guid, "_thumb", fileExtension);
                        savedFileName = fileName;

                        //Get the physical path, where the file will be saved.
                        fileName = System.IO.Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.FolderPath]), fileName);

                        extension        = Path.GetExtension(fileName).Trim().ToLower();
                        originalFileName = file.FileName;

                        //saving the file with a unique name.
                        file.SaveAs(fileName);
                        fileSize = ((double)file.ContentLength / 1024);
                    }
                    if (Convert.ToString(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.ImageExtensions]).Contains(extension))
                    {
                        ResizeImage(fileName, thumbFileName);
                    }
                    else
                    {
                        thumbFileName = objBusiness.ExtIconName(extension);
                    }
                }

                DataAccessLayer objDataAccess = new DataAccessLayer();

                if (objDataAccess != null)
                {
                    fileId = objDataAccess.SaveFileDetails(originalFileName, savedFileName, CurrentUser.Id,
                                                           machineName, ipAddress, fileSize, extension, thumbFileName);
                    string fileEncryptedId = IGroupUtility.Encrypt(fileId.ToString());

                    //saving the data in session state.
                    HttpContext.Current.Session["FileId"] = fileEncryptedId;
                }
                context.Response.Output.Write(ConstantUtility.True);
            }
            catch (Exception ex)
            {
                //Log error
                ErrorUtility.WriteError(ex);
            }
        }