public int CompressFile(FileModel sendFile)
        {
            try
            {
                string     fileName            = sendFile.OriginalFileName;
                string     file_path           = environment.ContentRootPath + $"\\Data\\temporal\\" + fileName;
                string     file_compressedpath = sendFile.AbsolutePhat;
                FileManage _file = new FileManage()
                {
                    OriginalFileName = fileName, CompressedFileName = sendFile.RegisterFileName, CompressedFilePath = file_compressedpath, DateOfCompression = Convert.ToDateTime(DateTime.Now.ToShortTimeString())
                };

                //Compress the file previously saved
                _file.CompressFile(file_path, fileName);

                //Write on log file the compression result
                _file.WriteCompression(_file);

                //Delete the original file
                _file.DeleteFile(file_path);

                return(1);
            }
            catch (Exception)
            {
                return(-1);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 插入一条数据
        /// </summary>
        /// <returns>"true"/"false"</returns>
        private string doInsert()
        {
            try
            {
                string filename = IRequest.GetFormString("File_Name");

                string        filecontent     = Server.UrlDecode(IRequest.GetFormString("File_Content"));//.Replace(" ", "&nbsp;").Replace("\r\n", "<br/>"));//Replace("&lt;", "<").Replace("&quot;", "\"").Replace("&gt;", ">").
                string        langflag        = IRequest.GetFormString("langflag");
                string        TemplatePathStr = Utils.GetMapPath(ConfigurationManager.AppSettings["TempLatePath"] + langflag);
                DirectoryInfo dirinfo         = new DirectoryInfo(TemplatePathStr);
                FileInfo[]    files           = dirinfo.GetFiles();
                foreach (FileInfo tempfile in files)
                {
                    if (tempfile.Name.Split('.')[0].Equals(filename.Split('.')[0]))
                    {
                        //  Jscript.Alert("当前目录存在同名的文件!");
                        return("false");
                    }
                }

                FileStream fs = File.Create(TemplatePathStr + "\\" + filename);
                fs.Close();
                FileManage.SaveTextFile(TemplatePathStr + "\\" + filename, filecontent, "utf-8");
                //   FileUtil.WriteText(TemplatePathStr + "\\" + filename, filecontent);

                return("true");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        public ActionResult DecompressFile([FromForm] IFormFile file)
        {
            try
            {
                string file_path        = environment.ContentRootPath + $"\\Data\\temporal\\{file.FileName}";
                string output_file_path = environment.ContentRootPath + $"\\Data\\compressions\\{file.FileName}";

                FileManage _file = new FileManage();

                //Save the file in the server
                _file.SaveFile(file, file_path);

                //Get the original file name
                string file_name = _file.GetOriginalName(environment.ContentRootPath, file.FileName);

                //Decompress the file previosly saved
                _file.DecompressFile(file_path, file_name);


                //Delete the original file
                _file.DeleteFile(file_path);

                string     path   = environment.ContentRootPath + $"\\Data\\decompressions\\{file_name}";
                FileStream result = new FileStream(path, FileMode.Open);
                return(File(result, "text/plain", file_name));
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// 编辑一条数据
 /// </summary>
 /// <returns>"true"/"false"</returns>
 private string doUpdate()
 {
     try
     {
         string        filename        = IRequest.GetFormString("File_Name");
         string        filecontent     = Server.UrlDecode(IRequest.GetFormString("File_Content"));
         string        langflag        = IRequest.GetFormString("langflag");
         string        TemplatePathStr = Utils.GetMapPath(ConfigurationManager.AppSettings["TempLatePath"] + langflag);
         DirectoryInfo dirinfo         = new DirectoryInfo(TemplatePathStr);
         FileInfo[]    files           = dirinfo.GetFiles();
         foreach (FileInfo tempfile in files)
         {
             if (tempfile.Name.Equals(filename))
             {
                 string TempFileContent = FileManage.ReadTextFile(tempfile.FullName);//.Replace("\"", "&quot;").Replace(Environment.NewLine, "");
                 FileManage.SaveTextFile(tempfile.FullName, filecontent, "utf-8");
                 //  FileUtil.WriteText(tempfile.FullName, filecontent);
                 break;
             }
         }
         return("true");
     }
     catch
     {
         return("false");
     }
 }
Ejemplo n.º 5
0
        public IHttpActionResult RenameFile(string fileId, [FromBody] string newFileName)
        {
            string     userId      = HttpContext.Current.User.Identity.Name;
            FileManage renamedFile = null;

            using (var db = new WebDiskDBEntities())
            {
                renamedFile = db.FileManage.Where(x => x.OwnerId == userId && x.FileId == fileId).SingleOrDefault();

                //실제 파일 이름도 변경하기
                string folderPath     = Path.Combine(renamedFile.ServerPath, renamedFile.OwnerId, renamedFile.RealPath);
                string sourceFilePath = Path.Combine(folderPath, renamedFile.FileName + "." + renamedFile.FileExtension);
                string targetFilePath = Path.Combine(folderPath, newFileName + "." + renamedFile.FileExtension);


                if (renamedFile != null)
                {
                    if (!File.Exists(targetFilePath))
                    {
                        File.Move(sourceFilePath, targetFilePath);
                    }

                    renamedFile.FileName     = newFileName;
                    renamedFile.LastModified = DateTime.Now;
                    db.SaveChanges();
                }
                else
                {
                    return(NotFound());
                }
            }
            return(Ok(renamedFile));
        }
Ejemplo n.º 6
0
        //public static void getListOfIIS()
        //{
        //    this.listBox1.Items.Clear();
        //    string StateStr = "";
        //    for (int i = 0; i < IISManager.Sites.Count; i++)
        //    {

        //        switch (IISManager.Sites[i].State)
        //        {
        //            case ObjectState.Started:
        //                {
        //                    StateStr = "正常"; break;
        //                }
        //            case ObjectState.Starting:
        //                {
        //                    StateStr = "正在启动"; break;
        //                }
        //            case ObjectState.Stopping:
        //                {
        //                    StateStr = "正在关闭"; break;
        //                }
        //            case ObjectState.Stopped:
        //                {
        //                    StateStr = "关闭"; break;
        //                }
        //        }
        //        this.listBox1.Items.Add(IISManager.Sites[i].Name + "【" + StateStr + "】");
        //    }
        //}
        #endregion

        #region 创建站点、绑定域名
        //public static void Creat(string[] args)
        //{
        //    Site site = serverManager.Sites.Add("site name", "http", "*:80:" + siteUrl, sitePath);
        //    mySite.ServerAutoStart = true;
        //    serverManager.CommitChanges();
        //}
        #endregion

        #region 站点权限设置
        //        Configuration config = serverManager.GetApplicationHostConfiguration();
        //        ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", sitename);
        //        anonymousAuthenticationSection["enabled"] = true;
        //anonymousAuthenticationSection["userName"] = @"IUSR_" + this.txt_No.Text.ToString();
        //anonymousAuthenticationSection["password"] = @"" + this.txt_password.Text.ToString();
        //serverManager.CommitChanges();
        #endregion

        #region 创建应用池
        //        ApplicationPool newPool = IISManager.ApplicationPools[appoolname];
        //if (newPool == null)
        //{
        //    IISManager.ApplicationPools.Add(appoolname);
        //    newPool = IISManager.ApplicationPools[appoolname];
        //    newPool.Name =appoolname;
        //    newPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
        //    newPool.ManagedRuntimeVersion = "v2.0";
        //}
        #endregion

        #region 站点应用池绑定
        //site.Applications["/"].ApplicationPoolName  = appoolName //此appoolname就是新的的引用池
        #endregion

        #region  追加域名
        public static bool AddHost(string siteName, string domain, int port = 80, string ip = "*")
        {
            if (string.IsNullOrWhiteSpace(siteName) || string.IsNullOrWhiteSpace(domain))
            {
                return(false);
            }

            try
            {
                Site              site     = serverManager.Sites[siteName];
                string            bindInfo = $"{ip}:{port}:{domain}";
                BindingCollection binds    = site.Bindings;
                if (binds.AllowsAdd && binds.All(xx => xx.BindingInformation != bindInfo))
                {
                    binds.Add(bindInfo, "http");
                }
                serverManager.CommitChanges();
                return(true);
            }
            catch (Exception ex)
            {
                FileManage.WriteText(new System.Text.StringBuilder(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + " YSWL.Common.IIS.IISWebsite.AddHost:" + ex.Message));
            }
            return(false);
        }
Ejemplo n.º 7
0
        public IHttpActionResult DeleteFileForever(string fileId)
        {
            string     userId      = HttpContext.Current.User.Identity.Name;
            FileManage deletedFile = null;

            using (var db = new WebDiskDBEntities())
            {
                deletedFile = db.FileManage.Where(x => x.OwnerId == userId && x.Trashed == true && x.FileId == fileId).SingleOrDefault();

                string fileName     = deletedFile.FileName + '.' + deletedFile.FileExtension;
                string fileFullPath = Path.Combine(deletedFile.ServerPath, deletedFile.OwnerId, deletedFile.RealPath, fileName);



                if (deletedFile != null)
                {
                    if (File.Exists(fileFullPath))
                    {
                        File.Delete(fileFullPath);
                    }
                    db.FileManage.Remove(deletedFile);
                    db.SaveChanges();
                }
                else
                {
                    return(NotFound());
                }
            }
            return(Ok(deletedFile));
        }
Ejemplo n.º 8
0
 /// <summary>
 /// 批量删除操作
 /// </summary>
 /// <returns></returns>
 private string doDelete()
 {
     try
     {
         string[]      filenames       = IRequest.GetQueryString("files").TrimStart(new char[] { ',' }).Split(new char[] { ',' });
         string        langflag        = IRequest.GetQueryString("langflag");
         string        TemplatePathStr = Utils.GetMapPath(ConfigurationManager.AppSettings["TempLatePath"] + langflag);
         DirectoryInfo dirinfo         = new DirectoryInfo(TemplatePathStr);
         FileInfo[]    files           = dirinfo.GetFiles();
         foreach (FileInfo tempfile in files)
         {
             foreach (string filename in filenames)
             {
                 if (tempfile.Name.Equals(filename))
                 {
                     FileManage.DeleteFileFolder(tempfile.FullName);
                     break;
                 }
             }
         }
         return("true");
     }
     catch
     {
         return("false");
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// lync状态设置
        /// </summary>
        private void StateSetting()
        {
            try
            {
                //获取本地个人用户存储信息
                LoginWindow.user = FileManage.Load_Entity <MeetingUser>(SpaceCodeEnterEntity.UserFilePath);
                //绑定本存储的用户信息
                this.txtUser.Text = LoginWindow.user.UserName;
                //登陆密码
                this.pwd.Password = LoginWindow.user.PassWord;
                //记住密码
                this.IsPwdRemmber = LoginWindow.user.IsPwdRemmber;
                //自动登陆
                this.IsAutoLogin = LoginWindow.user.IsAutoLogin;
                //登陆状态
                this.StateIndex = Convert.ToInt32(LoginWindow.user.State);
                //自动登陆(登陆窗体显示事件)
                this.ContentRendered += LoginWindow_ContentRendered;
                //编辑区域位置设置
                this.EditPanelMargin = new Thickness(0);

                this.InitializtionVisibility = vy.Collapsed;
                this.LoginPanelIsEnable      = true;
            }
            catch (Exception ex)
            {
                LogManage.WriteLog(this.GetType(), ex);
            }
            finally
            {
            }
        }
Ejemplo n.º 10
0
        public ActionResult EditCategory(UpdateArticleCategoryModel model, int id)
        {
            if (ModelState.IsValid)
            {
                var r = YunClient.Instance.Execute(new UpdateCategoryRequest
                {
                    Id          = id,
                    Name        = model.Title,
                    Display     = Request.Form["IsDisplay"].TryTo(0) == 1,
                    Image       = model.Image,
                    NewImage    = FileManage.GetFirstFile(),
                    Sort        = model.Sort,
                    ParentId    = model.ParentId,
                    Description = model.Description
                }, Token);

                if (r.Result)
                {
                    TempData["success"] = "已成功修改文章分类";
                    return(RedirectToAction("Category"));
                }
            }

            return(View(model));
        }
Ejemplo n.º 11
0
        public ActionResult AddCategory(AddArticleCategoryModel model, int id = 0)
        {
            if (ModelState.IsValid)
            {
                var r = YunClient.Instance.Execute(new AddCategoryRequest
                {
                    Name        = model.Title,
                    Display     = Request.Form["Display"].TryTo(0) == 1,
                    Image       = FileManage.GetFirstFile(),
                    Description = model.Description,
                    ParentId    = id
                }, Token);

                if (r.Result > 0)
                {
                    TempData["success"] = "已成功添加“" + model.Title + "” 分类";
                    return(RedirectToAction("Category"));
                }

                TempData["error"] = "添加失败,该分类已经存在";
            }


            return(View(model));
        }
Ejemplo n.º 12
0
        public ActionResult UpdateImageText(UpdateImageTextModel model, int id, int moduleId)
        {
            if (ModelState.IsValid)
            {
                var img = FileManage.UploadOneFile();
                var r   = YunClient.Instance.Execute(new UpdateSiteElementImageTextRequest
                {
                    Id        = id,
                    Title     = model.Title,
                    Display   = Request.Form["Display"].TryTo(0) == 1,
                    HyperLink = model.HyperLink,
                    Image     = string.IsNullOrEmpty(img) ? model.Image : img,
                    SortOrder = model.SortOrder,
                    ParentId  = model.ParentId
                }, Token);

                if (r.Result)
                {
                    ClearCache(moduleId);
                }

                return(Json(r.Result));
            }

            return(Json(false));
        }
Ejemplo n.º 13
0
        public ActionResult AddMultipleInfo(AddMultiPeInfoModel model, string moduleFlag)
        {
            if (ModelState.IsValid)
            {
                var r = YunClient.Instance.Execute(new AddSiteElementMultipeinfoRequest
                {
                    Title                = model.Title,
                    Display              = Request.Form["Display"].TryTo(0) == 1,
                    ModuleId             = model.CurrentModuleId,
                    HyperLink            = model.HyperLink,
                    AdditionalInfo       = model.AdditionalInfo,
                    SecondAdditionalInfo = model.SecondAdditionalInfo,
                    ThirdAdditionalInfo  = model.ThirdAdditionalInfo,
                    SortOrder            = model.SortOrder,
                    ParentId             = model.ParentId,
                    Thumb                = FileManage.UploadOneFile()
                }, Token);

                if (r.Result > 0)
                {
                    ClearCache(model.CurrentModuleId);
                }

                if (r.Result > 0)
                {
                    return(Json(r.Result));
                }
            }

            return(Json(false));
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 更新
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void MenuItemUpdate_OnClick(object sender, RoutedEventArgs e)
 {
     if (FileManage.IsUpdate())
     {
         FileManage.StartMainApplication();
     }
 }
Ejemplo n.º 15
0
        public ActionResult AddImageText(AddImageTextModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(false));
            }

            var r = YunClient.Instance.Execute(new AddSiteElementImageTextRequest
            {
                Title     = model.Title,
                Display   = Request.Form["Display"].TryTo(0) == 1,
                ModuleId  = model.CurrentModuleId,
                HyperLink = model.HyperLink,
                SortOrder = model.SortOrder,
                Thumb     = FileManage.UploadOneFile(),
                ParentId  = model.ParentId
            }, Token);

            if (r.Result > 0)
            {
                ClearCache(model.CurrentModuleId);
            }

            return(Json(r.Result));
        }
Ejemplo n.º 16
0
        public ActionResult UpdateModule(int id, FormCollection collection)
        {
            if (!collection["ModuleName"].IsEmpty())
            {
                var lognImg = FileManage.UploadOneFile();

                var r =
                    YunClient.Instance.Execute(
                        new UpdateSitePageModuleRequest
                {
                    Id          = id,
                    Name        = collection["ModuleName"].Trim(),
                    Remark      = collection["remark"],
                    ModuleThumb = lognImg != "" ? lognImg : collection["thumb"],
                    ModuleFlag  = collection["moduleflag"]
                }, Token);

                if (r.Result)
                {
                    ClearCache(id);
                }

                return(Json(r.Result));
            }

            return(Json(false));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// InputFileselect,mutiply
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_InPutFile_Click(object sender, EventArgs e)
        {
            this.listViewImage.GridLines = true;
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txt_ImageInput.Text = folderBrowserDialog1.SelectedPath;

                string sInputPath = this.txt_ImageInput.Text;
                //获取输入目录下所有压缩包文件名
                List <string> listFileName = FileManage.getAllFolderAndFiles(sInputPath, ".tar.gz");

                //将所有文件名绑定到LIST上显示在界面上
                foreach (var filename in listFileName)
                {
                    ListViewItem item = new ListViewItem()
                    {
                        Text = "  " + filename
                    };
                    this.listViewImage.Items.Add(item);
                }
            }

            //输出路径=输入路径
            this.txt_ImageOutPath.Text = this.txt_ImageInput.Text;
        }
Ejemplo n.º 18
0
        public string Get()
        {
            FileManage data = new FileManage();

            data.CreateDirectoriesForData(environment.ContentRootPath);
            return("CHAT");
        }
Ejemplo n.º 19
0
        public HttpResponseMessage DownloadFile(string fileId)
        {
            using (var db = new WebDiskDBEntities())
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

                FileManage file     = db.FileManage.Where(x => x.FileId == fileId).SingleOrDefault();
                string     fileName = file.FileName + '.' + file.FileExtension;
                string     filePath = Path.Combine(file.ServerPath, file.OwnerId, file.RealPath, file.FileName + '.' + file.FileExtension);

                if (!File.Exists(filePath))
                {
                    //만약 파일이 없으면 404 (Not Found) 에러
                    response.StatusCode   = HttpStatusCode.NotFound;
                    response.ReasonPhrase = string.Format("File not found: {0} .", fileName);
                    throw new HttpResponseException(response);
                }

                byte[] bytes = File.ReadAllBytes(filePath);

                response.Content = new ByteArrayContent(bytes);

                response.Content.Headers.ContentLength = bytes.LongLength;

                response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = fileName;

                response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName));
                return(response);
            }
        }
Ejemplo n.º 20
0
        public ActionResult UpdateMultipleInfo(UpdateMultipeInfoModel model, int id, int moduleId, string moduleFlag)
        {
            if (ModelState.IsValid)
            {
                var img = FileManage.UploadOneFile();

                var r = YunClient.Instance.Execute(new UpdateSiteElementMultipeinfoRequest
                {
                    Id                   = id,
                    Title                = model.Title,
                    Display              = Request.Form["Display"].TryTo(0) == 1,
                    Image                = string.IsNullOrEmpty(img) ? model.Image : img,
                    HyperLink            = model.HyperLink,
                    AdditionalInfo       = model.AdditionalInfo,
                    SecondAdditionalInfo = model.SecondAdditionalInfo,
                    ThirdAdditionalInfo  = model.ThirdAdditionalInfo,
                    SortOrder            = model.SortOrder,
                    ParentId             = model.ParentId
                }, Token);

                if (r.Result)
                {
                    ClearCache(moduleId);
                }
                return(Json(r.Result));
            }

            return(Json(false));
        }
Ejemplo n.º 21
0
        public ActionResult Add(AddArticleModel model)
        {
            if (ModelState.IsValid)
            {
                var r = YunClient.Instance.Execute(new AddArchiveRequest
                {
                    Title      = model.Title,
                    CategoryId = model.Categoryid.TryTo(0),
                    Detail     = model.Detail,
                    Sort       = model.Sort,
                    Tags       = model.Tags,
                    Status     = model.Status,
                    PostMeta   = string.IsNullOrEmpty(model.Summary) ? null : string.Format("summary:{0}", model.Summary),
                    Thumb      = FileManage.UploadOneFile(),
                    PostTime   = model.PostTime.ToUnix()
                }, Token);

                if (r.Result > 0)
                {
                    TempData["success"] = "新增文章成功";
                    return(RedirectToAction("Index"));
                }
            }

            TempData["error"] = "新增文章失败,请刷新后重试";
            return(View(model));
        }
        public ActionResult CompressFile([FromForm] IFormFile file, string name)
        {
            try
            {
                string     file_path           = environment.ContentRootPath + $"\\Data\\temporal\\{name}.txt";
                string     fileName            = file.FileName;
                string     file_compressedpath = environment.ContentRootPath + $"\\Data\\compressions\\{name}.lzw";
                FileManage _file = new FileManage()
                {
                    OriginalFileName = file.FileName, CompressedFileName = name + ".lzw", CompressedFilePath = file_compressedpath, DateOfCompression = Convert.ToDateTime(DateTime.Now.ToShortTimeString())
                };

                //Save the file in the server
                _file.SaveFile(file, file_path);

                //Compress the file previously saved
                _file.CompressFile(file_path);

                //Write on log file the compression result
                _file.WriteCompression(_file);

                //Delete the original file
                _file.DeleteFile(file_path);

                FileStream result = new FileStream(_file.CompressedFilePath, FileMode.Open);
                return(File(result, "text/plain", _file.CompressedFileName));
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
Ejemplo n.º 23
0
        public ActionResult Edit(UpdateArticleModel model, int id)
        {
            if (ModelState.IsValid)
            {
                var img = FileManage.UploadOneFile();

                var r = YunClient.Instance.Execute(new UpdateArchiveRequest
                {
                    Id         = id,
                    Title      = model.Title,
                    Detail     = model.Detail,
                    Sort       = model.Sort,
                    CategoryId = model.Categoryid.TryTo(0),
                    Tags       = model.Tags,
                    PostMeta   = string.IsNullOrEmpty(model.Summary) ? null : string.Format("summary:{0}", model.Summary),
                    Status     = model.Status,
                    Image      = string.IsNullOrEmpty(img) ? model.Image : img,
                    PostTime   = model.PostTime.ToUnix()
                }, Token);

                if (r.Result)
                {
                    TempData["success"] = "文章保存成功";
                    return(RedirectToAction("Index"));
                }
            }

            TempData["error"] = "修改文章失败";
            return(View(model));
        }
Ejemplo n.º 24
0
        public IHttpActionResult ChangeTrashedStatus(string fileId, [FromBody] bool trashed)
        {
            string     userId = HttpContext.Current.User.Identity.Name;
            FileManage file   = null;

            using (var db = new WebDiskDBEntities())
            {
                file = db.FileManage.Where(x => x.FileId == fileId && x.OwnerId == userId).SingleOrDefault();

                if (file != null)
                {
                    file.Trashed = trashed;
                    if (file.Starred == true)
                    {
                        file.Starred = false;                        //만약 삭제된 파일이 중요처리가 되어 있다면 false처리
                    }
                    file.LastModified = DateTime.Now;
                    db.SaveChanges();
                }
                else
                {
                    return(NotFound());
                }
            }

            return(Ok(file));
        }
        public string Index()
        {
            string     text = "\t\t\t- LAB 6 -\n\nKevin Romero 1047519\nJosé De León 1072619";
            FileManage data = new FileManage();

            data.CreateDirectoriesForData(environment.ContentRootPath);
            return(text);
        }
Ejemplo n.º 26
0
        public string DecompressFile(FileModel downloadFile)
        {
            FileManage _file = new FileManage();
            //Decompress the file previosly saved
            string file_name = _file.DecompressFile(downloadFile);
            string path      = environment.ContentRootPath + $"\\Data\\decompressions\\{file_name}";

            return(path);
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            var  fileType = context.Request["fileType"];//"更新";"覆盖"
            bool isUpdate = true;

            if (fileType == "覆盖")
            {
                isUpdate = false;
            }
            int    personId   = int.Parse(context.Session["id"].ToString());
            string personName = context.Session["UserName"].ToString();
            var    number     = context.Request.Form[0];
            var    processId  = int.Parse(context.Request.Form[1]);
            var    file       = context.Request.Files;

            using (JDJS_WMS_DB_USEREntities entities = new JDJS_WMS_DB_USEREntities())
            {
                var row = entities.JDJS_WMS_Order_Process_Info_Table.Where(r => r.ID == processId).FirstOrDefault();

                var programName = row.programName;

                PathInfo pathInfo = new PathInfo();
                var      root     = pathInfo.upLoadPath();

                var fileName = Path.GetFileNameWithoutExtension(programName) + Path.GetExtension(file[0].FileName);
                var path     = Path.Combine(root, number, "加工文件", fileName);
                var Folder   = Path.Combine(root, number, "加工文件");

                if (System.IO.File.Exists(path))
                {
                    if (!isUpdate)
                    {
                        System.IO.File.Delete(path);
                    }
                    else
                    {
                        int    i       = 1;
                        string oldPath = Path.Combine(root, number, "加工文件", Path.GetFileNameWithoutExtension(programName) + "-" + i.ToString() + Path.GetExtension(file[0].FileName));
                        while (System.IO.File.Exists(oldPath))
                        {
                            i++;
                            oldPath = Path.Combine(root, number, "加工文件", Path.GetFileNameWithoutExtension(programName) + "-" + i.ToString() + Path.GetExtension(file[0].FileName));
                        }
                        System.IO.File.Move(path, oldPath);
                    }
                }
                string str = "";
                FileManage.UpdateFileToDB(Convert.ToInt32(row.OrderID), row.ID, personId, personName, FileType.加工文件, isUpdate, ref str);
                file[0].SaveAs(path);
                row.programName = fileName;
                entities.SaveChanges();

                context.Response.Write(str);
            }
        }
Ejemplo n.º 28
0
            public static Task WriteGraphsAsync(IList <Graph> graphsList)
            {
                var tasks = new List <Task>();

                foreach (var graph in graphsList)
                {
                    tasks.Add(FileManage.WriteFileAsync($"graph_v{graph.VerticesCount}_exemplo{graph.Id}_a{graph.Edges.Count}", graph.Edges));
                }
                return(Task.WhenAll(tasks));
            }
Ejemplo n.º 29
0
        public ActionResult Download(string user, IFormCollection llaves)
        {
            string     pathDescompress = "";
            FileModel  fileModel       = new FileModel();
            FileManage fileManage      = new FileManage();

            fileModel.RegisterFileName = llaves["Register"];
            fileModel.RegisterFileName = fileModel.RegisterFileName.Trim();
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44389/api/");
                var responseTask = client.PostAsJsonAsync("file/download/", fileModel);
                responseTask.Wait();
                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var read = result.Content.ReadAsStringAsync();
                    read.Wait();
                    JsonSerializerOptions name_rule = new JsonSerializerOptions {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase, IgnoreNullValues = true
                    };
                    fileModel = JsonSerializer.Deserialize <FileModel>(read.Result, name_rule);
                    if (fileModel.Receiver == HttpContext.Session.GetString("UserName"))
                    {
                        fileModel.Status = 1;
                        responseTask     = client.PostAsJsonAsync("file/edit", fileModel);
                        responseTask.Wait();
                    }
                }
            }
            if (Path.GetExtension(fileModel.AbsolutePhat) == ".lzw")
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:44389/api/");
                    var responseTask = client.PostAsJsonAsync("file/decompress/", fileModel);
                    responseTask.Wait();

                    var result = responseTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        var read = result.Content.ReadAsStringAsync();
                        read.Wait();
                        pathDescompress = read.Result;
                    }
                }
            }
            else
            {
                pathDescompress = fileModel.AbsolutePhat;
            }
            var ext = Path.GetExtension(pathDescompress).ToLowerInvariant();

            return(File(fileManage.RetunFile(pathDescompress), fileManage.GetFileType(ext), fileModel.OriginalFileName));
        }
Ejemplo n.º 30
0
        public ActionResult AddPage(string name, string remark)
        {
            var r = YunClient.Instance.Execute(new AddSitePageRequest
            {
                Name   = name,
                Thumb  = FileManage.UploadOneFile(),
                Remark = remark,
            }, Token);

            return(Json(r.Result));
        }
        private void btn_ok_Click(object sender, EventArgs e)
        { 
            #region 输入与输出路径条件判断
            if (this.listViewImage.Items.Count <= 0)
            {
                MessageBox.Show("请选择输入影像!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (this.txt_ImageOutPath.Text.Equals(""))
            {
                MessageBox.Show("请选择输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string sImageOutPath = this.txt_ImageOutPath.Text.Trim();
            #endregion
            this.btn_ok.Enabled = false;

            #region 界面参数获取

            

            #endregion

            #region 执行合成
            this.progressBar.Visible = true;
            try
            {
                
                foreach (ListViewItem item in this.listViewImage.Items)
                {
                    string sFile = item.SubItems[0].Text.Trim();

                    if (!sFile.Contains("WFV") && !sFile.Contains("PMS") && !sFile.Contains("wfv") && !sFile.Contains("pms"))
                    {
                        MessageBox.Show("请输入包含传感器名称WFV或者PMS的影像!");
                        return;
                    }

                    string sFileName = Path.GetFileNameWithoutExtension(sFile);

                    string sSensorType = sFileName.Substring(4, 4);
                    sSensorType = sSensorType.ToUpper();
                    string[] BandCoefficients = new string[4];
                    switch (sSensorType)
                    {
                        case "PMS1":
                            BandCoefficients[0] = "*0.2082+4.6186";//第一波段定标系数
                            BandCoefficients[1] = "*0.1672+4.8768";//第二波段定标系数
                            BandCoefficients[2] = "*0.1748+4.8924";//第三波段定标系数
                            BandCoefficients[3] = "*0.1883-9.4771";//第四波段定标系数
                            break;
                        case "PMS2":
                            BandCoefficients[0] = "*0.2072+7.5348";//第一波段定标系数
                            BandCoefficients[1] = "*0.1776+3.9395";//第二波段定标系数
                            BandCoefficients[2] = "*0.177-1.7445";//第三波段定标系数
                            BandCoefficients[3] = "*0.1909-7.2053";//第四波段定标系数
                            break;
                        case "WFV1":
                            BandCoefficients[0] = "*0.1709-0.0039";//第一波段定标系数
                            BandCoefficients[1] = "*0.1398-0.0047";//第二波段定标系数
                            BandCoefficients[2] = "*0.1195-0.0030";//第三波段定标系数
                            BandCoefficients[3] = "*0.1338-0.0274";//第四波段定标系数
                            break;
                        case "WFV2":
                            BandCoefficients[0] = "*0.1588+5.5303";//第一波段定标系数
                            BandCoefficients[1] = "*0.1515-13.642";//第二波段定标系数
                            BandCoefficients[2] = "*0.1251-15.382";//第三波段定标系数
                            BandCoefficients[3] = "*0.1209-7.985";//第四波段定标系数
                            break;
                        case "WFV3":
                            BandCoefficients[0] = "*0.1556+12.28";//第一波段定标系数
                            BandCoefficients[1] = "*0.1700-7.9336";//第二波段定标系数
                            BandCoefficients[2] = "*0.1392-7.031";//第三波段定标系数
                            BandCoefficients[3] = "*0.1354-4.3578";//第四波段定标系数
                            break;
                        case "WFV4":
                            BandCoefficients[0] = "*0.1819+3.6469";//第一波段定标系数
                            BandCoefficients[1] = "*0.1762-13.54";//第二波段定标系数
                            BandCoefficients[2] = "*0.1463-10.998";//第三波段定标系数
                            BandCoefficients[3] = "*0.1522-12.142";//第四波段定标系数
                            break;
                    }
                    //默认为NDVI计算输入波段数组
                    int[] nBand = new int[1];
                    string sOutFilePath = sImageOutPath + "\\" + sFileName;
                    sOutFilePath = sOutFilePath.Replace("\\\\", "\\");

                    //波段组合文件名组合参数
                    string sLayerStackName = "";
                    List<string> filelist = new List<string>();

                    for (int i = 1; i <= 4; i++)
                    {
                        string strFormula = "b" + i + "*1" + BandCoefficients[i-1];//默认为NDVI计算公式
                        nBand[0] = i;
                        
                        string sOutFileName = sOutFilePath + "_Band" + i + ".tif";
                        //组装波段组合的输入参数名,所有文件名组成一个字符串,中间用*连接
                        sLayerStackName += sOutFileName + "*";
                        filelist.Add(Path.GetFileName(sOutFileName));
                        ProgressFunc pd = new ProgressFunc(this.ProgressBarInfo);
                        IntPtr pre = this.Handle;
                        int ire = 0;
                        char[] strInFileList = sFile.ToCharArray();
                        char[] strOutFileList = sOutFileName.ToCharArray();

                        ire = GdalAlgInterface.ImageCalculate(strInFileList, strOutFileList, strFormula, nBand, "GTiff", pd, pre);
                        //Console.Write(ire.ToString());
                    }

                    //波段叠加输入波段影像
                    sLayerStackName = sLayerStackName.Substring(0, sLayerStackName.Length - 1);
                    //波段组合后输出影像文件名
                    string sLayerStackResult = sImageOutPath + "\\" + sFileName+"_radiocorrect.tif";
                    


                    ProgressFunc pd2 = new ProgressFunc(this.ProgressBarInfo);
                    IntPtr pre2 = this.Handle;
                    int ire2 = 0;
                    char[] strLayerInFileList = sLayerStackName.ToCharArray();
                    char[] strLayerOutFileList = sLayerStackResult.ToCharArray();
                    ire2 = GdalAlgInterface.ImageLayerStack(strLayerInFileList, strLayerOutFileList, 0, false, "GTiff", pd2, pre2);
                    //MessageBox.Show("波段合成完毕", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.btn_ok.Enabled = true;
                    //this.btn_OpenOutPut.Visible = true;
                    //this.progressBar.Visible = false;
                    FileManage pFileManage = new FileManage();
                    pFileManage.DeteleFiles(filelist,sImageOutPath+"\\");

                }
                
            }
            catch (Exception ex)
            {
                this.progressBar.Visible = false;
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                MessageBox.Show("波段提取并辐射定标完毕", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btn_ok.Enabled = true;
                //this.btn_OpenOutPut.Visible = true;
                this.progressBar.Visible = false;
            }
            
            #endregion

        }