Ejemplo n.º 1
0
        public string getProfilePhotoPath(myUser u)
        {
            string imagePath = "Content/data/images/defM.png";

            if (u.PhotoRef == null) //no photo added
            {
                if (u.Gender.Equals("F"))
                {
                    imagePath = "Content/data/images/defF.png";
                }
            }
            else
            {
                OfficeChatDBEntities context = new OfficeChatDBEntities();
                FileHolder           fh      = new FileHolder();
                fh        = context.FileHolders.Find(u.PhotoRef);
                imagePath = fh.FName;

                if (imagePath.ElementAt(0).Equals('~'))
                {
                    imagePath = imagePath.Substring(2);
                }
            }

            return(imagePath);
        }
Ejemplo n.º 2
0
        public IFileHolder <XLWorkbook> GetFile(string fileName)
        {
            // получаем сохраненный файл
            string xsltPath = Path.Combine(_hostingEnvironment.WebRootPath, "excel", fileName);
            // начало использования библиотеке ClosedXML
            var workbook  = new XLWorkbook(xsltPath);
            var worksheet = workbook.Worksheet(1);

            var model = new FileHolder <XLWorkbook>(fileName, workbook);

            var capacity = worksheet.FirstColumnUsed().LastCellUsed().Address.RowNumber;

            capacity--;

            foreach (var column in worksheet.ColumnsUsed())
            {
                var rowItem = new RowItem(capacity);

                foreach (var usedCell in column.CellsUsed().Where(c => c.Address.RowNumber > 1))
                {
                    rowItem.SetValue(usedCell.Address.RowNumber - 2, usedCell.Value.ToString());
                }

                model.FileRowList.AddRow(rowItem);
            }


            return(model);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> PostFile(int Id, IFormFile sendFile)
        {
            if (sendFile != null)
            {
                Folder folder = await db.GetFolderByIdAsync(Id);

                IClientProxy hub = _folderHub.Clients.All;
                if (hub == null)
                {
                    return(BadRequest());
                }

                FileHolder uplodadedFile = new FileHolder
                {
                    Name   = sendFile.FileName,
                    Folder = folder,
                    Size   = sendFile.Length,
                    Type   = sendFile.ContentType
                };
                await db.AddFileAsync(uplodadedFile);

                using (Stream fileStream = sendFile.OpenReadStream())
                {
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(db.GetDatabase().GetDbConnection().ConnectionString);
                    await Extensions.InsertFileStream(builder, uplodadedFile.Id, fileStream);
                }

                await hub.SendAsync("DataUpdate");

                return(Ok());
            }
            return(NotFound());
        }
Ejemplo n.º 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OfficeChatDBEntities context = new OfficeChatDBEntities();
            int u1 = (int)Session["curUserID"];

            myUser user1 = context.myUsers.Find(u1);

            if (user1.Role != "manager")
            {
                wrapper.InnerHtml = "<h1>Managers only</h1> <a href='index.aspx'>Back to main page</a>";
            }
            else
            {
                Company c = context.Companies.Find(user1.Company);

                if (IsPostBack)
                {
                    string name  = String.Format("{0}", Request.Form["Text1"]);
                    string desc  = String.Format("{0}", Request.Form["Text2"]);
                    string email = String.Format("{0}", Request.Form["Text3"]);

                    c.N_ame = name;
                    c.D_esc = desc;
                    c.Email = email;

                    HttpPostedFile postedFile = Request.Files["FileUpload"];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
                        string filePath = Server.MapPath("tmpFiles/") + Path.GetFileName(postedFile.FileName);

                        postedFile.SaveAs(filePath);


                        FileHolder fh = new FileHolder();
                        fh.FName = "~/tmpFiles/" + Path.GetFileName(postedFile.FileName);

                        context.FileHolders.Add(fh);
                        c.LogoRef = fh.FID;
                    }

                    user1.Company = c.CID;
                    context.SaveChanges();
                }
                else
                {
                    Text1.Value = c.N_ame;
                    Text2.Value = c.D_esc;
                    Text3.Value = c.Email;

                    Image img = new Image();
                    img.ImageUrl = getfilepathComp(c);
                    img.Height   = Unit.Pixel(100);
                    img.Width    = Unit.Pixel(100);

                    imageHere.Controls.Add(img);
                }
            }
        }
Ejemplo n.º 5
0
 void InnerDispose()
 {
     try
     {
         _holder?.Release();
     }
     finally
     {
         _holder = null !;
     }
 }
Ejemplo n.º 6
0
        public string getfilepathComp(Company c)
        {
            string imagePath = "Content/data/images/defComp.png";

            if (c.LogoRef != null)
            {
                OfficeChatDBEntities context = new OfficeChatDBEntities();

                FileHolder fh = new FileHolder();
                fh        = context.FileHolders.Find(c.LogoRef);
                imagePath = fh.FName;
            }
            return(imagePath);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Xu ly ket qua truoc khi tra ve client
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            string temp = "";

            try
            {
                HttpContent content = null;
                if (resultValue != null)
                {
                    if (resultValue.GetType() == typeof(bool) || resultValue.GetType() == typeof(Boolean))
                    {
                        temp    = resultValue.ToString().ToLower();
                        content = new StringContent(temp);
                    }
                    else if (resultValue.GetType().IsPrimitive || resultValue.GetType() == typeof(string))
                    {
                        temp    = resultValue + "";
                        content = new StringContent(temp);
                    }
                    else if (resultValue.GetType() == typeof(FileHolder))
                    {
                        FileHolder sr = (FileHolder)resultValue;
                        if (sr != null)
                        {
                            content = new StreamContent(sr.Content);
                            content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
                            content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                            content.Headers.ContentDisposition.FileName = sr.FileName;
                        }
                    }
                    else
                    {
                        temp    = JsonConvert.SerializeObject(resultValue);
                        content = new StringContent(temp);
                    }
                }

                var response = new HttpResponseMessage()
                {
                    Content        = content,
                    RequestMessage = actionContext.Request
                };
                return(Task.FromResult(response));
            }
            catch (Exception ex)
            {
                LogSystem.Error(ex);
            }
            return(null);
        }
Ejemplo n.º 8
0
        public IFileHolder <XLWorkbook> GetFile(string fileName)
        {
            // получаем сохраненный файл
            var xsltPath = Path.Combine(_webHostEnvironment.ContentRootPath + @"~/App_Data" + fileName);
            // начало использования библиотеке ClosedXML
            var workbook  = new XLWorkbook(xsltPath);
            var worksheet = workbook.Worksheet(1);

            var model = new FileHolder <XLWorkbook>(fileName, workbook);



            return(model);
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> DeleteFile(int id)
        {
            FileHolder file = await db.GetFileByIdAsync(id);

            if (file == null)
            {
                return(NotFound());
            }
            await db.RemoveFileAsync(file);

            await _folderHub.Clients.All.SendAsync("DataUpdate");

            return(Ok(file));
        }
Ejemplo n.º 10
0
        private FileBucket(FileHolder holder, int bufferSize = 8192, int chunkSize = 4096)
        {
            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferSize));
            }
            if (chunkSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(chunkSize));
            }

            _holder = holder ?? throw new ArgumentNullException(nameof(holder));
            _holder.AddRef();
            _buffer          = new byte[bufferSize];
            _chunkSizeMinus1 = chunkSize - 1;
            _bufStart        = -bufferSize;
            _nDispose        = 1;
        }
Ejemplo n.º 11
0
        public static FileResult GetFileResult(this FileHolder file)
        {
            if (file == null)
            {
                return(null);
            }

            const string contentType = "application/octet-stream";
            var          ms          = new MemoryStream();

            ms.Write(file.Data, 0, file.Data.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, contentType)
            {
                FileDownloadName = file.Name
            });
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> UploadFileAsync(IFormFile image)
        {
            if (image == null)
            {
                throw new Exception("File is null");
            }
            if (image.Length == 0)
            {
                throw new Exception("File is empty");
            }

            string folderName  = "images";
            string webRootPath = _env.ContentRootPath + "\\ClientApp\\src\\assets\\";
            string newPath     = Path.Combine(webRootPath, folderName);

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }

            var file = new FileHolder();

            file.Name = image.FileName;

            using (var memoryStream = new MemoryStream())
            {
                await image.CopyToAsync(memoryStream);

                file.File = memoryStream.ToArray();
            }
            string fileName = ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName.Trim('"');
            string fullPath = Path.Combine(newPath, fileName);

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                image.CopyTo(stream);
            }

            _unitOfWork.Files.Add(file);
            _unitOfWork.SaveChanges();

            return(Ok(file));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Get(int Id)
        {
            var writer = new MemoryStream();
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(db.GetDatabase().GetDbConnection().ConnectionString);

            try
            {
                FileHolder file = await db.GetFileByIdAsync(Id);

                Extensions.ReadFileStream(builder, file.Id, file.Name, writer);
                writer.Position = 0;
                return(File(writer, file.Type, file.Name));
            }
            catch (Exception)
            {
                writer.Dispose();
                return(NotFound());
            }
        }
Ejemplo n.º 14
0
        private static Files LoadAllFilesFromRootPath(DirectoryInfo xiTreeRoot)
        {
            Files lAcc            = new Files();
            Regex lLevelNameRegex = new Regex("[A-Z]+\\\\[A-Z]+[0-9]\\.DAT$", RegexOptions.IgnoreCase);

            foreach (FileInfo file in xiTreeRoot.GetFiles("*.DAT", SearchOption.AllDirectories))
            {
                Level lev;

                if (lLevelNameRegex.IsMatch(file.FullName))
                {
                    using (FileStream fs = file.OpenRead())
                    {
                        lev = new Level(fs);
                        FileHolder fh = new FileHolder(file.FullName, lev);
                        lAcc.FileHolders.Add(fh);
                    }
                }
            }
            return(lAcc);
        }
Ejemplo n.º 15
0
 public ActionResult GetReadyFile(string name, short key)
 {
     return(DownloadXlsxFile(FileHolder.GetFile(key), name));
 }
 public Task AddFileAsync(FileHolder file)
 {
     _dbContext.Files.Add(file);
     return(_dbContext.SaveChangesAsync());
 }
Ejemplo n.º 17
0
        private static Files LoadAllFilesFromRootPath(DirectoryInfo xiTreeRoot)
        {
            Files lAcc = new Files();
              Regex lLevelNameRegex = new Regex("[A-Z]+\\\\[A-Z]+[0-9]\\.DAT$", RegexOptions.IgnoreCase);
              foreach (FileInfo file in xiTreeRoot.GetFiles("*.DAT", SearchOption.AllDirectories))
              {
            Level lev;

            if (lLevelNameRegex.IsMatch(file.FullName))
            {
              using (FileStream fs = file.OpenRead())
              {
            lev = new Level(fs);
            FileHolder fh = new FileHolder(file.FullName, lev);
            lAcc.FileHolders.Add(fh);
              }
            }
              }
              return lAcc;
        }
 public Task RemoveFileAsync(FileHolder file)
 {
     _dbContext.Files.Remove(file);
     return(_dbContext.SaveChangesAsync());
 }
Ejemplo n.º 19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int urgentflag = 0, receivedflag = 0;

            OfficeChatDBEntities context = new OfficeChatDBEntities();
            List <M_essage>      msgs    = context.M_essage.ToList();


            //remove any spam messages
            foreach (M_essage ms in msgs)
            {
                if (ms.T_ext == null)
                {
                    context.M_essage.Remove(ms);
                    context.SaveChanges();
                }
            }

            //getting users
            int    u1    = (int)Session["curUserID"];
            myUser user1 = context.myUsers.Find(u1);
            int    u2    = int.Parse((string)Session["user2"]);
            myUser user2 = context.myUsers.Find(u2);

            //setting up profile photo:
            Image pf = new Image();

            pf.ImageUrl = getProfilePhotoPath(user1);
            pf.CssClass = "profileImage rounded-circle float-right";
            profilePhoto.Controls.Add(pf);

            List <myUser> users = context.myUsers.ToList();

            //add user2 image, name, and status at top:
            string imagepath = getProfilePhotoPath(user2);
            string status    = "Offline";
            string color     = "red";

            if (user2.isOnline == 1)
            {
                status = "Online";
                color  = "green";
            }

            user2Dets.InnerHtml = "<img src='" + imagepath + "' class='profileImageTo rounded-circle'/>"
                                  + "<span style = 'font-size:20px' > " + user2.N_ame + " </span>"
                                  + "<span style = 'color:" + color + "'> " + status + " </span>"
                                  + "<a href=\"index.aspx?\"> X </a>";
            M_essage mes = new M_essage();

            if (Request.QueryString["sending"] == "1" && IsPostBack) //text message
            {
                //Add typed message to database
                mes.timeSent   = System.DateTime.Now;
                mes.SenderID   = user1.UserID;
                mes.ReceiverID = user2.UserID;
                mes.isRead     = 0;
                mes.isUrgent   = 0;
                mes.isDeleted  = 0;
                mes.isText     = 1;
                mes.isFile     = 0;
                mes.T_ext      = Request.Form["messageIn"];

                if (Checkbox1.Checked == true)
                {
                    mes.isUrgent = 1;
                }
                if (mes.T_ext != "")
                {
                    context.M_essage.Add(mes);
                }
                context.SaveChanges();
            }
            HttpPostedFile postedFile = Request.Files["fileupload"];

            if (postedFile != null && postedFile.ContentLength > 0)//file was uploaded
            {
                mes.isFile = 1;

                string filePath = Server.MapPath("tmpFiles/") + Path.GetFileName(postedFile.FileName);

                postedFile.SaveAs(filePath);

                FileHolder fh = new FileHolder();
                fh.FName    = "tmpFiles/" + Path.GetFileName(postedFile.FileName);
                mes.FileRef = fh.FID;
                context.FileHolders.Add(fh);
                context.SaveChanges();
            }

            msgs = context.M_essage.ToList(); //refreshing messages list

            chatField.InnerHtml = "~Beginning of chat with " + user2.N_ame;

            //get messages/fileRefs from database with right sender/receiver and add them in order
            foreach (M_essage m in msgs)
            {
                //setting up read string
                string readString = "Not read yet";
                if (m.isRead == 1)
                {
                    readString = m.timeRead.ToString();
                }
                //form user2 to user1
                if (m.SenderID.Equals(user1.UserID) && m.ReceiverID.Equals(user2.UserID))
                {
                    if (m.isText == 1)
                    {
                        if (m.isUrgent == 1)
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2 urgent\"> Sent: " + m.timeSent + " Read: " + readString + " <br/>" + m.T_ext + " </div>";
                        }
                        else //not urgent
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2\"> " + m.timeSent + " Read: " + readString + " <br/>" + m.T_ext + " </div>";
                        }
                    }
                    if (m.isFile == 1) //file/photo
                    {
                        FileHolder fh2      = context.FileHolders.Find(m.FileRef);
                        String     filepath = fh2.FName;
                        String     ext3     = filepath.Substring(filepath.Length - 4); // .png .jpg
                        String     ext4     = filepath.Substring(filepath.Length - 5); // .jpeg
                        if (ext3.Equals(".png") || ext3.Equals(".jpg") || ext4.Equals(".jpeg"))
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2\"> <img src = '" + fh2.FName + "' class='imgupload'> </div>";
                        }
                        else //non image file
                        {
                            string filename = filepath.Split('/')[1];
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2\"> <a href='" + fh2.FName + "' download> <img src='Content/data/icons/download.png' class='btnIcon icon'/> Download " + filename + "</a></div>";
                        }
                    }
                }
                //user1 to user2
                else if (m.SenderID.Equals(user2.UserID) && m.ReceiverID.Equals(user1.UserID))
                {
                    if (m.isText == 1)
                    {
                        if (m.isUrgent == 1)
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user1 urgent\"> " + m.timeSent + " Read: " + readString + " <br/>" + m.T_ext + " </div>";
                        }
                        else //not urgent
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user1\"> " + m.timeSent + " Read: " + readString + " <br/>" + m.T_ext + " </div>";
                        }
                    }
                    if (m.isFile == 1) //file/photo
                    {
                        FileHolder fh2      = context.FileHolders.Find(m.FileRef);
                        String     filepath = fh2.FName;
                        String     ext3     = filepath.Substring(filepath.Length - 4); // .png .jpg
                        String     ext4     = filepath.Substring(filepath.Length - 5); // .jpeg
                        if (ext3.Equals(".png") || ext3.Equals(".jpg") || ext4.Equals(".jpeg"))
                        {
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2\"> <img src = '" + fh2.FName + "' class='imgupload'> </div>";
                        }
                        else //non image file
                        {
                            string filename = filepath.Split('/')[1];
                            chatField.InnerHtml = chatField.InnerHtml + "<div class =\"row user2\"> <button onclick=\"javascript: window.location = '" + fh2.FName + "'\" class='ButtonDownload'> <img src='Content/data/icons/download.png' class='btnIcon icon'/> Download " + filename + "</button></div>";
                        }
                    }
                    if (m.isRead == 0)
                    {
                        m.isRead   = 1;
                        m.timeRead = System.DateTime.Now;
                    }
                }
            }
            context.SaveChanges();

            //Filling sidebar
            //get messages that are directed to user1 and unread then add them to the list (for no repetition)
            List <myUser> usersSending       = new List <myUser>();
            List <myUser> usersSendingUrgent = new List <myUser>();

            foreach (M_essage m in msgs)
            {
                //if directed to user1
                if (m.ReceiverID.Equals(user1.UserID))
                {
                    myUser sendingUser = context.myUsers.Find(m.SenderID);
                    if (!usersSending.Contains(sendingUser) && !usersSendingUrgent.Contains(sendingUser))
                    {
                        if (m.isUrgent == 1 && m.isRead == 0)
                        {
                            usersSendingUrgent.Add(sendingUser);
                        }
                        else
                        {
                            usersSending.Add(sendingUser);
                        }
                    }
                }
            }
            //Go through the lists and add the users to the sidebar
            foreach (myUser sendingUser in usersSendingUrgent)
            {
                urgentflag   = 1;
                receivedflag = 1;
                string imagePath = getProfilePhotoPath(sendingUser);

                ImageButton but = new ImageButton();
                but.ImageUrl = imagePath;
                but.Width    = Unit.Pixel(50);
                but.Height   = Unit.Pixel(50);
                but.Click   += new ImageClickEventHandler(Button_Click);
                but.ID       = "" + sendingUser.UserID;

                HtmlGenericControl div1 = new HtmlGenericControl("div");
                div1.Controls.Add(but);
                div1.Controls.Add(new LiteralControl(" " + sendingUser.N_ame + " [" + sendingUser.Title + "]"));

                div1.Attributes["class"] = "sidenavbardivurgent";

                newChatHolder.Controls.Add(div1);
            }
            foreach (myUser sendingUser in usersSending)
            {
                receivedflag = 1;
                string imagePath = getProfilePhotoPath(sendingUser);

                ImageButton but = new ImageButton();
                but.ImageUrl      = imagePath;
                but.Width         = Unit.Pixel(50);
                but.Height        = Unit.Pixel(50);
                but.OnClientClick = "Button_Click";
                but.Click        += new ImageClickEventHandler(Button_Click);
                but.ID            = "" + sendingUser.UserID;

                HtmlGenericControl div1 = new HtmlGenericControl("div");
                div1.Controls.Add(but);
                div1.Controls.Add(new LiteralControl(" " + sendingUser.N_ame + " [" + sendingUser.Title + "]"));

                div1.Attributes["class"] = "sidenavbardiv";

                newChatHolder.Controls.Add(div1);
            }
            //update message icon in top bar if needed
            if (receivedflag == 1)
            {
                msgLogo.Src = "Content/data/icons/msg.png";
            }
            if (urgentflag == 1)
            {
                msgLogo.Src = "Content/data/icons/msgUrg.png";
            }
            //refresh entire page
            System.Threading.Thread.Sleep(1500);
            HttpContext.Current.RewritePath("indexChat.aspx/sending=0");

            context.SaveChanges();
        }
Ejemplo n.º 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OfficeChatDBEntities context = new OfficeChatDBEntities();
            int    u1    = (int)Session["curUserID"];
            myUser user1 = context.myUsers.Find(u1);

            if (IsPostBack)
            {
                string   name  = String.Format("{0}", Request.Form["Text1"]);
                string   gend  = String.Format("{0}", Request.Form["Text2"]);
                string   email = String.Format("{0}", Request.Form["Text3"]);
                DateTime start = DateTime.Parse(Request.Form["Text4"]);
                string   title = String.Format("{0}", Request.Form["Text5"]);
                string   comp  = String.Format("{0}", Request.Form["Text6"]);

                Company c = null;
                foreach (Company cmp in context.Companies)
                {
                    if (cmp.N_ame.Equals(comp))
                    {
                        c = cmp;
                        break;
                    }
                }
                user1.N_ame          = name;
                user1.Gender         = gend;
                user1.Email          = email;
                user1.Title          = title;
                user1.StartedWorking = start;

                HttpPostedFile postedFile = Request.Files["FileUpload"];
                if (postedFile != null && postedFile.ContentLength > 0)
                {
                    string filePath = Server.MapPath("tmpFiles/") + Path.GetFileName(postedFile.FileName);

                    postedFile.SaveAs(filePath);


                    FileHolder fh = new FileHolder();
                    fh.FName = "~/tmpFiles/" + Path.GetFileName(postedFile.FileName);

                    context.FileHolders.Add(fh);
                    user1.PhotoRef = fh.FID;
                }

                if (c != null)
                {
                    user1.Company = c.CID;
                    context.SaveChanges();
                }
                else
                {
                    errorHolder.InnerHtml = "<h4 style='color:red'> Company does not exist </h4>";
                }
            }
            else
            {
                Text1.Value = user1.N_ame;
                Text2.Value = user1.Gender;
                Text3.Value = user1.Email;
                Text4.Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(' ', 'T');
                Text5.Value = user1.Title;
                string cname = context.Companies.Find((int)user1.Company).N_ame;
                Text6.Value = cname;

                Image img = new Image();
                img.ImageUrl = getfilepath(user1);
                img.Height   = Unit.Pixel(100);
                img.Width    = Unit.Pixel(100);

                imageHere.Controls.Add(img);
            }
        }