Example #1
0
 internal Reader(
     IInputStream stream,
     files.File file
     )
 {
     this.parser = new FileParser(stream, file);
 }
Example #2
0
   internal CompressedWriter(
 files.File file,
 IOutputStream stream
 )
       : base(file, stream)
   {
   }
Example #3
0
        public static File SaveCamera(string image, int folder_id)
        {
            File result = new File();

            result.status = false;
            if (image != null)
            {
                rekursosEntities db     = new rekursosEntities();
                files            insert = new files();

                image = image.Replace("data:image/png;base64,", "");
                byte[] data = Convert.FromBase64String(image);

                MD5 md5 = MD5.Create();
                insert.filename = GetMd5Hash(md5, GetUniqID()) + ".png";
                insert.name     = "camera_" + insert.filename;
                var destinationImgPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads"), insert.filename);

                System.IO.File.WriteAllBytes(destinationImgPath, data);

                if (System.IO.File.Exists(destinationImgPath))
                {
                    DateTime now  = DateTime.Now;
                    var      info = new System.IO.FileInfo(destinationImgPath);
                    // var dto = new DateTimeOffset(DateTime.Now);



                    insert.filesize   = (int)info.Length;
                    insert.mimetype   = "image/png";
                    insert.folder_id  = folder_id;
                    insert.extension  = ".png";
                    insert.type       = "i";
                    insert.date_added = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

                    System.Drawing.Image myImage = System.Drawing.Image.FromFile(destinationImgPath);


                    insert.width  = myImage.Width;
                    insert.height = myImage.Height;

                    string id = GetMd5Hash(md5, insert.filename);



                    insert.id = id.Substring(0, 15);

                    db.files.Add(insert);
                    db.SaveChanges();


                    result.status  = true;
                    result.message = "El archivo se ha subido correctamente";
                    result.data    = insert;
                }
            }

            return(result);
        }
Example #4
0
        static void Main(string[] args)
        {
            files t = new files();

            t.Reader(arg);

            Connections();
        }
Example #5
0
   internal FileParser(
 IInputStream stream,
 files.File file
 )
       : base(stream)
   {
       this.file = file;
   }
Example #6
0
 private async Task <int> SaveFiles(files file, Image img)
 {
     // save thumb
     SaveToFolder(img, new Size(160, 160), file.ThumbPath);
     // save image of size max 600 x 600
     SaveToFolder(img, new Size(650, 650), file.ImagePath);
     // Save  to database
     return(await Save(file));
 }
Example #7
0
        private async Task <int> Save(files file)
        {
            db.files.Add(file);
            await db.SaveChangesAsync();

            int id = file.Id;

            return(id);
        }
 public static void createDocument(files file)
 {
     using (var conn = new db_entities()) {
         try {
             conn.SP_FILE_INSERT(file.task_id, file.name, file.url, file.path, DateTime.Now);
         } catch (Exception e) {
             throw e;
         }
     }
 }
Example #9
0
        /// <summary>
        /// 还原文件
        /// </summary>
        public void Restore()
        {
            decimal fid  = this.requestData.fid;
            files   file = (from c in db.files
                            where c.use_id == this.uid && c.softdelete == true && c.id == fid
                            select c).FirstOrDefault();

            file.softdelete = false;
            file.updated_at = DateTime.Now;
            db.SubmitChanges();
        }
Example #10
0
        public void loadInfromationAboutFiles(string nameFile, string time, string sizeFile)
        {
            files dataFile = new files() // создаём экземпляр класса
            {
                nameFile = nameFile,     // указываем имя файла
                time     = time,         // указываем время создания
                sizeFile = sizeFile      // указываем пароль
            };

            listUsers.Items.Add(dataFile); // выводим строку в список
        }
Example #11
0
        /// <summary>
        /// 删除文件(软删除)
        /// </summary>
        /// <param name="fid">文件编号</param>
        private void FileDelete(files file)
        {
            string path = App.Get("SavePath");

            if (file != null)
            {
                //File.Delete(path + file.guid);
                file.fol_id     = null;
                file.softdelete = true;
                file.updated_at = DateTime.Now;
            }
            db.SubmitChanges();
        }
Example #12
0
        /// <summary>
        /// 彻底删除文件
        /// </summary>
        public void Destroy()
        {
            string  path = App.Get("SavePath");
            decimal fid  = this.requestData.fid;
            files   file = (from c in db.files
                            where c.use_id == this.uid && c.softdelete == true && c.id == fid
                            select c).FirstOrDefault();

            File.Delete(path + file.guid);
            db.record.DeleteAllOnSubmit(db.record.Where(u => u.fil_id == fid)); //删除记录
            db.files.DeleteOnSubmit(file);
            db.users.Where(u => u.id == this.uid).FirstOrDefault().savedsize -= file.size;
            db.SubmitChanges();
        }
Example #13
0
        public void TestMethod1()
        {
            var   list = new string[] { "test.h", "test1.h" };
            files s;

            s = new files();

            var x = s.Reader(list);

            Assert.IsNotNull(x);
            Assert.AreEqual(x.Count, 2);
            Assert.IsTrue(x.ContainsKey("test.h"));

            Assert.IsTrue(x.ContainsKey("test1.h"));
        }
Example #14
0
        public void Rename()
        {
            decimal id   = this.requestData.info.id;
            decimal type = this.requestData.info.type;
            string  name = this.requestData.name;

            NodeData ret = null;

            if (type == 0)   //文件夹类型
            {
                folders folder = (from c in db.folders
                                  where c.id == id
                                  select c).FirstOrDefault();
                folder.name       = name;
                folder.updated_at = DateTime.Now;
                db.SubmitChanges();
                ret = new NodeData
                {
                    id       = folder.id,
                    type     = 0,
                    filename = folder.name.Trim(),
                    time     = folder.updated_at,
                    del      = false,
                    size     = "-"
                };
            }
            else
            {
                files file = (from c in db.files
                              where c.id == id
                              select c
                              ).FirstOrDefault();
                file.name       = name;
                file.updated_at = DateTime.Now;
                db.SubmitChanges();
                ret = new NodeData
                {
                    id       = file.id,
                    type     = file.fil_id == null ? 6 : (decimal)file.fil_id,
                    filename = file.name.Trim(),
                    time     = file.updated_at,
                    del      = file.softdelete,
                    size     = file.size.ToString()
                };
            }

            this.resultData = ret;
        }
Example #15
0
        private void insertImageData()
        {
            try
            {
                if (imageName != "")
                {
                    //Initialize a file stream to read the image file
                    FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);

                    //Initialize a byte array with size of stream
                    byte[] imgByteArr = new byte[fs.Length];



                    //Read data from the file stream and put into the byte array
                    fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));


                    //Close a file stream
                    fs.Close();


                    try
                    {
                        var newImage = new files()
                        {
                            code = "foto",
                            img  = imgByteArr
                        };
                        dbContext.files.Add(newImage);
                        dbContext.SaveChanges();

                        insertedPhotoID = newImage.ID;
                    }
                    catch (DbUpdateException ex)
                    {
                        MessageBox.Show("Problem yarandı" + ex.ToString());
                    }
                    finally
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static void createTask(Task task)
        {
            try {
                if (TaskDAL.exists(task.name))
                {
                    throw new ExistsException();
                }
                else
                {
                    tasks tasks = new tasks();
                    tasks.name        = task.name;
                    tasks.description = task.description;

                    if (task.processId != -1 && task.processId != 0)
                    {
                        tasks.process_id = int.Parse(task.processId + "");
                    }
                    if (task.assingId != -1 && task.processId != 0)
                    {
                        tasks.assing_id = int.Parse(task.assingId + "");
                    }
                    if (task.fatherTaksId != -1 && task.processId != 0)
                    {
                        tasks.father_taks_id = int.Parse(task.fatherTaksId + "");
                    }
                    tasks.task_status     = task.taskStatusId;
                    tasks.creator_user_id = task.creatorUserId;
                    tasks.created_at      = DateTime.Now;
                    tasks.date_end        = task.dateEnd;


                    var id = TaskDAL.createTask(tasks);

                    if (task.document != null)
                    {
                        files file = new files();
                        file.name    = task.document.name;
                        file.url     = task.document.url;
                        file.path    = task.document.path;
                        file.task_id = id;

                        DocumentDAL.createDocument(file);
                    }
                }
            } catch (Exception e) {
                throw e;
            }
        }
Example #17
0
        //Eliminacion del archivo fisico del disco duro
        public static bool _unlink_file(files file)
        {
            if (file.filename == null)
            {
                return(false);
            }
            string path = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads"), file.filename);

            if (System.IO.File.Exists(path) == true)
            {
                FileStream f = new FileStream(path, FileMode.Open);
                f.Close();
                f.Dispose();

                System.IO.File.Delete(path);
            }

            return(true);
        }
Example #18
0
        public void Delete()
        {
            decimal id   = this.requestData.id;
            decimal type = this.requestData.type;

            //判断是文件夹还是文件
            if (type == 0)
            {
                BFSDeleteFolder(id);
            }
            else
            {
                files file = (from c in db.files
                              where c.id == id
                              select c).FirstOrDefault();
                FileDelete(file);
            }
            this.resultData = null;
        }
Example #19
0
        public IHttpActionResult getimages([FromBody] string[] subidas)
        {
            List <files> lsMostrar = new List <files>();
            var          response  = new MyReponse();

            try
            {
                foreach (var id in subidas)
                {
                    int   idConvertido = Convert.ToInt32(id);
                    files f            = db.files.Where(x => x.Id == idConvertido).FirstOrDefault();
                    lsMostrar.Add(f);
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message, e.InnerException);
            }
            return(Ok(lsMostrar));
        }
Example #20
0
    void OnGUI()
    {
        GUI.skin.label.fontSize  = 22;
        GUI.skin.button.fontSize = 22;



        if (GUI.Button(new Rect(0, 0, proper_bigbuttonsize, proper_bigbuttonsize), btnretry) || Input.GetKeyDown(KeyCode.R) && sander > 10)
        {
            sander = 0;
            files filer = new files();
            filer.BinaryWriteInt("needgenerate", 1);

            string levelname;
            int    autoid = Random.Range(0, 4);
            switch (autoid)
            {
            case 0:
                levelname = "normalmaze";
                break;

            case 1:
                levelname = "icemaze";
                break;

            case 2:
                levelname = "easywhitemaze";
                break;

            case 3:
                levelname = "programmermaze";
                break;

            default:
                levelname = "normalmaze";
                break;
            }
            SceneManager.LoadScene(levelname);
            // Application.LoadLevel ("icemaze");
        }
    }
Example #21
0
    protected void BtnOk_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string savePath = Server.MapPath("~/admin/upload/");//指定上传文件在服务器上的保存路径
            //检查服务器上是否存在这个物理路径,如果不存在则创建
            if (!System.IO.Directory.Exists(savePath))
            {
                System.IO.Directory.CreateDirectory(savePath);
            }
            string Extension = Path.GetExtension(FileUpload1.FileName);     //获取后缀名
            string fname     = DateTime.Now.ToString("yyyyMMddHHmmssffff"); //当前时间作为文件名
            string finalname = "/admin/upload/" + fname + Extension;        //存在数据库中的路径
            savePath = savePath + "\\" + fname + Extension;
            try
            {
                FileUpload1.SaveAs(savePath);
                using (var db = new SiewebEntities())
                {
                    var fs = new files();

                    fs.title      = TxtTitle.Text;
                    fs.filename   = finalname;
                    fs.lang       = 0;
                    fs.createtime = DateTime.Now;
                    fs.viewlevel  = Convert.ToInt32(DdlKind.SelectedValue.ToString());
                    db.files.Add(fs);
                    db.SaveChanges();
                    Response.Write("<script>alert('添加成功');window.location.href='files.aspx'</script>");
                }
            }
            catch
            {
                Response.Write("<script>alert('添加失败')</script>");
            }
        }
        else
        {
            LabMessage.Text = "你还没有选择上传文件!";
        }
    }
Example #22
0
        /// <summary>
        /// Converts this instance of <see cref="files"/> to an instance of <see cref="filesDTO"/>.
        /// </summary>
        /// <param name="entity"><see cref="files"/> to convert.</param>
        public static filesDTO ToDTO(this files entity)
        {
            if (entity == null)
            {
                return(null);
            }

            var dto = new filesDTO();

            dto.id_file     = entity.id_file;
            dto.name_file   = entity.name_file;
            dto.adjunt_date = entity.adjunt_date;
            dto.status      = entity.status;
            dto.type        = entity.type;
            dto.modify_date = entity.modify_date;
            dto.address     = entity.address;

            entity.OnDTO(dto);

            return(dto);
        }
Example #23
0
        /// <summary>
        /// Converts this instance of <see cref="filesDTO"/> to an instance of <see cref="files"/>.
        /// </summary>
        /// <param name="dto"><see cref="filesDTO"/> to convert.</param>
        public static files ToEntity(this filesDTO dto)
        {
            if (dto == null)
            {
                return(null);
            }

            var entity = new files();

            entity.id_file     = dto.id_file;
            entity.name_file   = dto.name_file;
            entity.adjunt_date = dto.adjunt_date;
            entity.status      = dto.status;
            entity.type        = dto.type;
            entity.modify_date = dto.modify_date;
            entity.address     = dto.address;

            dto.OnEntity(entity);

            return(entity);
        }
Example #24
0
        public string getFilesByPath(string path)
        {
            List <files> listoffiles = new List <files>();
            files        backpath    = new files();

            backpath.path = path.Replace("\\" + path.Split('\\').Last(), "");
            backpath.name = "...";
            backpath.size = "0";
            backpath.type = "folder";
            listoffiles.Add(backpath);

            foreach (string FI in Directory.GetDirectories(path))
            {
                try
                {
                    files n = new files();
                    n.path = Path.Combine(path, FI);
                    n.name = Path.GetFileName(FI);
                    n.size = " ";
                    n.type = "folder";
                    listoffiles.Add(n);
                }
                catch { }
            }
            foreach (string FI in Directory.GetFiles(path))
            {
                try
                {
                    files n = new files();
                    n.path = Path.Combine(path, FI);
                    n.name = Path.GetFileName(FI);
                    n.size = new FileInfo(FI).Length.ToString();
                    n.type = "file";
                    listoffiles.Add(n);
                }
                catch { }
            }
            return(encode(listoffiles));
        }
Example #25
0
        public async Task <HttpResponseMessage> Upload(string projectId, string sectionId)
        {
            var status = new MyReponse();

            try
            {
                var context = HttpContext.Current.Request;
                if (context.Files.Count > 0)
                {
                    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

                    var index = 0;
                    foreach (var streamContent in filesReadToProvider.Contents)
                    {
                        var fileBytes = await streamContent.ReadAsByteArrayAsync();

                        var file = new files();
                        file.ProjectId = projectId;
                        file.SectionId = sectionId;
                        file.FileName  = context.Files[index].FileName;
                        file.FileSize  = fileBytes.Length;
                        file.ImagePath = String.Format("/UploadedFiles/{0}_{1}_{2}", projectId, sectionId, file.FileName);
                        file.ThumbPath = String.Format("/UploadedFiles/{0}_{1}_th_{2}", projectId, sectionId, file.FileName);
                        var img = Image.FromStream(new System.IO.MemoryStream(fileBytes));
                        status.subidas.Add(await SaveFiles(file, img));
                        index++;
                    }
                    status.Status  = true;
                    status.Message = "File uploaded successfully";
                    return(Request.CreateResponse(HttpStatusCode.OK, status));
                }
            }
            catch (Exception ex)
            {
                status.Message = ex.Message;
            }
            return(Request.CreateResponse(HttpStatusCode.OK, status));
        }
 partial void Deletefiles(files instance);
 partial void Updatefiles(files instance);
 partial void Insertfiles(files instance);
Example #29
0
    public static bool addProposal(long inquiryId, string jeid, string url)
    {
        InquiriesDataContext dbContext = new InquiriesDataContext();

        //Update existing like status
        likes myLike = null;
        try
        {
            myLike = dbContext.likes.Single(p => p.iid == inquiryId && p.jeid == jeid);
        }
        catch (Exception ex)
        {
            //No inquiry there
        }

        if (myLike != null)
        {
            myLike.status = 3;

            files newFile = new files();
            newFile.created = DateTime.Now;
            newFile.external_url = url;

            newFile.likes.Add(myLike);

            dbContext.SubmitChanges();

            return true;
        }
        else
        {
            return false;
        }

    }
Example #30
0
    //比对
    private void RunCheck()
    {
        int percent = 50;
        int state = 0;
        recCount = 0;//中标数
        if (alKeys.Count > 0)
        {
            percent /= alKeys.Count;
            foreach (string sKey in alKeys)
            {
                state = Convert.ToInt32(Session["State"].ToString());

                files attachFiles = new files();
                recCount += attachFiles.searchFile(sKey, 0);
                Session["State"] = state + percent;
                recCount += DB.CheckData(0, sKey, "", "");
                Session["State"] = state + percent * 2;
            }
            Session["recCount"] = recCount;
            Session["State"] = 100;
        }
    }
Example #31
0
        public static File upload(HttpPostedFileBase file, int folder_id)
        {
            rekursosEntities db     = new rekursosEntities();
            files            insert = new files();
            File             result = new File();

            result.status = false;

            try
            {
                var file_name = Path.GetFileName(file.FileName);
                var extension = Path.GetExtension(file.FileName);

                //Extraemos mime,type y extension
                _check_ext(file);


                MD5      md5 = MD5.Create();
                DateTime now = DateTime.Now;
                // var dto = new DateTimeOffset(DateTime.Now);


                insert.filename   = GetMd5Hash(md5, GetUniqID()) + extension;
                insert.name       = file_name;
                insert.filesize   = file.ContentLength;
                insert.mimetype   = file.ContentType;
                insert.folder_id  = folder_id;
                insert.extension  = _ext;
                insert.type       = _type;
                insert.date_added = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
                insert.user_id    = null;
                insert.width      = null;
                insert.height     = null;
                if (System.Web.HttpContext.Current.User != null)
                {
                    /*var user = Cobacam.Security.Ion_Auth.GetUser(System.Web.HttpContext.Current.User.Identity.Name);
                     *
                     * if (user != null)
                     * {
                     *  file_m.user_id = user.id;
                     * }*/
                }
                string id = GetMd5Hash(md5, insert.filename);



                insert.id = id.Substring(0, 15);

                if (IsImage(file.ContentType))
                {
                    System.Drawing.Image myImage = System.Drawing.Image.FromStream(file.InputStream);


                    insert.width  = myImage.Width;
                    insert.height = myImage.Height;
                }

                db.files.Add(insert);
                db.SaveChanges();

                var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads"), insert.filename);
                file.SaveAs(path);
                result.status  = true;
                result.message = "El archivo se ha subido correctamente";
                result.data    = insert;
            }
            catch (Exception ex)
            {
                result.status  = false;
                result.message = ex.Message.ToString();
            }
            return(result);
        }
Example #32
0
        private void genericReceive()
        {
            bool connected = true;

            Socket n  = socketList[socketList.Count - 1];
            String nm = nameList[socketList.Count - 1];

            int index = socketList.Count - 1;

            while (connected)
            {
                try
                {
                    byte[] buffer = new byte[2048];

                    int receivedByteLen = n.Receive(buffer);
                    if (receivedByteLen <= 0)
                    {
                        throw new SocketException();
                    }

                    string message = Encoding.Default.GetString(buffer);
                    string code    = message.Substring(0, 4);

                    if (code == upload)
                    {
                        int size = Int32.Parse(message.Substring(4, message.IndexOf("\0") - 4));
                        boxLog.Items.Add(nm + " is  sending a file");
                        FileReceive(n, nm, size);
                    }
                    else if (code == request)
                    {
                        bool empty = false;
                        boxLog.Items.Add(nm + " wants the list of his files.");
                        string fCollection = request;
                        for (int i = 0; i < userList.Count; i++)
                        {
                            if (nm == userList[i].username)
                            {
                                if (userList[i].file.Count == 0)
                                {
                                    empty = true;
                                    genericSend(text + "Server : Your file list is empty.", n);
                                }
                                else
                                {
                                    for (int k = 0; k < userList[i].file.Count; k++)
                                    {
                                        if (k == (userList[i].file.Count - 1))
                                        {
                                            fCollection += userList[i].file[k].filename + "*"
                                                           + userList[i].file[k].date + "*" + userList[i].file[k].size;
                                        }
                                        else
                                        {
                                            fCollection += userList[i].file[k].filename + "*"
                                                           + userList[i].file[k].date + "*" + userList[i].file[k].size + "<";
                                        }
                                    }
                                }
                                i = userList.Count;
                            }
                        }
                        if (empty == false)
                        {
                            genericSend(fCollection, n);
                        }
                    }
                    else if (code == delete)
                    {
                        string fDelete = message.Substring(4, message.IndexOf("\0") - 4);
                        boxLog.Items.Add(nm + " wants to delete " + fDelete + ".");
                        bool exist = false;
                        for (int i = 0; i < userList.Count; i++)
                        {
                            if (nm == userList[i].username)
                            {
                                //TODO check empty list
                                for (int k = 0; k < userList[i].file.Count; k++)
                                {
                                    if (userList[i].file[k].filename == fDelete)
                                    {
                                        exist = true;
                                        try
                                        {
                                            string[] files = Directory.GetFiles(userList[i].userpath);
                                            for (int j = 0; j < files.Length; j++)
                                            {
                                                if (files[j] == System.IO.Path.Combine(userList[i].userpath, fDelete))
                                                {
                                                    //File.SetAttributes(fDelete, FileAttributes.Normal);
                                                    File.Delete(files[j]);
                                                    userList[i].file.RemoveAt(k);
                                                    genericSend(text + "Your file is deleted", n);
                                                    boxLog.Items.Add(nm + "'s file is deleted.");
                                                    k = userList[i].file.Count;
                                                }
                                            }
                                        }
                                        catch
                                        {
                                            boxLog.Items.Add(nm + "'s file could not be deleted.");
                                            genericSend(text + "File that you requested could not be deleted.", n);
                                        }
                                    }
                                }
                                if (exist == false)
                                {
                                    genericSend(text + "File that you want to delete could not be found.", n);
                                }
                                i = userList.Count;
                            }
                        }
                    }
                    else if (code == rename)
                    {
                        //TODO
                        files  f         = new files();
                        String existFile = message.Substring(4, message.IndexOf("*") - 4);
                        String fRename   = message.Substring(message.IndexOf("*") + 1, message.IndexOf("\0") - message.IndexOf("*") - 1);
                        boxLog.Items.Add(nm + " wants to rename " + existFile + " with " + fRename);
                        bool renm = true, exist = false;
                        for (int i = 0; i < userList.Count; i++)
                        {
                            if (nm == userList[i].username)
                            {
                                for (int k = 0; k < userList[i].file.Count; k++)
                                {
                                    if (userList[i].file[k].filename == existFile)
                                    {
                                        f     = userList[i].file[k];
                                        exist = true;

                                        for (int j = 0; j < userList[i].file.Count; j++)
                                        {
                                            if (fRename == userList[i].file[j].filename)
                                            {
                                                j    = userList[i].file.Count;
                                                renm = false;
                                                genericSend(text + "Your new name is already used.", n);
                                                k = userList[i].file.Count;
                                            }
                                        }
                                        if (renm == true)
                                        {
                                            String oldPath = System.IO.Path.Combine(serverFolder, nm, existFile);
                                            String newPath = System.IO.Path.Combine(serverFolder, nm, fRename);

                                            File.Move(oldPath, newPath);
                                            f.filename          = fRename;
                                            userList[i].file[k] = f;
                                            genericSend(text + "Your file is renamed", n);
                                            boxLog.Items.Add(nm + "'s " + existFile + " file is renamed with " + fRename + ".");
                                            k = userList[i].file.Count;
                                        }
                                    }
                                }
                            }
                            i = userList.Count;
                            if (exist == false)
                            {
                                genericSend(text + "There is no file exists with this name.", n);
                            }
                        }
                    }
                    else if (code == download)
                    {
                        String fname = message.Substring(4, message.IndexOf("\0") - 4);
                        boxLog.Items.Add(nm + " wants to download " + fname + ".");

                        bool exist = false;
                        for (int i = 0; i < userList.Count; i++)
                        {
                            if (nm == userList[i].username)
                            {
                                //TODO check empty list
                                for (int k = 0; k < userList[i].file.Count; k++)
                                {
                                    if (userList[i].file[k].filename == fname)
                                    {
                                        exist = true;
                                        genericSend(text + "Server: Your file " + fname + " is being sent to you.", n);
                                        FileSend(n, nm, fname);
                                        k = userList[i].file.Count;
                                    }
                                }
                                if (exist == false)
                                {
                                    genericSend(text + "File that you want to download could not be found.", n);
                                }
                                i = userList.Count;
                            }
                        }
                    }
                }
                catch
                {
                    if (!terminating)
                    {
                        boxLog.Items.Add(nm + " has disconnected...");
                        nameList.Remove(nm);
                    }
                    n.Close();

                    socketList.Remove(n);
                    nameList.Remove(nm);
                    for (int m = boxName.Items.Count - 1; m >= 0; --m)
                    {
                        string removelistitem = nm;
                        if (boxName.Items[m].ToString().Contains(removelistitem))
                        {
                            boxName.Items.RemoveAt(m);
                            m = -1;
                        }
                    }
                    connected = false;
                }
            }
        }
Example #33
0
        private void FileReceive(Socket n, String nm, int size)
        {
            try
            {
                byte[] buffer = new byte[size];
                n.Receive(buffer);

                string path = System.IO.Path.Combine(serverFolder, nm);


                int    fNameLen = BitConverter.ToInt32(buffer, 0);
                String fName    = Encoding.ASCII.GetString(buffer, 4, fNameLen);
                // if there exist a file with same name
                String extension = fName.Substring(fName.IndexOf("."), fName.Length - fName.IndexOf(".")); //extension
                String tempName  = fName.Substring(0, fName.IndexOf("."));                                 //fname without extension
                int    count     = 1;
                for (int i = 0; i < userList.Count; i++)
                {
                    if (nm == userList[i].username)
                    {
                        //check filename exists or not
                        for (int k = 0; k < userList[i].file.Count; k++)
                        {
                            if (userList[i].file[k].filename == fName)
                            {
                                fName = tempName + "(" + count.ToString() + ")" + extension;
                                k     = -1;
                                count++;
                            }
                        }
                    }
                }

                BinaryWriter write = new BinaryWriter(File.Open(path + "/" + fName, FileMode.Append));
                write.Write(buffer, 4 + fNameLen, size - 4 - fNameLen);
                write.Close();

                DateTime d = DateTime.Now;
                int      s = size - 4 - fNameLen;
                string   fsize;
                if (s > 1000000)
                {
                    float fls = s / (float)1000000;
                    fsize = Convert.ToString(fls) + " MB";
                    string.Format("{0:N2}", fsize);
                }
                else if (s > 1000)
                {
                    float fls = s / (float)1000;
                    fsize = Convert.ToString(fls) + " KB";
                    string.Format("{0:N2}", fsize);
                }
                else
                {
                    fsize = Convert.ToString(s) + " KB";
                }

                files newFile = new files(fName, d.ToString(), fsize);

                for (int i = 0; i < userList.Count; i++)
                {
                    if (nm == userList[i].username)
                    {
                        userList[i].file.Add(newFile);
                        i = userList.Count;
                    }
                }
                boxLog.Items.Add("Heyy " + nm + "'s file is received:)");
            }
            catch
            {
                boxLog.Items.Add(nm + "'s file couldn't received:(");
            }
        }
Example #34
0
 /// <summary>
 /// Invoked when <see cref="ToEntity"/> operation is about to return.
 /// </summary>
 /// <param name="entity"><see cref="files"/> converted from <see cref="filesDTO"/>.</param>
 static partial void OnEntity(this filesDTO dto, files entity);
Example #35
0
 Write(xmlWriter, project, files, module);
Example #36
0
        private void Accept()
        {
            while (accept)
            {
                try
                {
                    socketList.Add(sck.Accept());
                    byte[] name = new byte[64];
                    socketList[socketList.Count - 1].Receive(name);
                    String userName = Encoding.Default.GetString(name);
                    userName = userName.Substring(4, userName.IndexOf("\0") - 4);

                    if (nameList.Contains(userName))
                    {
                        nameList.Add(userName);
                        genericSend(rejected, socketList[socketList.Count - 1]);

                        socketList[socketList.Count - 1].Close();
                        socketList.RemoveAt(socketList.Count - 1);
                    }
                    else
                    {
                        string upath = System.IO.Path.Combine(serverFolder, userName);
                        System.IO.Directory.CreateDirectory(upath);

                        string str     = userName + " connected to the server";
                        user   newUser = new user(userName, upath);

                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(upath);
                        // Get the root directory and print out some information about it.
                        //System.IO.DirectoryInfo dirInfo = di.RootDirectory;

                        // Get the files in the directory and print out some information about them.
                        System.IO.FileInfo[] fileNames = di.GetFiles("*.*");

                        foreach (System.IO.FileInfo fi in fileNames)
                        {
                            files f = new files(fi.Name, fi.LastAccessTime.ToString(), fi.Length.ToString());
                            newUser.file.Add(f);
                        }
                        userList.Add(newUser);

                        boxLog.Items.Add(str);
                        nameList.Add(userName);
                        boxName.Items.Add(userName);

                        thrReceive = new Thread(new ThreadStart(genericReceive));
                        thrReceive.Start();
                    }
                }
                catch (Exception ex)
                {
                    if (terminating)
                    {
                        accept = false;
                    }
                    else
                    {
                        boxLog.Items.Add("Listening socket has stopped working...");
                    }
                }
            }
        }
Example #37
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid && Profile.Status > 1)
        {
            //If File has been uploaded
            string newfilepath = "";
            bool fileOK = false;
            string path = Server.MapPath("~/Files/");
            if (FileUpload1.HasFile)
            {
                string filePath = FileUpload1.FileName;
                if (filePath.EndsWith(".doc") || filePath.EndsWith(".docx") || filePath.EndsWith(".pdf"))
                {
                    double fileSize = FileUpload1.FileBytes.Length;
                    double fileSizeInMB = fileSize / (1024 * 1024);
                    if (fileSizeInMB < 20)
                    {
                        fileOK = true;
                    }
                }
            }

            if (fileOK)
            {
                try
                {
                    newfilepath = path + FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(newfilepath);
                    FileUploadedLabel.Text = FileUpload1.FileName;
                }
                catch (Exception ex)
                {
                }
            }

            using (InquiriesDataContext inquiryDb = new InquiriesDataContext())
            {
                //If existing inquiry ist updated
                if (Request.QueryString["iid"] != "" && Request.QueryString["iid"] != null)
                {
                    int inquiryid;
                    Int32.TryParse(Request.QueryString["iid"], out inquiryid);

                    inquiries newInquiry = inquiryDb.inquiries.Single(p => p.iid == inquiryid);

                    //Check if user has access
                    MembershipUser myUser = Membership.GetUser();
                    if (newInquiry.uid == myUser.ProviderUserKey.ToString())
                    {
                        newInquiry.title = TitleTextBox.Text;
                        newInquiry.description = DescriptionTextBox.Text;
                        newInquiry.interest_start = DateTime.ParseExact(InterestPhaseTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        newInquiry.interest_end = DateTime.ParseExact(InterestPhaseEndTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        newInquiry.updated = DateTime.Now;

                        //New file uploaded
                        if (newfilepath != "")
                        {
						  files newfile = new files();
                          newfile.filename = FileUpload1.FileName;
                          newfile.filepath = newfilepath;
                          newfile.filesize = FileUpload1.FileBytes.Length;
                          newfile.created = DateTime.Now;

                          newfile.inquiries.Add(newInquiry);
                        }
                    }

                    //If already in proposal phase let users change proposal dates
                    if (newInquiry.status == 2)
                    {
                        newInquiry.proposal_start = DateTime.ParseExact(ProposalStartTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                        newInquiry.proposal_end = DateTime.ParseExact(ProposalEndTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    }

                    inquiryDb.SubmitChanges();

                    //Send update webservice request
                    Dictionary<string, dynamic> args = new Dictionary<string, dynamic>();
                    args.Add("method", "update.inquiry");
                    args.Add("iid", newInquiry.iid);
                    args.Add("uid", newInquiry.uid);
                    args.Add("companyname", Profile.CompanyName);
                    args.Add("title", newInquiry.title);
                    args.Add("description", newInquiry.description);
					if(newInquiry.files != null) {
                      args.Add("filepath", newInquiry.files.filepath);
					}

                    //Convert datetime to unix timestamp
                    DateTime unixStart = new DateTime(1970, 1, 1);

                    if (newInquiry.interest_start != null)
                    {
                        TimeSpan span = new TimeSpan(newInquiry.interest_start.Value.Ticks - unixStart.Ticks);
                        args.Add("interest_start", Convert.ToInt32(span.TotalSeconds));
                    }
                    else
                    {
                        args.Add("interest_start", "");
                    }

                    if (newInquiry.interest_end != null)
                    {
                        TimeSpan span2 = new TimeSpan(newInquiry.interest_end.Value.Ticks - unixStart.Ticks);
                        args.Add("interest_end", Convert.ToInt32(span2.TotalSeconds));
                    }
                    else
                    {
                        args.Add("interest_end", "");
                    }

                    if (newInquiry.proposal_start != null)
                    {
                        TimeSpan span3 = new TimeSpan(newInquiry.proposal_start.Value.Ticks - unixStart.Ticks);
                        args.Add("proposal_start", Convert.ToInt32(span3.TotalSeconds));
                    }
                    else
                    {
                        args.Add("proposal_start", "");
                    }

                    if (newInquiry.proposal_end != null)
                    {
                        TimeSpan span4 = new TimeSpan(newInquiry.proposal_end.Value.Ticks - unixStart.Ticks);
                        args.Add("proposal_end", Convert.ToInt32(span4.TotalSeconds));
                    }
                    else
                    {
                        args.Add("proposal_end", "");
                    }

                    if (newInquiry.inquiry_end != null)
                    {
                        TimeSpan span5 = new TimeSpan(newInquiry.inquiry_end.Value.Ticks - unixStart.Ticks);
                        args.Add("inqiry_end", Convert.ToInt32(span5.TotalSeconds));
                    }
                    else
                    {
                        args.Add("inquiry_end", "");
                    }

                    WebRequestHandler.load(args);

                    StatusLabel.Visible = true;
                    StatusLabel.Text = "Inquiry updated";
                }
                //If new inquiry is created
                else
                {
                    inquiries myInquiry = new inquiries();
                    myInquiry.title = TitleTextBox.Text;
                    myInquiry.description = DescriptionTextBox.Text;

                    DateTime intereststart;
                    myInquiry.interest_start = intereststart = DateTime.ParseExact(InterestPhaseTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);

                    DateTime interestend;
                    myInquiry.interest_end = interestend = DateTime.ParseExact(InterestPhaseEndTextBox.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);

                    myInquiry.created = myInquiry.updated = DateTime.Today;

                    MembershipUser myUser = Membership.GetUser();
                    myInquiry.uid = myUser.ProviderUserKey.ToString();
                    myInquiry.status = 1;

                    //New file uploaded
                    if (newfilepath != "")
                    {
                        files newfile = new files();
                        newfile.filename = FileUpload1.FileName;
                        newfile.filepath = newfilepath;
                        newfile.filesize = FileUpload1.FileBytes.Length;
                        newfile.created = DateTime.Now;

                        newfile.inquiries.Add(myInquiry);
                    }

                    inquiryDb.inquiries.InsertOnSubmit(myInquiry);
                    inquiryDb.SubmitChanges();

                    Dictionary<string, dynamic> args = new Dictionary<string, dynamic>();
                    args.Add("method", "send.inquiry");
                    args.Add("iid", myInquiry.iid);
                    args.Add("uid", myInquiry.uid);
                    args.Add("companyname", Profile.CompanyName);
                    args.Add("title", myInquiry.title);
                    args.Add("description", myInquiry.description);
                    args.Add("status", myInquiry.status);
                    if (newfilepath != "")
                    {
                        args.Add("filepath", newfilepath);
                    }

                    //Convert datetime to unix timestamp
                    DateTime unixStart = new DateTime(1970, 1, 1);

                    TimeSpan span = new TimeSpan(intereststart.Ticks - unixStart.Ticks);
                    args.Add("interest_start", Convert.ToInt32(span.TotalSeconds));

                    TimeSpan span2 = new TimeSpan(interestend.Ticks - unixStart.Ticks);
                    args.Add("interest_end", Convert.ToInt32(span2.TotalSeconds));

                    WebRequestHandler.load(args);
                    Response.Redirect("InquiryOverview.aspx");
                }

                //Server.Transfer("InquiryOverview.aspx", false);
            }
        }
    }
        private void uploadImagem(highlights consulta, IEnumerable <HttpPostedFileBase> files, string page)
        {
            var ultimoitem2 = new files();
            var consulta2   = new files();

            foreach (var file in files)
            {
                if (file != null)
                {
                    var consultaOrdem2 = (from ev in db.files where ev.content_id == consulta.id && ev.reference == page orderby ev.position ascending select ev).ToList();

                    if (consultaOrdem2.Count() > 0)
                    {
                        ultimoitem2        = consultaOrdem2[(consultaOrdem2.Count()) - 1];
                        consulta2.position = ultimoitem2.position + 1;
                    }
                    else
                    {
                        consulta2.position = 1;
                    }

                    int id = Convert.ToInt32(consulta.id);
                    //nome do arquivo original
                    var fileName = Path.GetFileName(file.FileName);

                    //atribuicao da extensão do arquivo (.jpg / .gif) na variavel
                    var extensao = Path.GetExtension(fileName);

                    //geracao de numeros randômicos que serao o novo nome do arquivo
                    Random randNum = new Random();
                    var    random  = randNum.Next().ToString();

                    //mapeamento do caminho absoluto onde ficarão os arquivos
                    string dir = (Server.MapPath("~/uploads/"));

                    //verifica se o diretorio referente ao determinado conteudo existe. caso não exista, cria o diretorio.
                    if (System.IO.Directory.Exists(dir) == false)
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }

                    var path = Path.Combine(Server.MapPath("~/uploads/"), random + extensao);
                    file.SaveAs(path);
                    consulta2.filename   = random + extensao;
                    consulta2.status     = 1;
                    consulta2.content_id = consulta.id;
                    consulta2.updated    = DateTime.Now;
                    consulta2.created    = DateTime.Now;
                    consulta2.reference  = page;
                    //consulta2.tipo = "imagem";
                    try
                    {
                        db.files.Add(consulta2);
                        db.SaveChanges();
                    }
                    catch
                    {
                    }
                }
            }
        }
Example #39
0
 /// <summary>
 /// Invoked when <see cref="ToDTO"/> operation is about to return.
 /// </summary>
 /// <param name="dto"><see cref="filesDTO"/> converted from <see cref="files"/>.</param>
 static partial void OnDTO(this files entity, filesDTO dto);