예제 #1
0
        public AppResponse <SftpFile> getRemoteFileInfo(string remoteDir, string remoteFileName)
        {
            AppResponse <SftpFile> resp = new AppResponse <SftpFile>();

            try
            {
                sftp.ConnectionInfo.Timeout = TimeSpan.FromMinutes(30);
                sftp.Connect();
                SftpFile remoteFile = sftp.ListDirectory(remoteDir).Where(x => x.Name == remoteFileName).FirstOrDefault();
                if (remoteFile != null)
                {
                    resp.SetSuccess();
                    resp.setData(remoteFile);
                }
                else
                {
                    resp.SetFailure("File not found");
                    resp.responseCode = AppResponse <SftpFile> .NOT_FOUND;
                }
            }
            catch (Exception ex)
            {
                resp.SetFailure(ex.Message);
            }
            finally
            {
                sftp.Disconnect();
            }
            return(resp);
        }
예제 #2
0
        private AppResponse <List <string> > uploadFiles(HttpPostedFileBase[] files)
        {
            AppResponse <List <string> > resp = new AppResponse <List <string> >();

            //Uploading files
            if (files != null)
            {
                try
                {
                    List <string> filesToUpload = new List <string>();
                    foreach (var f in files)
                    {
                        if (f != null)
                        {
                            Regex  rgx       = new Regex("[^a-zA-Z0-9 -_.]");
                            var    uploadDir = localFileDir + "\\";
                            string fullPath  = Server.MapPath(localFileDir);
                            if (!Directory.Exists(fullPath))
                            {
                                Directory.CreateDirectory(fullPath);
                            }

                            var filePathTemp = Path.Combine(fullPath, f.FileName);
                            var fileNameNoEx = rgx.Replace(Path.GetFileNameWithoutExtension(filePathTemp), "");

                            var    fileEx      = Path.GetExtension(filePathTemp);
                            string fileNameInc = "";
                            int    inc         = 0;
                            var    filePath    = Path.Combine(fullPath, fileNameNoEx + fileNameInc + fileEx);
                            string fName       = fileNameNoEx + fileNameInc + fileEx;

                            while (System.IO.File.Exists(filePath))
                            {
                                inc++;
                                fileNameInc = inc.ToString();
                                filePath    = Path.Combine(fullPath, fileNameNoEx + fileNameInc + fileEx);
                                fName       = fileNameNoEx + fileNameInc + fileEx;
                            }
                            f.SaveAs(filePath);
                            filesToUpload.Add(fName);
                        }
                    }

                    resp.SetSuccess();
                    resp.setData(filesToUpload);
                }
                catch (Exception ex)
                {
                    resp.SetFailure(ex.Message);
                }
            }

            return(resp);
        }
예제 #3
0
        public JsonResult Agregar(string data)
        {
            var lista = JsonConvert.DeserializeObject <List <IndicadorDetalleLogic> >(data);

            if (Session[SessionIndicadorDetalle] != null)
            {
                listaIndicadorDetalleSession = (List <IndicadorDetalleLogic>)Session[SessionIndicadorDetalle];
            }

            if (Session[SessionContadorIndicadorDet] != null)
            {
                contador = (int)Session[SessionContadorIndicadorDet];
            }

            lista[0].Item = contador + 1;
            listaIndicadorDetalleSession.AddRange(lista);

            Session[SessionIndicadorDetalle]     = listaIndicadorDetalleSession;
            Session[SessionContadorIndicadorDet] = contador + 1;

            appResponse.SetSuccess(string.Empty);
            appResponse.SetError(string.Empty);
            return(Json(appResponse, JsonRequestBehavior.AllowGet));
        }
예제 #4
0
        public JsonResult Agregar(string data)
        {
            var lista = JsonConvert.DeserializeObject <List <AlineamientoEstrategicoLogic> >(data);

            if (Session[SessionAlineamientos] != null)
            {
                listaAlineamientoSession = (List <AlineamientoEstrategicoLogic>)Session[SessionAlineamientos];
            }

            if (Session[SessionContadorAlineamiento] != null)
            {
                contador = (int)Session[SessionContadorAlineamiento];
            }

            lista[0].Item = contador + 1;
            listaAlineamientoSession.AddRange(lista);

            Session[SessionAlineamientos]        = listaAlineamientoSession;
            Session[SessionContadorAlineamiento] = contador + 1;

            appResponse.SetSuccess(string.Empty);
            appResponse.SetError(string.Empty);
            return(Json(appResponse, JsonRequestBehavior.AllowGet));
        }
예제 #5
0
        public AppResponse <List <VMDirectoryItem> > getDirectoryContents(string remoteDirectory)
        {
            AppResponse <List <VMDirectoryItem> > resp = new AppResponse <List <VMDirectoryItem> >();

            try
            {
                sftp.ConnectionInfo.Timeout = TimeSpan.FromMinutes(30);
                sftp.Connect();
                sftp.ChangeDirectory("/");

                List <VMDirectoryItem> items = new List <VMDirectoryItem>();
                var dirObjects = sftp.ListDirectory(remoteDirectory);

                foreach (var dir in dirObjects)
                {
                    string d = dir.FullName;
                    if (!d.EndsWith("/.") && !d.Contains(".."))
                    {
                        string typeCode     = VMDirectoryItemType.FILE;
                        int    typeSequence = 1;
                        if (dir.IsDirectory)
                        {
                            typeCode     = VMDirectoryItemType.DIRECTORY;
                            typeSequence = 0;
                        }
                        string[] parts = d.Split('/');
                        string   val   = parts[parts.Length - 1];
                        items.Add(new VMDirectoryItem(dir, remoteDirectory, typeCode, typeSequence));
                    }
                }
                resp.SetSuccess();
                resp.setData(items);
            }
            catch (Exception ex)
            {
                resp.SetFailure(ex.Message);
            }

            return(resp);
        }
예제 #6
0
        public JsonResult FetchFile(int id, string remoteDir, string fileName)
        {
            AppResponse <String> resp = new AppResponse <String>();
            FTPK_FTPs            site = dbContext.FTPK_FTPs.Where(x => x.ID == id).FirstOrDefault();

            if (site == null)
            {
                resp.SetFailure("Invalid FTP Site");
                return(Json(resp));
            }

            if (!SecurityManager.canRead(site.ID))
            {
                resp.SetFailure("Unauthorized");
                return(Json(resp));
            }


            string downloadPath = Server.MapPath(localFileDir);

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }
            DirectoryInfo downloadDir   = new DirectoryInfo(downloadPath);
            string        localFilePath = Path.Combine(downloadPath, fileName);

            try
            {
                bool useCacheFile           = false;
                SftpClientWrapper sftp      = initSFTP(site);
                FileInfo          localFile = downloadDir.GetFiles().Where(x => x.Name == fileName).FirstOrDefault();
                if (localFile != null)
                {
                    AppResponse <SftpFile> fileResp = sftp.getRemoteFileInfo(remoteDir, fileName);
                    if (fileResp.success)
                    {
                        SftpFile remoteFile = fileResp.getData();
                        if (remoteFile.Length == localFile.Length && remoteFile.LastWriteTime <= localFile.LastWriteTime)
                        {
                            useCacheFile = true;
                            resp.SetSuccess();
                        }
                        else
                        {
                            localFile.Delete();
                        }
                    }
                    else
                    {
                        localFile.Delete();
                    }
                }

                if (!useCacheFile)
                {
                    bool res = sftp.downloadFile(remoteDir, fileName, downloadDir);
                    if (res)
                    {
                        resp.SetSuccess();
                    }
                    else
                    {
                        resp.SetFailure("Failed to download file. Please try again later.");
                    }
                }
            }
            catch (Exception ex)
            {
                resp.SetFailure(ex.Message);
            }
            finally
            {
                //kick off cache cleanup
                Task.Factory.StartNew(this.CleanUpCache);
            }
            return(Json(resp));
        }
예제 #7
0
        public ActionResult Upload(VMUpload model)
        {
            if (model == null)
            {
                return(HttpNotFound());
            }

            if (model.path == null)
            {
                model.path = "";
            }

            AppResponse <List <string> > resp = uploadFiles(model.files);

            if (!resp.success)
            {
                ModelState.AddModelError("files", resp.message);
                return(View(model));
            }

            List <string> filesToUpload = resp.getData();

            FTPK_FTPs site = dbContext.FTPK_FTPs.Where(x => x.ID == model.id).FirstOrDefault();

            if (site == null)
            {
                return(HttpNotFound());
            }

            if (!SecurityManager.canUpload(site.ID))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized));
            }

            SftpClientWrapper sftp = initSFTP(site);

            string        fullPath = Server.MapPath(localFileDir);
            DirectoryInfo localDir = new DirectoryInfo(fullPath);

            int failedCnt = 0;

            foreach (string fName in filesToUpload)
            {
                try
                {
                    FTPK_Logs log = new FTPK_Logs();
                    log.SiteID   = model.id;
                    log.Action   = ACTION_UPLOAD;
                    log.FileName = fName;
                    log.Path     = model.path;
                    log.UserID   = SecurityManager.getUserID();
                    log.LogDate  = DateTime.Now;
                    dbContext.FTPK_Logs.Add(log);

                    dbContext.SaveChanges();

                    resp.SetSuccess();
                }
                catch (Exception ex)
                {
                    resp.SetFailure(ex.Message);
                }

                bool success = sftp.uploadFile(model.path, fName, localDir);
                if (!success)
                {
                    ModelState.AddModelError("files", fName + " failed to upload. Please retry this file.");
                    failedCnt++;
                }
            }
            AppResponse <Object> mResp = new AppResponse <object>();

            if (!ModelState.IsValid)
            {
                mResp.SetFailure(failedCnt + " of " + filesToUpload.Count() + " file(s) uploaded successfully!");
            }
            else
            {
                mResp.SetSuccess();
            }


            model.files    = null;
            model.response = mResp;
            return(View(model));
        }
예제 #8
0
        public ActionResult Download(int?id, string remoteDir, string fileName)
        {
            AppResponse <Object> resp = new AppResponse <object>();

            if (remoteDir == null)
            {
                remoteDir = "";
            }

            if (!id.HasValue)
            {
                return(RedirectToAction("Index"));
            }

            if (fileName == "")
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            string siteName = "";

            try
            {
                FTPK_FTPs site = dbContext.FTPK_FTPs.Where(x => x.ID == id.Value).FirstOrDefault();

                if (site == null)
                {
                    return(HttpNotFound("No FTP Site with ID '" + id.Value + ", found"));
                }

                if (!SecurityManager.canRead(site.ID))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized));
                }

                siteName = site.DisplayName;

                FTPK_Logs log = new FTPK_Logs();
                log.SiteID   = id.Value;
                log.Action   = ACTION_DOWNLOAD;
                log.FileName = fileName;
                log.Path     = remoteDir;
                log.UserID   = SecurityManager.getUserID();
                log.LogDate  = DateTime.Now;
                dbContext.FTPK_Logs.Add(log);

                dbContext.SaveChanges();

                resp.SetSuccess();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            catch (Exception ex)
            {
                resp.SetFailure(ex.Message);
            }
            VMDownload model = new VMDownload(id.Value, remoteDir, fileName, siteName);

            model.response = resp;
            return(View(model));
        }